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,400
|
test_range.py
|
freeipa_freeipa/ipatests/test_webui/test_range.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/>.
"""
Range tests
"""
import pytest
import ipatests.test_webui.test_trust as trust_mod
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui.task_range import (
range_tasks,
LOCAL_ID_RANGE,
TRUSTED_ID_RANGE,
)
ENTITY = 'idrange'
PKEY = 'itest-range'
@pytest.mark.tier1
class test_range(range_tasks):
@pytest.fixture(autouse=True)
def range_setup(self, ui_driver_fsetup):
self.init_app()
self.get_shifts()
self.range_types = [LOCAL_ID_RANGE]
if self.has_trusts():
self.range_types.append(TRUSTED_ID_RANGE)
@screenshot
def test_crud(self):
"""
Basic CRUD: range
"""
self.basic_crud(ENTITY, self.get_data(PKEY), mod=False)
@screenshot
def test_mod(self):
"""
Test mod operating in a new range
"""
data = self.get_data(PKEY)
self.add_record(ENTITY, data)
self.navigate_to_record(PKEY)
# changes idrange and tries to save it
self.fill_fields(data['mod'], undo=True)
self.assert_facet_button_enabled('save')
self.facet_button_click('save')
self.wait_for_request(n=2)
# the user should not be able to change the ID allocation for
# IPA domain, as it's explained in https://pagure.io/freeipa/issue/4826
dialog = self.get_last_error_dialog()
assert ("can not be used to change ID allocation for local IPA domain"
in dialog.text)
self.dialog_button_click('cancel')
self.navigate_to_entity(ENTITY)
self.wait_for_request()
self.delete_record(PKEY)
@screenshot
def test_types(self):
"""
Test range types
Only 'local' and 'ipa-ad-trust' types are tested since range validation
made quite hard to test the other types:
- 'ipa-ad-trust-posix' can be tested only with subdomains.
- 'ipa-ad-winsync' and 'ipa-ipa-trust' and are not supported yet
https://fedorahosted.org/freeipa/ticket/4323
"""
pkey_local = 'itest-local'
pkey_ad = 'itest-ad'
column = 'iparangetype'
data = self.get_data(pkey_local)
self.add_record(ENTITY, data)
self.assert_record_value('local domain range', pkey_local, column)
if self.has_trusts():
trust_tasks = trust_mod.trust_tasks()
trust_data = trust_tasks.get_data()
self.add_record(trust_mod.ENTITY, trust_data)
domain = self.get_domain()
self.navigate_to_entity(ENTITY)
data = self.get_data(pkey_ad, range_type=TRUSTED_ID_RANGE,
domain=domain)
self.add_record(ENTITY, data, navigate=False)
self.assert_record_value('Active Directory domain range', pkey_ad,
column)
self.delete(trust_mod.ENTITY, [trust_data])
self.navigate_to_entity(ENTITY)
self.delete_record(pkey_ad)
self.delete_record(pkey_local)
@screenshot
def test_add_range_with_special_characters_in_name(self):
"""
Test creating ID Range with special characters in name
"""
data = self.get_data('itest-range-!@#$%^&*')
self.add_record(ENTITY, data, delete=True)
@screenshot
def test_add_range_with_existing_name(self):
"""
Test creating ID Range with existing range name
"""
for range_type in self.range_types:
pkey = 'itest-range-{}'.format(range_type)
data = self.get_data(pkey, range_type=range_type)
self.add_record(ENTITY, data)
self.add_record(ENTITY, data, navigate=False, negative=True,
pre_delete=False)
dialog = self.get_last_error_dialog()
try:
assert ('range with name "{}" already exists'.format(pkey)
in dialog.text)
finally:
self.delete_record(pkey)
@screenshot
def test_add_range_with_existing_base_id(self):
"""
Test creating ID Range with existing base ID
"""
for range_type in self.range_types:
pkey = 'itest-range-original'
form_data = self.get_add_form_data(pkey)
data = self.get_data(pkey, form_data=form_data)
form_data.range_type = range_type
duplicated_data = self.get_data(form_data=form_data)
self.add_record(ENTITY, data)
self.add_record(ENTITY, duplicated_data, navigate=False,
negative=True, pre_delete=False)
dialog = self.get_last_error_dialog()
try:
assert self.BASE_RANGE_OVERLAPS_ERROR in dialog.text
finally:
self.delete_record(pkey)
@screenshot
def test_add_range_overlaps_with_existing(self):
"""
Test creating ID Range with overlapping of existing range
"""
for range_type in self.range_types:
pkey = 'itest-range'
pkey_overlaps = 'itest-range-overlaps'
form_data = self.get_add_form_data(pkey)
data = self.get_data(pkey, form_data=form_data)
form_data_overlaps = self.get_add_form_data(
pkey_overlaps,
base_id=form_data.base_id + form_data.size - 1,
range_type=range_type
)
data_overlaps = self.get_data(form_data=form_data_overlaps)
self.add_record(ENTITY, data)
self.add_record(ENTITY, data_overlaps, navigate=False,
negative=True, pre_delete=False)
dialog = self.get_last_error_dialog()
try:
assert self.BASE_RANGE_OVERLAPS_ERROR in dialog.text
finally:
self.delete_record(pkey)
@screenshot
def test_add_range_with_overlapping_primary_and_secondary_rid(self):
"""
Test creating ID Range with overlapping of primary and secondary RID
"""
form_data = self.get_add_form_data(PKEY)
form_data.secondary_base_rid = form_data.base_rid
data = self.get_data(PKEY, form_data=form_data)
self.add_record(ENTITY, data, negative=True)
dialog = self.get_last_error_dialog()
try:
assert self.PRIMARY_AND_SECONDARY_RID_OVERLAP_ERROR in dialog.text
finally:
self.delete_record(PKEY)
@screenshot
def test_add_range_with_existing_base_rid(self):
"""
Test creating ID Range with existing primary RID base
"""
form_data = self.get_add_form_data(PKEY)
data = self.get_data(PKEY, form_data=form_data)
# Get RID base from previous form
duplicated_data = self.get_data(base_rid=form_data.base_rid)
self.add_record(ENTITY, data)
self.add_record(ENTITY, duplicated_data, navigate=False, negative=True,
pre_delete=False)
dialog = self.get_last_error_dialog()
try:
assert self.PRIMARY_RID_RANGE_OVERLAPS_ERROR in dialog.text
finally:
self.delete_record(PKEY)
@screenshot
def test_add_range_with_existing_secondary_rid(self):
"""
Test creating ID Range with existing secondary RID base
"""
form_data = self.get_add_form_data(PKEY)
data = self.get_data(PKEY, form_data=form_data)
# Get RID base from previous form
duplicated_data = self.get_data(
secondary_base_rid=form_data.secondary_base_rid
)
self.add_record(ENTITY, data)
self.add_record(ENTITY, duplicated_data, navigate=False, negative=True,
pre_delete=False)
dialog = self.get_last_error_dialog()
try:
assert self.SECONDARY_RID_RANGE_OVERLAPS_ERROR in dialog.text
finally:
self.delete_record(PKEY)
@screenshot
def test_add_range_without_rid(self):
"""
Test creating ID Range without giving rid-base or/and
secondary-rid-base values
"""
pkey = 'itest-range-without-rid'
# Without primary RID base
data = self.get_data(pkey, base_rid='')
self.add_record(ENTITY, data, negative=True)
try:
assert self.has_form_error('ipabaserid')
finally:
self.delete_record(pkey)
self.dialog_button_click('cancel')
# Without secondary RID base
data = self.get_data(pkey, secondary_base_rid='')
self.add_record(ENTITY, data, navigate=False, negative=True)
try:
assert self.has_form_error('ipasecondarybaserid')
finally:
self.delete_record(pkey)
self.dialog_button_click('cancel')
# Without primary and secondary RID bases
data = self.get_data(pkey, base_rid='', secondary_base_rid='')
self.add_record(ENTITY, data, navigate=False, negative=True)
try:
assert self.has_form_error('ipabaserid')
finally:
self.delete_record(pkey)
self.dialog_button_click('cancel')
@screenshot
def test_modify_range_with_invalid_or_missing_values(self):
"""
Test modification ID range with empty values of options
"""
cases = [
# Empty values
{
'base_id': '',
'base_rid': '',
'secondary_base_rid': '',
'size': '',
},
# Out of range
{'base_id': 2 ** 32},
{'size': 2 ** 32},
{'base_rid': 2 ** 32},
{'secondary_base_rid': 2 ** 32},
# Invalid value
{'base_id': 1.1},
{'size': 1.1},
{'base_rid': 1.1},
{'secondary_base_rid': 1.1},
]
data = self.get_data(PKEY)
self.add_record(ENTITY, data)
self.navigate_to_record(PKEY)
for values in cases:
form_data = self.get_mod_form_data(**values)
self.fill_fields(form_data.serialize(), undo=True)
self.assert_facet_button_enabled('save')
self.facet_button_click('save')
self.assert_notification(
type='danger',
assert_text='Input form contains invalid or missing values.'
)
self.close_notifications()
self.facet_button_click('revert')
self.delete_record(PKEY)
@screenshot
def test_delete_primary_local_range(self):
"""
Test deleting primary local ID range
"""
ipa_realm = self.config.get('ipa_realm')
pkey = '{}_id_range'.format(ipa_realm)
self.navigate_to_entity(ENTITY)
self.delete_record(pkey)
self.assert_last_error_dialog(
self.DELETE_PRIMARY_LOCAL_RANGE_ERROR,
details=True
)
| 11,806
|
Python
|
.py
| 299
| 29.468227
| 79
| 0.598217
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,401
|
ui_driver.py
|
freeipa_freeipa/ipatests/test_webui/ui_driver.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/>.
"""
Base class for UI integration tests.
Contains browser driver and common tasks.
"""
from __future__ import print_function, absolute_import
import os
import re
import time
from datetime import datetime
from functools import wraps
from pkg_resources import parse_version
from urllib.error import URLError
import pytest
try:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import InvalidElementStateException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.common.exceptions import UnexpectedAlertPresentException
from selenium.common.exceptions import WebDriverException
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.support.expected_conditions import alert_is_present
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.ui import Select
NO_SELENIUM = False
except ImportError:
NO_SELENIUM = True
try:
import yaml
NO_YAML = False
except ImportError:
NO_YAML = True
from ipaplatform.paths import paths
from ipatests.pytest_ipa.integration import tasks
ENV_MAP = {
'MASTER': 'ipa_server',
'ADMINID': 'ipa_admin',
'ADMINPW': 'ipa_password',
'DOMAIN': 'ipa_domain',
'IPA_REALM': 'ipa_realm',
'IPA_IP': 'ipa_ip',
'IPA_NO_CA': 'no_ca',
'IPA_NO_DNS': 'no_dns',
'IPA_HAS_TRUSTS': 'has_trusts',
'IPA_HAS_KRA': 'has_kra',
'IPA_HOST_CSR_PATH': 'host_csr_path',
'IPA_SERVICE_CSR_PATH': 'service_csr_path',
'AD_DOMAIN': 'ad_domain',
'AD_DC': 'ad_dc',
'AD_ADMIN': 'ad_admin',
'AD_PASSWORD': 'ad_password',
'AD_DC_IP': 'ad_dc_ip',
'TRUST_SECRET': 'trust_secret',
'SEL_TYPE': 'type',
'SEL_BROWSER': 'browser',
'SEL_HOST': 'host',
'FF_PROFILE': 'ff_profile',
}
DEFAULT_BROWSER = 'firefox'
DEFAULT_PORT = 4444
DEFAULT_TYPE = 'local'
def screenshot(fn):
"""
Decorator for saving screenshot on exception (test fail)
Should be applied on methods of UI_driver subclasses
"""
@wraps(fn)
def screenshot_wrapper(*args, **kwargs):
try:
return fn(*args, **kwargs)
except Exception:
self = args[0]
name = '%s_%s_%s' % (
datetime.now().isoformat(),
self.__class__.__name__,
fn.__name__)
self.take_screenshot(name)
raise
return screenshot_wrapper
def dismiss_unexpected_alert(fn):
"""
Temporary fix for UnexpectedAlertPresentException.
It is regression in Firefox 55
Fixed in Firefox 65:
https://bugzilla.mozilla.org/show_bug.cgi?id=1503015
"""
@wraps(fn)
def wrapped(*args, **kwargs):
self = args[0]
try:
return fn(*args, **kwargs)
except UnexpectedAlertPresentException:
if alert_is_present()(self.driver):
self.driver.switch_to.alert.dismiss()
# One retry is enough for now.
# But in the case of catching two alerts at the same time
# loop or recursive call should be used.
return fn(*args, **kwargs)
return wrapped
def repeat_on_stale_parent_reference(fn):
"""
The decorator repeats a function once when StaleElementReferenceException
is caught.
It is not applicable if a parent reference is created outside a function.
"""
@wraps(fn)
def wrapped(*args, **kwargs):
if ('parent' in kwargs) and kwargs['parent'] is None:
try:
return fn(*args, **kwargs)
except StaleElementReferenceException:
pass
return fn(*args, **kwargs)
return wrapped
class UI_driver:
"""
Base class for all UI integration tests
"""
request_timeout = 60
@pytest.fixture(autouse=True, scope="class")
def ui_driver_setup(self, request):
cls = request.cls
if NO_SELENIUM:
pytest.skip('Selenium not installed')
cls.load_config()
@pytest.fixture(autouse=True)
def ui_driver_fsetup(self, request):
self.driver = self.get_driver()
self.driver.maximize_window()
def fin():
self.driver.delete_all_cookies()
self.driver.quit()
request.addfinalizer(fin)
@classmethod
def load_config(cls):
"""
Load configuration
1) From ~/.ipa/ui_test.conf
2) From environmental variables
"""
# load config file
path = os.path.join(os.path.expanduser("~"), ".ipa/ui_test.conf")
if not NO_YAML and os.path.isfile(path):
try:
with open(path, 'r') as conf:
cls.config = yaml.safe_load(stream=conf)
except yaml.YAMLError as e:
pytest.skip("Invalid Web UI config.\n%s" % e)
except IOError as e:
pytest.skip(
"Can't load Web UI test config: %s" % e
)
else:
cls.config = {}
c = cls.config
# override with environmental variables
for k, v in ENV_MAP.items():
val = os.environ.get(k)
if val is not None:
c[v] = val
# apply defaults
if 'port' not in c:
c['port'] = DEFAULT_PORT
if 'browser' not in c:
c['browser'] = DEFAULT_BROWSER
if 'type' not in c:
c['type'] = DEFAULT_TYPE
@classmethod
def get_driver(cls):
"""
Get WebDriver according to configuration
"""
browser = cls.config["browser"]
port = cls.config["port"]
driver_type = cls.config["type"]
options = None
if browser == 'chromium':
options = ChromeOptions()
options.binary_location = paths.CHROMIUM_BROWSER
if driver_type == 'remote':
if 'host' not in cls.config:
pytest.skip('Selenium server host not configured')
host = cls.config["host"]
if browser == 'chrome':
capabilities = DesiredCapabilities.CHROME
elif browser == 'chromium':
capabilities = options.to_capabilities()
elif browser == 'ie':
capabilities = DesiredCapabilities.INTERNETEXPLORER
else:
capabilities = DesiredCapabilities.FIREFOX
try:
driver = webdriver.Remote(
command_executor='http://%s:%d/wd/hub' % (host, port),
desired_capabilities=capabilities)
except URLError as e:
pytest.skip(
'Error connecting to selenium server: %s' % e
)
except RuntimeError as e:
pytest.skip(
'Error while establishing webdriver: %s' % e
)
else:
try:
if browser in {'chrome', 'chromium'}:
driver = webdriver.Chrome(chrome_options=options)
elif browser == 'ie':
driver = webdriver.Ie()
else:
fp = None
if "ff_profile" in cls.config:
fp = webdriver.FirefoxProfile(cls.config["ff_profile"])
ff_log_path = cls.config.get("geckodriver_log_path")
webdriver_version = parse_version(webdriver.__version__)
if webdriver_version < parse_version('4.10.0'):
driver = webdriver.Firefox(fp, log_path=ff_log_path)
else:
service = webdriver.FirefoxService(
log_output=ff_log_path,
service_args=['--log', 'debug'])
driver = webdriver.Firefox(fp, service=service)
except URLError as e:
pytest.skip(
'Error connecting to selenium server: %s' % e
)
except RuntimeError as e:
pytest.skip(
'Error while establishing webdriver: %s' % e
)
return driver
@dismiss_unexpected_alert
def find(self, expression, by='id', context=None, many=False, strict=False):
"""
Helper which calls selenium find_element_by_xxx methods.
expression: search expression
by: selenium.webdriver.common.by
context: element to search on. Default: driver
many: all matching elements
strict: error out when element is not found
Returns None instead of raising exception when element is not found.
"""
assert expression, 'expression is missing'
if context is None:
context = self.driver
if not many:
method_name = 'find_element'
else:
method_name = 'find_elements'
try:
func = getattr(context, method_name)
result = func(by, expression)
except NoSuchElementException:
if strict:
raise
else:
result = None
return result
def find_by_selector(self, expression, context=None, **kwargs):
return self.find(expression, by=By.CSS_SELECTOR, context=context,
**kwargs)
def files_loaded(self):
"""
Test if dependencies were loaded. (Checks if UI has been rendered)
"""
indicator = self.find(".global-activity-indicator", By.CSS_SELECTOR)
return indicator is not None
def has_ca(self):
"""
FreeIPA server was installed with CA.
"""
return not self.config.get('no_ca')
def has_dns(self):
"""
FreeIPA server was installed with DNS.
"""
return not self.config.get('no_dns')
def has_trusts(self):
"""
FreeIPA server was installed with Trusts.
"""
return self.config.get('has_trusts')
def has_kra(self):
"""
FreeIPA server was installed with Kra.
"""
return self.config.get('has_kra')
def has_active_request(self):
"""
Check if there is running AJAX request
"""
global_indicators = self.find(".global-activity-indicator", By.CSS_SELECTOR, many=True)
for el in global_indicators:
try:
if not self.has_class(el, 'closed'):
return True
except StaleElementReferenceException:
# we don't care. Happens when indicator is part of removed dialog.
continue
return False
def wait(self, seconds=0.2):
"""
Wait specific amount of seconds
"""
time.sleep(seconds)
def wait_for_request(self, implicit=0.2, n=1, d=0):
"""
Wait for AJAX request to finish
"""
runner = self
for _i in range(n):
self.wait(implicit)
WebDriverWait(self.driver, self.request_timeout).until_not(lambda d: runner.has_active_request())
self.wait()
self.wait(d)
def wait_while_working(self, widget, implicit=0.2):
"""
Wait while working widget active
"""
working_widget = self.find('.working-widget', By.CSS_SELECTOR, widget)
self.wait(implicit)
WebDriverWait(self.driver, self.request_timeout).until_not(
lambda d: working_widget.is_displayed()
)
self.wait(0.5)
def xpath_has_val(self, attr, val):
"""
Create xpath expression for matching a presence of item in attribute
value where value is a list of items separated by space.
"""
return "contains(concat(' ',normalize-space(@%s), ' '),' %s ')" % (attr, val)
def init_app(self, login=None, password=None):
"""
Load and login
"""
self.load()
self.wait(0.5)
self.login(login, password)
# metadata + default page
self.wait_for_request(n=5)
def load(self):
"""
Navigate to Web UI first page and wait for loading of all dependencies.
"""
# if is not any of above cases, we need to load the application for
# its first time entering the URL in the address bar
self.driver.get(self.get_base_url())
runner = self
WebDriverWait(self.driver, 10).until(lambda d: runner.files_loaded())
self.wait_for_request()
def login(self, login=None, password=None, new_password=None):
"""
Log in if user is not logged in.
"""
if self.logged_in():
return
if login is None:
login = self.config['ipa_admin']
if password is None:
password = self.config['ipa_password']
if not new_password:
new_password = password
auth = self.get_login_screen()
login_tb = self.find("//input[@type='text'][@name='username']",
'xpath', auth, strict=True)
psw_tb = self.find("//input[@type='password'][@name='password']",
'xpath', auth, strict=True)
login_tb.send_keys(login)
psw_tb.send_keys(password)
psw_tb.send_keys(Keys.RETURN)
self.wait(0.5)
self.wait_for_request(n=2)
# reset password if needed
if self.login_screen_visible():
newpw_tb = self.find("//input[@type='password'][@name='new_password']", 'xpath', auth)
verify_tb = self.find("//input[@type='password'][@name='verify_password']", 'xpath', auth)
if newpw_tb and newpw_tb.is_displayed():
newpw_tb.send_keys(new_password)
verify_tb.send_keys(new_password)
verify_tb.send_keys(Keys.RETURN)
self.wait(0.5)
self.wait_for_request(n=2)
def logged_in(self):
"""
Check if user is logged in
"""
login_as = self.find('loggedinas', 'class name')
visible_name = len(login_as.text) > 0
logged_in = not self.login_screen_visible() and visible_name
return logged_in
def logout(self):
runner = self
self.profile_menu_action('logout')
# it may take some time to get login screen visible
WebDriverWait(self.driver, self.request_timeout).until(
lambda d: runner.login_screen_visible())
assert self.login_screen_visible()
def get_login_screen(self):
"""
Get reference of login screen
"""
return self.find('.login-pf', By.CSS_SELECTOR)
def login_screen_visible(self):
"""
Check if login screen is visible
"""
screen = self.get_login_screen()
return screen and screen.is_displayed()
def take_screenshot(self, name):
if self.config.get('save_screenshots'):
scr_dir = self.config.get('screenshot_dir')
path = name + '.png'
if scr_dir:
path = os.path.join(scr_dir, path)
self.driver.get_screenshot_as_file(path)
def navigate_to_entity(self, entity, facet=None):
self.driver.get(self.get_url(entity, facet))
self.wait_for_request(n=3, d=0.4)
def navigate_to_page(self, page):
self.driver.get('/'.join([self.get_base_url(), '#', 'p', page]))
self.wait_for_request(n=3, d=0.4)
def navigate_by_menu(self, item, complete=True):
"""
Navigate by using menu
"""
if complete:
parts = item.split('/')
if len(parts) > 1:
parent = parts[0:-1]
self.navigate_by_menu('/'.join(parent), complete)
s = ".navbar li[data-name='%s'] a" % item
link = self.find(s, By.CSS_SELECTOR, strict=True)
assert link.is_displayed(), 'Navigation link is not displayed: %s' % item
link.click()
self.wait_for_request()
self.wait_for_request(0.4)
def navigate_by_breadcrumb(self, item):
"""
Navigate by breadcrumb navigation
"""
facet = self.get_facet()
nav = self.find('.breadcrumb', By.CSS_SELECTOR, facet, strict=True)
a = self.find(item, By.LINK_TEXT, nav, strict=True)
a.click()
self.wait_for_request()
self.wait_for_request(0.4)
def switch_to_facet(self, name):
"""
Click on tab with given name
"""
facet = self.get_facet()
tabs = "div.facet-tabs"
sidebar = "div.sidebar-pf"
facets_container = self.find(tabs, By.CSS_SELECTOR, facet)
# handle sidebar instead of facet-tabs
# the webui facet can have only the facet-tabs OR sidebar, not both
if not facets_container:
facets_container = self.find(sidebar, By.CSS_SELECTOR, facet)
s = "li[name='%s'] a" % name
link = self.find(s, By.CSS_SELECTOR, facets_container, strict=True)
link.click()
# double wait because of facet's paging
self.wait_for_request(0.5)
self.wait_for_request()
def get_url(self, entity, facet=None):
"""
Create entity url
"""
url = [self.get_base_url(), '#', 'e', entity]
if facet:
url.append(facet)
return '/'.join(url)
def get_base_url(self):
"""
Get FreeIPA Web UI url
"""
host = self.config.get('ipa_server')
if not host:
self.skip('FreeIPA server hostname not configured')
return 'https://%s/ipa/ui' % host
def get_facet(self):
"""
Get currently displayed facet
"""
facet = self.find('.active-facet', By.CSS_SELECTOR)
assert facet is not None, "Current facet not found"
return facet
def get_facet_info(self, facet=None):
"""
Get information of currently displayed facet
"""
info = {}
# get facet
if facet is None:
facet = self.get_facet()
info["element"] = facet
#get facet name and entity
info["name"] = facet.get_attribute('data-name')
info["entity"] = facet.get_attribute('data-entity')
# get facet title
el = self.find(".facet-header h3 *:first-child", By.CSS_SELECTOR, facet)
if el:
info["title"] = el.text
# get facet pkey
el = self.find(".facet-header h3 span.facet-pkey", By.CSS_SELECTOR, facet)
if el:
info["pkey"] = el.text
return info
def get_dialogs(self, strict=False, name=None):
"""
Get all dialogs in DOM
"""
s = '.modal-dialog'
if name:
s += "[data-name='%s']" % name
dialogs = self.find(s, By.CSS_SELECTOR, many=True)
if strict:
assert dialogs, "No dialogs found"
return dialogs
def get_dialog(self, strict=False, name=None):
"""
Get last opened dialog
"""
dialogs = self.get_dialogs(strict, name)
dialog = None
if len(dialogs):
dialog = dialogs[-1]
return dialog
def get_last_error_dialog(self, dialog_name='error_dialog'):
"""
Get last opened error dialog or None.
"""
s = ".modal-dialog[data-name='%s']" % dialog_name
dialogs = self.find(s, By.CSS_SELECTOR, many=True)
dialog = None
if dialogs:
dialog = dialogs[-1]
return dialog
def get_dialog_info(self):
"""
Get last open dialog info: name, text if any.
Returns None if no dialog is open.
"""
dialog = self.get_dialog()
info = None
if dialog:
body = self.find('.modal-body', By.CSS_SELECTOR, dialog, strict=True)
info = {
'name': dialog.get_attribute('data-name'),
'text': body.text,
}
return info
def execute_api_from_ui(self, method, args, options, timeout=30):
"""
Executes FreeIPA API command/method from Web UI
"""
script = """
var method = arguments[0];
var args = arguments[1];
var options = arguments[2];
var callback = arguments[arguments.length - 1];
var rpc = require('freeipa/rpc');
var cmd = rpc.command({
method: method,
args: args,
options: options,
on_success: callback,
on_error: callback
});
cmd.execute();
"""
self.driver.set_script_timeout(timeout)
result = self.driver.execute_async_script(script, *[method, args, options])
return result
def click_on_link(self, text, parent=None):
"""
Click on link with given text and parent.
"""
if not parent:
parent = self.get_form()
link = self.find(text, By.LINK_TEXT, parent, strict=True)
link.click()
def click_undo_button(self, field, parent=None):
"""
Click undo button/s of particular field
"""
self.assert_undo_button(field)
undo_btns = self.get_undo_buttons(field, parent)
for btn in undo_btns:
btn.click()
self.assert_undo_button(field, visible=False)
def facet_button_click(self, name):
"""
Click on facet button with given name
"""
facet = self.get_facet()
s = ".facet-controls button[name=%s]" % name
self._button_click(s, facet, name)
def dialog_button_click(self, name, dialog=None):
"""
Click on dialog button with given name
Chooses last dialog if none is supplied
"""
if not dialog:
dialog = self.get_dialog(strict=True)
s = ".rcue-dialog-buttons button[name='%s']" % name
self._button_click(s, dialog, name)
def action_button_click(self, name, parent):
"""
Click on .action-button
"""
if not parent:
parent = self.get_form()
s = "a[name='%s'].action-button" % name
self._button_click(s, parent, name)
def button_click(self, name, parent=None,
parents_css_sel=None):
"""
Click on .ui-button
"""
if not parent:
if parents_css_sel:
parent = self.find(parents_css_sel, By.CSS_SELECTOR,
strict=True)
else:
parent = self.get_form()
s = "[name='%s'].btn" % name
self._button_click(s, parent, name)
def _button_click(self, selector, parent, name=''):
btn = self.find(selector, By.CSS_SELECTOR, parent, strict=True)
# The small timeout (up to 5 seconds) allows to prevent exceptions when
# driver attempts to click a button before it is rendered.
WebDriverWait(self.driver, 5, 0.2).until(
lambda d: btn.is_displayed(),
'Button is not displayed: %s' % (name or selector)
)
self.move_to_element_in_page(btn)
disabled = btn.get_attribute("disabled")
assert not disabled, 'Invalid button state: disabled. Button: %s' % name
btn.click()
self.wait_for_request()
def move_to_element_in_page(self, element):
# workaround to move the page until the element is visible
# more in https://github.com/mozilla/geckodriver/issues/776
self.driver.execute_script('arguments[0].scrollIntoView(true);',
element)
def profile_menu_action(self, name):
"""
Execute action from profile menu
"""
menu_toggle = self.find('[name=profile-menu] > a', By.CSS_SELECTOR)
menu_toggle.click()
s = "[name=profile-menu] a[href='#%s']" % name
btn = self.find(s, By.CSS_SELECTOR, strict=True)
btn.click()
# action is usually followed by opening a dialog, add wait to compensate
# possible dialog transition effect
self.wait(0.5)
def close_notifications(self):
"""
Close all notifications like success messages, warnings, infos
"""
self.wait()
while True:
# get close button of notification
s = ".notification-area .alert button"
button = self.find(s, By.CSS_SELECTOR, strict=False)
if button:
button.click()
self.wait()
else:
break
def close_all_dialogs(self):
"""
Close all currently opened dialogs
"""
self.wait()
while True:
s = ".modal.fade.in .modal-header button.close"
btn = self.find(s, By.CSS_SELECTOR)
if btn:
btn.click()
self.wait(0.5)
else:
break
def get_form(self):
"""
Get last dialog or visible facet
"""
form = self.get_dialog()
if not form:
form = self.get_facet()
return form
def select(self, selector, value, parent=None):
"""
Select option with given value in select element
"""
if not parent:
parent = self.get_form()
el = self.find(selector, By.CSS_SELECTOR, parent, strict=True)
Select(el).select_by_value(value)
def fill_text(self, selector, value, parent=None):
"""
Clear and enter text into input defined by selector.
Use for non-standard fields.
"""
if not parent:
parent = self.get_form()
tb = self.find(selector, By.CSS_SELECTOR, parent, strict=True)
try:
tb.send_keys(Keys.CONTROL + 'a')
tb.send_keys(Keys.DELETE)
tb.send_keys(value)
except InvalidElementStateException as e:
msg = "Invalid Element State, el: %s, value: %s, error: %s" % (selector, value, e)
assert False, msg
def fill_input(self, name, value, input_type="text", parent=None):
"""
Type into input element specified by name and type.
"""
s = "div[name='%s'] input[type='%s'][name='%s']" % (name, input_type, name)
self.fill_text(s, value, parent)
def fill_textarea(self, name, value, parent=None):
"""
Clear and fill textarea.
"""
s = "textarea[name='%s']" % (name)
self.fill_text(s, value, parent)
def fill_textbox(self, name, value, parent=None):
"""
Clear and fill textbox.
"""
self.fill_input(name, value, "text", parent)
def fill_password(self, name, value, parent=None):
"""
Clear and fill input[type=password]
"""
self.fill_input(name, value, "password", parent)
def fill_search_filter(self, value, parent=None):
search_field_s = '.search-filter input[name=filter]'
if not parent:
parent = self.get_form()
self.fill_text(search_field_s, value, parent)
def apply_search_filter(self, value):
self.fill_search_filter(value)
actions = ActionChains(self.driver)
actions.send_keys(Keys.ENTER).perform()
def add_multivalued(self, name, value, parent=None):
"""
Add new value to multivalued textbox
"""
if not parent:
parent = self.get_form()
s = "div[name='%s'].multivalued-widget" % name
w = self.find(s, By.CSS_SELECTOR, parent, strict=True)
add_btn = self.find("button[name=add]", By.CSS_SELECTOR, w, strict=True)
add_btn.click()
s = "div[name=value] input"
inputs = self.find(s, By.CSS_SELECTOR, w, many=True)
last = inputs[-1]
last.send_keys(value)
def edit_multivalued(self, name, value, new_value, parent=None):
"""
Edit multivalued textbox
"""
if not parent:
parent = self.get_form()
s = "div[name='%s'].multivalued-widget" % name
w = self.find(s, By.CSS_SELECTOR, parent, strict=True)
s = "div[name=value] input"
inputs = self.find(s, By.CSS_SELECTOR, w, many=True)
for i in inputs:
val = i.get_attribute('value')
if val == value:
i.clear()
i.send_keys(new_value)
def undo_multivalued(self, name, value, parent=None):
"""
Undo multivalued change
"""
if not parent:
parent = self.get_form()
s = "div[name='%s'].multivalued-widget" % name
w = self.find(s, By.CSS_SELECTOR, parent, strict=True)
s = "div[name=value] input"
inputs = self.find(s, By.CSS_SELECTOR, w, many=True)
clicked = False
for i in inputs:
val = i.get_attribute('value')
n = i.get_attribute('name')
if val == value:
s = "input[name='%s'] ~ .input-group-btn button[name=undo]" % n
link = self.find(s, By.CSS_SELECTOR, w, strict=True)
link.click()
self.wait()
clicked = True
# lets try to find the undo button element again to check if
# it is not present or displayed
link = self.find(s, By.CSS_SELECTOR, w)
assert not link or not link.is_displayed(), 'Undo btn present'
assert clicked, 'Value was not undone: %s' % value
def del_multivalued(self, name, value, parent=None):
"""
Mark value in multivalued textbox as deleted.
"""
if not parent:
parent = self.get_form()
s = "div[name='%s'].multivalued-widget" % name
w = self.find(s, By.CSS_SELECTOR, parent, strict=True)
s = "div[name=value] input"
inputs = self.find(s, By.CSS_SELECTOR, w, many=True)
clicked = False
for i in inputs:
val = i.get_attribute('value')
n = i.get_attribute('name')
if val == value:
s = "input[name='%s'] ~ .input-group-btn button[name=remove]" % n
link = self.find(s, By.CSS_SELECTOR, w, strict=True)
link.click()
self.wait()
clicked = True
assert clicked, 'Value was not removed: %s' % value
def undo_all_multivalued(self, name, parent=None):
"""
Undo all new values to multivalued textbox
"""
if parent is None:
parent = self.get_form()
label = "div[name='{}'].multivalued-widget".format(name)
widget = self.find(label, By.CSS_SELECTOR, parent, strict=True)
add_btn = self.find("button[name=undo_all]", By.CSS_SELECTOR, widget,
strict=True)
add_btn.click()
def fill_multivalued(self, name, instructions, parent=None):
"""
Add or delete a value from multivalued field
"""
for instruction in instructions:
t = instruction[0]
value = instruction[1]
if t == 'add':
self.add_multivalued(name, value, parent)
else:
self.del_multivalued(name, value, parent)
def check_option(self, name, value=None, parent=None):
r"""
Find checkbox or radio with name which matches ^NAME\d$ and
check it by clicking on a label.
"""
if not parent:
parent = self.get_form()
s = "//input[@type='checkbox' or 'radio'][contains(@name, '%s')]" % name
if value is not None:
s += "[@value='%s']" % value
opts = self.find(s, "xpath", parent, many=True)
label = None
checkbox = None
# Select only the one which matches exactly the name
for o in opts:
n = o.get_attribute("name")
if n == name or re.match(r"^%s\d+$" % name, n):
s = "label[for='%s']" % o.get_attribute("id")
label = self.find(s, By.CSS_SELECTOR, parent, strict=True)
checkbox = o
break
assert label is not None, "Option not found: %s" % name
try:
label.click()
except ElementClickInterceptedException:
checkbox.click()
def select_combobox(self, name, value, parent=None, combobox_input=None):
"""
Select value in a combobox. Search if not found.
"""
if not parent:
parent = self.get_form()
s = "[name='%s'].combobox-widget" % name
cb = self.find(s, By.CSS_SELECTOR, parent, strict=True)
open_btn = self.find('a[name=open] i', By.CSS_SELECTOR, cb, strict=True)
open_btn.click()
self.wait()
self.wait_for_request()
list_cnt = self.find('.combobox-widget-list', By.CSS_SELECTOR, cb, strict=True)
opt_s = 'select[name=list] option'
opt_s += "[value='%s']" % value if value else ':not([value])'
option = self.find(opt_s, By.CSS_SELECTOR, cb)
if combobox_input:
if not option:
open_btn.click()
self.fill_textbox(combobox_input, value, cb)
else:
if not option:
# try to search
self.fill_textbox('filter', value, cb)
search_btn = self.find('a[name=search] i', By.CSS_SELECTOR, cb,
strict=True)
search_btn.click()
self.wait_for_request()
option = self.find(opt_s, By.CSS_SELECTOR, cb, strict=True)
option.click()
# Chrome does not close search area on click
if list_cnt.is_displayed():
self.driver.switch_to.active_element.send_keys(Keys.RETURN)
self.wait()
def get_text(self, selector, parent=None):
if not parent:
parent = self.get_form()
el = self.find(selector, By.CSS_SELECTOR, parent, strict=True)
return el.text
def get_value(self, selector, parent=None):
if not parent:
parent = self.get_form()
el = self.find(selector, By.CSS_SELECTOR, parent, strict=True)
value = el.get_attribute('value')
return value
def get_field_text(self, name, parent=None, element='p'):
s = ".controls %s[name='%s']" % (element, name)
return self.get_text(s, parent)
def get_field_value(self, name, parent=None, element='input'):
s = ".controls %s[name='%s']" % (element, name)
return self.get_value(s, parent)
def get_multivalued_value(self, name, parent=None):
s = "div[name='%s'] div[name='value'] input[name^='%s']" % (name, name)
els = self.find(s, By.CSS_SELECTOR, parent, many=True)
values = []
for el in els:
values.append(el.get_attribute('value'))
return values
def get_field_checked(self, name, parent=None):
if not parent:
parent = self.get_form()
s = "div[name='%s'] input[name^='%s']" % (name, name)
els = self.find(s, By.CSS_SELECTOR, parent, strict=True, many=True)
values = []
for el in els:
if el.is_selected():
values.append(el.get_attribute('value'))
return values
def get_field_selected(self, name, parent=None):
if not parent:
parent = self.get_form()
s = "div[name='%s'] select[name='%s']" % (name, name)
el = self.find(s, By.CSS_SELECTOR, parent, strict=True)
select = Select(el)
selected = select.all_selected_options
values = []
for opt in selected:
values.append(opt.get_attribute('value'))
return values
def get_undo_buttons(self, field, parent):
"""
Get field undo button
"""
if not parent:
parent = self.get_form()
s = ".controls div[name='%s'] .btn.undo" % (field)
undos = self.find(s, By.CSS_SELECTOR, parent, strict=True, many=True)
return undos
def get_rows(self, parent=None, name=None):
"""
Return all rows of search table.
"""
if not parent:
parent = self.get_form()
# select table rows
s = self.get_table_selector(name)
s += ' tbody tr'
rows = self.find(s, By.CSS_SELECTOR, parent, many=True)
return rows
def get_row(self, pkey, parent=None, name=None):
"""
Get row element of search table with given pkey. None if not found.
"""
rows = self.get_rows(parent, name)
s = "input[value='%s']" % pkey
for row in rows:
has = self.find(s, By.CSS_SELECTOR, row)
if has:
return row
return None
def get_row_by_column_value(self, key, column_name, parent=None,
table_name=None):
"""
Get the first matched row element of a search table with given key
matched against selected column. None if not found
"""
rows = self.get_rows(parent, table_name)
s = "td div[name='%s']" % column_name
for row in rows:
has = self.find(s, By.CSS_SELECTOR, row)
if has.text == key:
return row
return None
def get_record_pkey(self, key, column, parent=None, table_name=None):
"""
Get record pkey if value of column is known
"""
row = self.get_row_by_column_value(key,
column_name=column,
parent=parent,
table_name=table_name)
val = None
if row:
el = self.find("td input", By.CSS_SELECTOR, row)
val = el.get_attribute("value")
return val
def navigate_to_row_record(self, row, pkey_column=None):
"""
Navigate to record by clicking on a link.
"""
s = 'a'
if pkey_column:
s = "div[name='%s'] a" % pkey_column
link = self.find(s, By.CSS_SELECTOR, row, strict=True)
link.click()
self.wait_for_request(0.4)
self.wait_for_request()
def navigate_to_row_record_in_new_tab(self, row, pkey_column=None):
"""
Navigate to record in a new tab by CTRL + SHIFT clicking on the link
which brings target focused in a new tab.
"""
selector = 'a'
if pkey_column:
selector = "div[name='%s'] a" % pkey_column
link = self.find(selector, By.CSS_SELECTOR, row, strict=True)
action_driver = ActionChains(self.driver)
action_driver\
.key_down(Keys.CONTROL)\
.key_down(Keys.SHIFT)\
.click(link)\
.key_up(Keys.CONTROL)\
.key_up(Keys.SHIFT)\
.perform()
self.wait_for_request()
def get_table_selector(self, name=None):
"""
Construct table selector
"""
s = "table"
if name:
s += "[name='%s']" % name
s += '.table'
return s
def select_record(self, pkey, parent=None,
table_name=None, unselect=False):
"""
Select record with given pkey in search table.
"""
if not parent:
parent = self.get_form()
s = self.get_table_selector(table_name)
input_s = s + " tbody td input[value='%s']" % pkey
checkbox = self.find(input_s, By.CSS_SELECTOR, parent, strict=True)
try:
self.move_to_element_in_page(checkbox)
checkbox.click()
except WebDriverException as e:
assert False, 'Can\'t click on checkbox label: %s \n%s' % (s, e)
self.wait()
if unselect:
assert checkbox.is_selected() is not True
self.wait()
else:
assert checkbox.is_selected(), \
'Record was not checked: %s' % input_s
self.wait()
def select_multiple_records(self, records):
"""
Select multiple records
"""
for data in records:
pkey = data['pkey']
self.select_record(pkey)
def get_record_value(self, pkey, column, parent=None, table_name=None):
"""
Get table column's text value
"""
row = self.get_row(pkey, parent, table_name)
s = "div[name=%s]" % column
val = None
if row:
el = self.find(s, By.CSS_SELECTOR, row)
val = el.text
return val
@repeat_on_stale_parent_reference
def has_record(self, pkey, parent=None, table_name=None):
"""
Check if table contains specific record.
"""
if not parent:
parent = self.get_form()
s = self.get_table_selector(table_name)
s += " tbody td input[value='%s']" % pkey
checkbox = self.find(s, By.CSS_SELECTOR, parent)
return checkbox is not None
def navigate_to_record(self, pkey, parent=None, table_name=None, entity=None, facet='search'):
"""
Clicks on record with given pkey in search table and thus cause
navigation to the record.
"""
if entity:
self.navigate_to_entity(entity, facet)
if not parent:
parent = self.get_facet()
s = self.get_table_selector(table_name)
s += " tbody"
table = self.find(s, By.CSS_SELECTOR, parent, strict=True)
link = self.find(pkey, By.LINK_TEXT, table, strict=True)
link.click()
self.wait_for_request()
def delete_record(
self, pkeys, fields=None, parent=None, table_name=None,
facet_btn='remove', confirm_btn='ok'):
"""
Delete records with given pkeys in currently opened search table.
"""
if type(pkeys) is not list:
pkeys = [pkeys]
# select
selected = False
for pkey in pkeys:
delete = self.has_record(pkey, parent, table_name)
if delete:
self.select_record(pkey, parent, table_name)
selected = True
# exec and confirm
if selected:
if table_name and parent:
s = self.get_table_selector(table_name)
table = self.find(s, By.CSS_SELECTOR, parent, strict=True)
self.button_click(facet_btn, table)
else:
self.facet_button_click(facet_btn)
if fields:
self.fill_fields(fields)
if not confirm_btn:
return
self.dialog_button_click(confirm_btn)
self.wait_for_request(n=2)
self.wait()
def delete(self, entity, data_list, facet='search', navigate=True):
"""
Delete entity records:
"""
if navigate:
self.navigate_to_entity(entity, facet)
for data in data_list:
pkey = data.get('pkey')
fields = data.get('del')
self.delete_record(pkey, fields)
def fill_fields(
self, fields, parent=None, undo=False, combobox_input=None):
"""
Fill dialog or facet inputs with give data.
Expected format:
[
('widget_type', 'key', value'),
('widget_type', 'key2', value2'),
]
"""
if not parent:
parent = self.get_form()
for field in fields:
widget_type = field[0]
key = field[1]
val = field[2]
if undo and not hasattr(key, '__call__'):
self.assert_undo_button(key, False, parent)
if widget_type == 'textbox':
self.fill_textbox(key, val, parent)
elif widget_type == 'textarea':
self.fill_textarea(key, val, parent)
elif widget_type == 'password':
self.fill_password(key, val, parent)
elif widget_type == 'radio':
self.check_option(key, val, parent)
elif widget_type == 'checkbox':
self.check_option(key, val, parent=parent)
elif widget_type == 'selectbox':
self.select('select[name=%s]' % key, val, parent)
elif widget_type == 'combobox':
self.select_combobox(
key, val, parent, combobox_input=combobox_input)
elif widget_type == 'add_table_record':
self.add_table_record(key, val, parent)
elif widget_type == 'add_table_association':
self.add_table_associations(key, val, parent)
elif widget_type == 'multivalued':
self.fill_multivalued(key, val, parent)
elif widget_type == 'table':
self.select_record(val, parent, key)
# this meta field specifies a function, to extend functionality of
# field checking
elif widget_type == 'callback':
if hasattr(key, '__call__'):
key(val)
self.wait()
if undo and not hasattr(key, '__call__'):
self.assert_undo_button(key, True, parent)
def validate_fields(self, fields, parent=None):
"""
Validate that fields on a page or dialog have desired values.
"""
if not fields:
return
if not parent:
parent = self.get_form()
for field in fields:
ftype = field[0]
key = field[1]
expected = field[2]
actual = None
if ftype == 'label':
actual = self.get_field_text(key, parent)
elif ftype in ('textbox', 'password', 'combobox'):
actual = self.get_field_value(key, parent, 'input')
elif ftype == 'textarea':
actual = self.get_field_value(key, parent, 'textarea')
elif ftype == 'radio':
actual = self.get_field_checked(key, parent)
elif ftype == 'checkbox':
actual = self.get_field_checked(key, parent)
elif ftype == 'multivalued':
actual = self.get_multivalued_value(key, parent)
elif ftype == 'table_record':
if self.has_record(expected, parent, key):
actual = expected
valid = False
if type(expected) == list:
valid = type(actual) == list and sorted(expected) == sorted(actual)
else:
# compare other values, usually strings:
valid = actual == expected
assert valid, "Values don't match. Expected: '%s', Got: '%s'" % (expected, actual)
def find_record(self, entity, data, facet='search', dummy='XXXXXXX'):
"""
Test search functionality of search facet.
1. search for non-existent value and test if result set is empty.
2. search for specific pkey and test if it's present on the page
3. reset search page by not using search criteria
"""
self.assert_facet(entity, facet)
facet = self.get_facet()
search_field_s = '.search-filter input[name=filter]'
key = data.get('pkey')
self.fill_text(search_field_s, dummy, facet)
self.action_button_click('find', facet)
self.wait_for_request(n=2)
self.assert_record(key, negative=True)
self.fill_text(search_field_s, key, facet)
self.action_button_click('find', facet)
self.wait_for_request(n=2)
self.assert_record(key)
self.fill_text(search_field_s, '', facet)
self.action_button_click('find', facet)
self.wait_for_request(n=2)
def add_record(self, entity, data, facet='search', facet_btn='add',
dialog_btn='add', add_another_btn='add_and_add_another',
delete=False, pre_delete=True, dialog_name='add',
navigate=True, combobox_input=None, negative=False):
"""
Add records.
When negative=True we are skipping final assertions.
Expected data format:
{
'pkey': 'key',
add: [
('widget_type', 'key', 'value'),
('widget_type', 'key2', 'value2'),
],
}
"""
if type(data) is not list:
data = [data]
last_element = data[len(data) - 1]
if navigate:
self.navigate_to_entity(entity, facet)
# check facet
self.assert_facet(entity, facet)
# delete if exists, ie. from previous test fail
if pre_delete:
self.delete(entity, data, navigate=False)
# current row count
self.wait_for_request(0.5)
count = len(self.get_rows())
# open add dialog
self.assert_no_dialog()
self.facet_button_click(facet_btn)
self.assert_dialog(dialog_name)
for record in data:
# fill dialog
self.fill_fields(record['add'], combobox_input=combobox_input)
btn = dialog_btn
if record != last_element:
btn = add_another_btn
if not dialog_btn:
return
self.dialog_button_click(btn)
self.wait_for_request()
self.wait_for_request()
# check expected error/warning/info
expected = ['error_4304_info']
dialog_info = self.get_dialog_info()
if dialog_info and dialog_info['name'] in expected:
self.dialog_button_click('ok')
self.wait_for_request()
if negative:
return
# check for error
self.assert_no_error_dialog()
self.wait_for_request()
self.wait_for_request(0.4)
if dialog_btn == 'add_and_edit':
page_pkey = self.get_text('.facet-pkey')
assert record['pkey'] in page_pkey
# we cannot delete because we are on different page
return
elif dialog_btn == add_another_btn:
# dialog is still open, we cannot check for records on search page
# or delete the records
return
elif dialog_btn == 'cancel':
return
# when standard 'add' was used then it will land on search page
# and we can check if new item was added - table has more rows
new_count = len(self.get_rows())
# adjust because of paging
expected = count + len(data)
if count == 20:
expected = 20
self.assert_row_count(expected, new_count)
# delete record
if delete:
self.delete(entity, data, navigate=False)
new_count = len(self.get_rows())
self.assert_row_count(count, new_count)
def mod_record(self, entity, data, facet='details', facet_btn='save',
negative=False):
"""
Mod record
Assumes that it is already on details page.
"""
self.assert_facet(entity, facet)
# TODO assert pkey
self.assert_facet_button_enabled(facet_btn, enabled=False)
self.fill_fields(data['mod'], undo=True)
self.assert_facet_button_enabled(facet_btn)
self.facet_button_click(facet_btn)
self.wait_for_request()
self.wait_for_request()
if negative:
return
self.assert_facet_button_enabled(facet_btn, enabled=False)
def basic_crud(self, entity, data,
parent_entity=None,
details_facet='details',
search_facet='search',
default_facet='details',
add_facet_btn='add',
add_dialog_btn='add',
add_dialog_name='add',
update_btn='save',
breadcrumb=None,
navigate=True,
mod=True,
delete=True):
"""
Basic CRUD operation sequence.
Expected data format:
{
'pkey': 'key',
'add': [
('widget_type', 'key', 'value'),
('widget_type', 'key2', 'value2'),
],
'mod': [
('widget_type', 'key', 'value'),
('widget_type', 'key2', 'value2'),
],
}
"""
# important for nested entities. Ie. autoumount maps
if not parent_entity:
parent_entity = entity
pkey = data['pkey']
# 1. Open Search Facet
if navigate:
self.navigate_to_entity(parent_entity)
self.assert_facet(parent_entity, search_facet)
self.wait_for_request()
# 2. Add record
self.add_record(parent_entity, data, facet=search_facet,
navigate=False, facet_btn=add_facet_btn,
dialog_name=add_dialog_name, dialog_btn=add_dialog_btn)
self.close_notifications()
# Find
self.find_record(parent_entity, data, search_facet)
# 3. Navigate to details facet
self.navigate_to_record(pkey)
self.assert_facet(entity, default_facet)
self.wait_for_request(0.5)
if default_facet != details_facet:
self.switch_to_facet(details_facet)
self.assert_facet(entity, details_facet)
self.validate_fields(data.get('add_v'))
# 4. Mod values
if mod and data.get('mod'):
self.mod_record(entity, data, details_facet, update_btn)
self.validate_fields(data.get('mod_v'))
self.close_notifications()
if not breadcrumb:
self.navigate_to_entity(entity, search_facet)
else:
self.navigate_by_breadcrumb(breadcrumb)
# 5. Delete record
if delete:
self.delete_record(pkey, data.get('del'))
self.close_notifications()
def add_table_record(self, name, data, parent=None, add_another=False):
"""
Add record to dnsrecord table, association table and similar
"""
if not parent:
parent = self.get_form()
s = self.get_table_selector(name)
table = self.find(s, By.CSS_SELECTOR, parent, strict=True)
s = ".btn[name=%s]" % 'add'
btn = self.find(s, By.CSS_SELECTOR, table, strict=True)
btn.click()
self.wait()
self.fill_fields(data['fields'])
if not add_another:
self.dialog_button_click('add')
self.wait_for_request()
def add_another_table_record(self, data, add_another=False):
"""
Add table record after creating previous one in the same dialog
TODO: Create class to manipulate such type of dialog
"""
self.dialog_button_click('add_and_add_another')
self.wait_for_request()
self.fill_fields(data['fields'])
if not add_another:
self.dialog_button_click('add')
self.wait_for_request()
def prepare_associations(
self, pkeys, facet=None, facet_btn='add', member_pkeys=None,
confirm_btn='add', search=False):
"""
Helper function for add_associations and delete_associations
"""
if facet:
self.switch_to_facet(facet)
self.facet_button_click(facet_btn)
self.wait()
self.wait_for_request()
if search is True:
for key in pkeys:
search_field_s = '.adder-dialog-top input[name="filter"]'
self.fill_text(search_field_s, key)
self._button_click(selector="button[name='find'].btn-default",
parent=None)
self.wait_for_request()
self.select_record(key, table_name='available')
self.button_click('add')
else:
for key in pkeys:
self.select_record(key, table_name='available')
self.button_click('add')
self.dialog_button_click(confirm_btn)
self.wait_for_request()
if member_pkeys:
check_pkeys = member_pkeys
else:
check_pkeys = pkeys
return check_pkeys
def add_associations(
self, pkeys, facet=None, delete=False, facet_btn='add',
member_pkeys=None, confirm_btn='add', search=False):
"""
Add associations
"""
check_pkeys = self.prepare_associations(
pkeys, facet, facet_btn, member_pkeys, confirm_btn, search)
# we need to return if we want to "cancel" to avoid assert record fail
if confirm_btn == 'cancel':
return
for key in check_pkeys:
self.assert_record(key)
if delete:
self.delete_record(key)
self.assert_record(key, negative=True)
def delete_associations(
self, pkeys, facet=None, facet_btn='remove', member_pkeys=None):
"""
Remove associations
"""
check_pkeys = self.prepare_associations(
pkeys, facet, facet_btn, member_pkeys)
for key in check_pkeys:
self.assert_record(key, negative=True)
def add_table_associations(self, table_name, pkeys, parent=False,
delete=False, confirm_btn='add',
negative=False):
"""
Add value to table (association|rule|...)
"""
if not parent:
parent = self.get_form()
s = self.get_table_selector(table_name)
table = self.find(s, By.CSS_SELECTOR, parent, strict=True)
s = "button[name='%s']" % 'add'
btn = self.find(s, By.CSS_SELECTOR, table, strict=True)
btn.click()
self.wait_for_request(0.4)
for key in pkeys:
self.select_record(key, table_name='available')
self.button_click('add')
self.wait()
self.dialog_button_click(confirm_btn)
if confirm_btn == 'cancel':
self.assert_record(key, parent, table_name, negative=True)
return
self.wait_for_request(n=2)
if negative:
return
for key in pkeys:
self.assert_record(key, parent, table_name)
if delete:
self.delete_record(pkeys, None, parent, table_name)
for key in pkeys:
self.assert_record(key, parent, table_name, negative=True)
def action_list_action(self, name, confirm=True, confirm_btn="ok",
parents_css_sel=None):
"""
Execute action list action
"""
context = None
if not parents_css_sel:
context = self.find(".active-facet .facet-actions",
By.CSS_SELECTOR, strict=True)
else:
context = self.find(parents_css_sel, By.CSS_SELECTOR,
strict=True)
expand = self.find(".dropdown-toggle", By.CSS_SELECTOR, context,
strict=True)
expand.click()
action_link = self.find("li[data-name=%s] a" % name, By.CSS_SELECTOR,
context, strict=True)
self.move_to_element_in_page(action_link)
action_link.click()
if confirm:
self.wait(0.5) # wait for dialog
self.dialog_button_click(confirm_btn)
self.wait()
def action_panel_action(self, panel_name, action):
"""
Execute action from action panel with given name.
"""
s = "div[data-name='%s'].action-panel" % panel_name
s += " a[data-name='%s']" % action
link = self.find(s, By.CSS_SELECTOR, strict=True)
link.click()
self.wait()
def enable_action(self):
"""
Execute and test 'enable' action panel action.
"""
title = self.find('.active-facet div.facet-title', By.CSS_SELECTOR, strict=True)
self.action_list_action('enable')
self.wait_for_request(n=2)
self.assert_no_error_dialog()
self.assert_class(title, 'disabled', negative=True)
def disable_action(self):
"""
Execute and test 'disable' action panel action.
"""
title = self.find('.active-facet div.facet-title', By.CSS_SELECTOR, strict=True)
self.action_list_action('disable')
self.wait_for_request(n=2)
self.assert_no_error_dialog()
self.close_notifications()
self.move_to_element_in_page(title)
self.assert_class(title, 'disabled')
def delete_action(self, entity, pkey, action='delete', facet='search'):
"""
Execute and test 'delete' action panel action.
"""
self.action_list_action(action)
self.wait_for_request(n=4)
self.assert_no_error_dialog()
self.assert_facet(entity, facet)
self.assert_record(pkey, negative=True)
def mod_rule_tables(self, tables, categories, no_categories):
"""
Test functionality of rule table widgets in a facet
"""
def get_t_vals(t):
table = t[0]
k = t[1]
e = []
if len(t) > 2:
e = t[2]
return table, k, e
t_list = [t[0] for t in tables if t[0] not in no_categories]
# add values
for t in tables:
table, keys, _exts = get_t_vals(t)
# add one by one to test for #3711
for key in keys:
self.add_table_associations(table, [key])
#disable tables
for cat in categories:
self.check_option(cat, 'all')
# update
self.assert_rule_tables_enabled(t_list, False)
self.facet_button_click('save')
self.wait_for_request(n=3, d=0.3)
self.assert_rule_tables_enabled(t_list, False)
p = self.get_form()
# now tables in categories should be empty, check it
for t in tables:
table, keys, _exts = get_t_vals(t)
if table in no_categories:
# clear the rest
self.delete_record(keys, None, p, table)
continue
for key in keys:
self.assert_record(key, p, table, negative=True)
# enable tables
for cat in categories:
self.check_option(cat, '')
self.assert_rule_tables_enabled(t_list, True)
self.facet_button_click('save')
self.wait_for_request(n=3, d=0.3)
self.assert_rule_tables_enabled(t_list, True)
for t in tables:
table, keys, _exts = get_t_vals(t)
# add multiple at once and test table delete button
self.add_table_associations(table, keys, delete=True)
def add_sshkey_to_record(self, ssh_keys, pkey, entity='user',
navigate=False, save=True):
"""
Add ssh public key to particular record
ssh_keys (list): public ssh key(s)
pkey (str): user/host/idview to add the key to
entity (str): name of entity where to navigate if navigate=True
navigate (bool): whether we should navigate to record
save (bool): whether we should click save after adding a key
"""
if type(ssh_keys) is not list:
ssh_keys = [ssh_keys]
if navigate:
self.navigate_to_entity(entity)
self.navigate_to_record(pkey)
for key in ssh_keys:
s_add = 'div[name="ipasshpubkey"] button[name="add"]'
ssh_add_btn = self.find(s_add, By.CSS_SELECTOR, strict=True)
ssh_add_btn.click()
self.wait()
s_text_area = 'textarea.certificate'
text_area = self.find(s_text_area, By.CSS_SELECTOR, strict=True)
text_area.send_keys(key)
self.wait()
self.dialog_button_click('update')
# sometimes we do not want to save e.g. in order to test undo buttons
if save:
self.facet_button_click('save')
def delete_record_sshkeys(self, pkey, entity='user', navigate=False):
"""
Delete all ssh public keys of particular record
pkey (str): user/host/idview to add the key to
entity (str): name of entity where to navigate if navigate=True
navigate (bool): whether we should navigate to record
"""
if navigate:
self.navigate_to_entity(entity)
self.navigate_to_record(pkey)
ssh_pub = 'div[name="ipasshpubkey"] button[name="remove"]'
rm_btns = self.find(ssh_pub, By.CSS_SELECTOR, many=True)
assert rm_btns, 'No SSH keys to be deleted found on current page'
for btn in rm_btns:
btn.click()
self.facet_button_click('save')
def assert_num_ssh_keys(self, num):
"""
Assert number of SSH keys we have associated with the user
"""
s_keys = 'div[name="ipasshpubkey"] .widget[name="value"]'
ssh_keys = self.find(s_keys, By.CSS_SELECTOR, many=True)
num_ssh_keys = len(ssh_keys) if not None else 0
assert num_ssh_keys == num, \
('Number of SSH keys does not match. '
'Expected: {}, Got: {}'.format(num, num_ssh_keys))
def undo_ssh_keys(self, btn_name='undo'):
"""
Undo either one SSH key or all of them
Possible options:
btn_name='undo'
btn_name='undo_all'
"""
s_undo = 'div[name="ipasshpubkey"] button[name="{}"]'.format(btn_name)
undo = self.find(s_undo, By.CSS_SELECTOR, strict=True)
undo.click()
self.wait(0.6)
def run_cmd_on_ui_host(self, cmd):
"""
Run "shell" command on the UI system using "admin" user's passwd from
conf.
Use only where API does not fit.
cmd (str): command to run
"""
login = self.config.get('ipa_admin')
hostname = self.config.get('ipa_server')
password = self.config.get('ipa_password')
tasks.run_ssh_cmd(
to_host=hostname, username=login,
auth_method="password", password=password,
cmd=cmd
)
@dismiss_unexpected_alert
def has_class(self, el, cls):
"""
Check if el has CSS class
"""
class_attr = el.get_attribute("class")
return bool(class_attr) and cls in class_attr.split()
def has_form_error(self, name):
"""
Check if form field has error
TODO: Move to some mixin class
"""
form_group = self.find(
'//input[@name="{}"]/ancestor'
'::div[contains(@class, "form-group")]'.format(name),
By.XPATH
)
return self.has_class(form_group, 'has-error')
def skip(self, reason):
"""
Skip tests
"""
pytest.skip(reason)
def assert_text(self, selector, value, parent=None):
"""
Assert read-only text value in details page or in a form
"""
text = self.get_text(selector, parent)
text = text.strip()
value = value.strip()
assert text == value, "Invalid value: '%s' Expected: %s" % (text, value)
def assert_text_field(self, name, value, parent=None, element='label'):
"""
Assert read-only text value in details page or in a form
"""
s = "div[name='%s'] %s[name='%s']" % (name, element, name)
self.assert_text(s, value, parent)
def assert_empty_value(self, selector, parent=None, negative=False):
"""
Assert empty value of some field in details page or in a form
"""
value = self.get_value(selector, parent)
if negative:
assert not value == ''
else:
assert value == ''
def assert_no_dialog(self):
"""
Assert that no dialog is opened
"""
dialogs = self.get_dialogs()
assert not dialogs, 'Invalid state: dialog opened'
def assert_dialog(self, name=None):
"""
Assert that one dialog is opened or a dialog with given name
"""
dialogs = self.get_dialogs(name)
assert len(dialogs) == 1, 'No or more than one dialog opened'
def assert_no_error_dialog(self):
"""
Assert that no error dialog is opened
"""
dialog = self.get_last_error_dialog()
ok = dialog is None
if not ok:
msg = self.find('p', By.CSS_SELECTOR, dialog).text
assert ok, 'Unexpected error: %s' % msg
def assert_row_count(self, expected, current):
"""
Assert that row counts match
"""
assert expected == current, "Rows don't match. Expected: %d, Got: %d" % (expected, current)
def assert_button_enabled(self, name, context_selector=None, enabled=True):
"""
Assert that button is enabled or disabled (expects that element will be
<button>)
"""
s = ""
if context_selector:
s = context_selector
s += "button[name=%s]" % name
facet = self.get_facet()
btn = self.find(s, By.CSS_SELECTOR, facet, strict=True)
valid = enabled == btn.is_enabled()
assert btn.is_displayed(), 'Button is not displayed'
assert valid, 'Button (%s) has incorrect enabled state (enabled==%s).' % (s, enabled)
def assert_facet_button_enabled(self, name, enabled=True):
"""
Assert that facet button is enabled or disabled
"""
self.assert_button_enabled(name, ".facet-controls ", enabled)
def assert_table_button_enabled(self, name, table_name, enabled=True):
"""
Assert that button in table is enabled/disabled
"""
s = "table[name='%s'] " % table_name
self.assert_button_enabled(name, s, enabled)
def assert_facet(self, entity, facet=None):
"""
Assert that current facet is correct
"""
info = self.get_facet_info()
if facet is not None:
assert info["name"] == facet, "Invalid facet. Expected: %s, Got: %s " % (facet, info["name"])
assert info["entity"] == entity, "Invalid entity. Expected: %s, Got: %s " % (entity, info["entity"])
def assert_undo_button(self, field, visible=True, parent=None):
"""
Assert that undo button is or is not visible
"""
undos = self.get_undo_buttons(field, parent)
state = False
for undo in undos:
if undo.is_displayed():
state = True
break
if visible:
assert state, "Undo button not visible. Field: %s" % field
else:
assert not state, "Undo button visible. Field: %s" % field
def assert_visible(self, selector, parent=None, negative=False):
"""
Assert that element defined by selector is visible
"""
if not parent:
parent = self.get_form()
el = self.find(selector, By.CSS_SELECTOR, parent, strict=True)
visible = el.is_displayed()
if negative:
assert not visible, "Element visible: %s" % selector
else:
assert visible, "Element not visible: %s" % selector
def assert_disabled(self, selector, parent=None, negative=False):
"""
Assert that element defined by selector is disabled
"""
if not parent:
parent = self.get_form()
self.find(selector, By.CSS_SELECTOR, parent, strict=True)
dis = self.find(selector+"[disabled]", By.CSS_SELECTOR, parent)
if negative:
assert dis is None, "Element is disabled: %s" % selector
else:
assert dis, "Element is not disabled: %s" % selector
def assert_record(self, pkey, parent=None, table_name=None, negative=False):
"""
Assert that record is in current search table
"""
has = self.has_record(pkey, parent, table_name)
has |= self.has_record(pkey.lower(), parent, table_name)
if negative:
assert not has, "Record exists when it shouldn't: %s" % pkey
else:
assert has, 'Record does not exist: %s' % pkey
def assert_indirect_record(self, pkey, entity, facet, negative=False, switch=True):
"""
Switch to indirect facet and assert record.
Lowers the key by default.
"""
if switch:
self.switch_to_facet(facet)
radio_name = "%s-%s-type-radio" % (entity, facet.replace('_', '-'))
self.check_option(radio_name, 'indirect')
self.wait_for_request(n=2)
key = pkey
self.assert_record(key, negative=negative)
def assert_record_value(self, expected, pkeys, column, parent=None,
table_name=None):
"""
Assert that column's value of record defined by pkey equals expected
value.
"""
if type(pkeys) is not list:
pkeys = [pkeys]
for pkey in pkeys:
val = self.get_record_value(pkey, column, parent, table_name)
assert expected == val, ("Invalid value: '%s'. Expected: '%s'."
% (val, expected))
def assert_class(self, element, cls, negative=False):
"""
Assert that element has certain class
"""
valid = self.has_class(element, cls)
if negative:
assert not valid, "Element contains unwanted class: %s" % cls
else:
assert valid, "Element doesn't contain required class: %s" % cls
def assert_rule_tables_enabled(self, tables, enabled):
"""
Assert that rule table is editable - values can be added and removed.
"""
for table in tables:
self.assert_table_button_enabled('add', table, enabled)
def assert_menu_item(self, path, present=True):
"""
Assert that menu link is not rendered or visible
"""
s = ".navigation a[href='#%s']" % path
link = self.find(s, By.CSS_SELECTOR)
is_present = link is not None and link.is_displayed()
assert present == is_present, ('Invalid state of navigation item: %s. '
'Presence expected: %s') % (path, str(present))
def assert_action_panel_action(self, panel_name, action, visible=True, enabled=True):
"""
Assert that action panel action is visible/hidden, and enabled/disabled
Enabled is checked only if action is visible.
"""
s = "div[data-name='%s'].action-panel" % panel_name
s += " a[data-name='%s']" % action
link = self.find(s, By.CSS_SELECTOR)
is_visible = link is not None and link.is_displayed()
is_enabled = False
if is_visible:
is_enabled = not self.has_class(link, 'disabled')
assert is_visible == visible, ('Invalid visibility of action button: %s. '
'Expected: %s') % (action, str(visible))
if is_visible:
assert is_enabled == enabled, ('Invalid enabled state of action button %s. '
'Expected: %s') % (action, str(visible))
def assert_action_list_action(self, action, visible=True, enabled=True,
parent=None, parents_css_sel=None,
facet_actions=True):
"""
Assert that action dropdown action is visible/hidden, and enabled/disabled
Enabled is checked only if action is visible.
"""
li_s = " li[data-name='%s']" % action
if not parent:
parent = self.get_form()
if facet_actions:
li_s = ".facet-actions" + li_s
else:
li_s = parents_css_sel + li_s
li = self.find(li_s, By.CSS_SELECTOR, parent)
link = self.find("a", By.CSS_SELECTOR, li)
is_visible = li is not None and link is not None
is_enabled = False
assert is_visible == visible, ('Invalid visibility of action item: %s. '
'Expected: %s') % (action, str(visible))
if is_visible:
is_enabled = not self.has_class(li, 'disabled')
assert is_enabled == enabled, ('Invalid enabled state of action item %s. '
'Expected: %s') % (action, str(visible))
def assert_field_validation(self, expect_error, parent=None, field=None):
"""
Assert for error in field validation
"""
if not parent:
parent = self.get_form()
if field:
field_s = '.widget[name="{}"]'.format(field)
parent = self.find(field_s, By.CSS_SELECTOR, context=parent)
req_field_css = '.help-block[name="error_link"]'
res = self.find(req_field_css, By.CSS_SELECTOR, context=parent)
assert expect_error in res.text, \
'Expected error: {} not found'.format(expect_error)
def assert_field_validation_required(self, parent=None, field=None):
self.assert_field_validation('Required field', parent, field)
def assert_notification(self, type='success', assert_text=None):
"""
Assert whether we have a notification of particular type
type: type for assertion
assert_text: assert particular text when True
Returns True if selector/text found
"""
notification_type = 'div.notification-area .alert-{}'.format(type)
# wait for a half sec for notification to appear
self.wait(0.5)
is_present = self.find(notification_type, By.CSS_SELECTOR, many=True)
assert is_present, "Notification not present"
if assert_text:
assert any(map(lambda x: assert_text in x.text, is_present))
def assert_last_error_dialog(self, expected_err, details=False,
dialog_name='error_dialog'):
"""
Assert error dialog body text or when details=True click on
'Show details' and assert text there
"""
err_dialog = self.get_last_error_dialog(dialog_name=dialog_name)
if details:
# open "Show details" paragraph
s = 'a[title="Show details"]'
details = self.find(s, By.CSS_SELECTOR)
details.click()
s = 'ul.error-container li p'
self.assert_text(s, expected_err, parent=err_dialog)
else:
s = '.modal-body div p'
self.assert_text(s, expected_err, parent=err_dialog)
def assert_value_checked(self, values, name, negative=False):
"""
Assert particular value is checked
"""
if type(values) is not list:
values = [values]
checked_values = self.get_field_checked(name)
for value in values:
if negative:
assert value not in checked_values, (
'{} checked while it should not be'.format(value)
)
else:
assert value in checked_values, ('{} NOT checked while it '
'should be'.format(value))
def add_cert_to_record(self, pem_certs, pkey, entity='user',
navigate=False, save=True):
"""
Add certificate to particular user
pem_certs (list): base64/pem certificate(s)
pkey (str): user/host to add the certificate to
entity (str): name of entity where to navigate if navigate=True
navigate (bool): whether we should navigate to record
save (bool): whether we should click save after adding a key
"""
if type(pem_certs) is not list:
pem_certs = [pem_certs]
if navigate:
self.navigate_to_entity(entity)
self.navigate_to_record(pkey)
for cert in pem_certs:
c_add = 'div[name="usercertificate"] button[name="add"]'
cert_add_btn = self.find(c_add, By.CSS_SELECTOR, strict=True)
cert_add_btn.click()
self.wait()
c_text_area = 'textarea.form-control'
text_area = self.find(c_text_area, By.CSS_SELECTOR, strict=True)
text_area.send_keys(cert)
self.wait()
self.dialog_button_click('ok')
# sometimes we do not want to save e.g. in order to test undo buttons
if save:
self.facet_button_click('save')
| 82,075
|
Python
|
.py
| 2,075
| 28.892048
| 109
| 0.563613
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,402
|
test_krbtpolicy.py
|
freeipa_freeipa/ipatests/test_webui/test_krbtpolicy.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/>.
"""
Kerberos policy tests
"""
from ipatests.test_webui.ui_driver import UI_driver
from ipatests.test_webui.ui_driver import screenshot
import pytest
ENTITY = 'krbtpolicy'
DATA = {
'mod': [
('textbox', 'krbmaxrenewableage', '599000'),
('textbox', 'krbmaxticketlife', '79800'),
('textbox', 'krbauthindmaxrenewableage_radius', '601000'),
('textbox', 'krbauthindmaxticketlife_radius', '81000'),
('textbox', 'krbauthindmaxrenewableage_otp', '602000'),
('textbox', 'krbauthindmaxticketlife_otp', '82000'),
('textbox', 'krbauthindmaxrenewableage_pkinit', '603000'),
('textbox', 'krbauthindmaxticketlife_pkinit', '83000'),
('textbox', 'krbauthindmaxrenewableage_hardened', '604000'),
('textbox', 'krbauthindmaxticketlife_hardened', '84000'),
('textbox', 'krbauthindmaxrenewableage_idp', '605000'),
('textbox', 'krbauthindmaxticketlife_idp', '85000'),
('textbox', 'krbauthindmaxrenewableage_passkey', '606000'),
('textbox', 'krbauthindmaxticketlife_passkey', '86000'),
],
}
DATA2 = {
'mod': [
('textbox', 'krbmaxrenewableage', '604800'),
('textbox', 'krbmaxticketlife', '86400'),
('textbox', 'krbauthindmaxrenewableage_radius', '604800'),
('textbox', 'krbauthindmaxticketlife_radius', '86400'),
('textbox', 'krbauthindmaxrenewableage_otp', '604800'),
('textbox', 'krbauthindmaxticketlife_otp', '86400'),
('textbox', 'krbauthindmaxrenewableage_pkinit', '604800'),
('textbox', 'krbauthindmaxticketlife_pkinit', '86400'),
('textbox', 'krbauthindmaxrenewableage_hardened', '604800'),
('textbox', 'krbauthindmaxticketlife_hardened', '86400'),
('textbox', 'krbauthindmaxrenewableage_idp', '604800'),
('textbox', 'krbauthindmaxticketlife_idp', '86400'),
('textbox', 'krbauthindmaxrenewableage_passkey', '604800'),
('textbox', 'krbauthindmaxticketlife_passkey', '86400'),
],
}
@pytest.mark.tier1
class test_krbtpolicy(UI_driver):
@screenshot
def test_mod(self):
"""
Kerberos policy mod test
"""
self.init_app()
self.navigate_to_entity(ENTITY)
self.mod_record(ENTITY, DATA)
self.mod_record(ENTITY, DATA2)
@screenshot
def test_verifying_button(self):
"""
verifying Revert, Refresh and Undo button
"""
self.init_app()
self.navigate_to_entity(ENTITY)
# verifying Revert, Refresh and Undo button for max renewable age
self.button_reset('krbmaxrenewableage', '444800')
# verifying Revert, Refresh and Undo button for max ticket age
self.button_reset('krbmaxticketlife', '46400')
def button_reset(self, field, value):
"""
testing "Revert", "Refresh" and "Undo" button
"""
# verifying undo button
self.fill_textbox(field, value)
facet = self.get_facet()
s = ".input-group button[name='undo']"
self._button_click(s, facet)
self.verify_btn_action(field, value)
self.wait_for_request(n=2)
# verifying revert button
self.fill_textbox(field, value)
self.facet_button_click('revert')
self.verify_btn_action(field, value)
self.wait_for_request(n=2)
# verifying refresh button
self.fill_textbox(field, value)
self.facet_button_click('refresh')
self.verify_btn_action(field, value)
self.wait_for_request(n=2)
def verify_btn_action(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_negative_value(self):
"""
Negative test for Max renew
"""
self.init_app()
self.navigate_to_entity(ENTITY)
# string used instead of integer
expected_error = 'Must be an integer'
value = 'nonInteger'
self.modify_policy(expected_error, value)
# bigger than max value
expected_error = 'Maximum value is 2147483647'
value = '2147483649'
self.modify_policy(expected_error, value)
# smaller than max value
expected_error = 'Minimum value is 1'
value = '-1'
self.modify_policy(expected_error, value)
def modify_policy(self, expected_error, value):
"""
modifying kerberos policy values and asserting expected error
"""
self.fill_textbox('krbmaxrenewableage', value)
self.wait_for_request()
self.assert_field_validation(expected_error)
self.facet_button_click('revert')
self.fill_textbox('krbmaxticketlife', value)
self.wait_for_request()
self.assert_field_validation(expected_error, field='krbmaxticketlife')
self.facet_button_click('revert')
@screenshot
def test_verify_measurement_unit(self):
"""
verifying measurement unit for Max renew and Max life
"""
self.init_app()
self.navigate_to_entity(ENTITY)
krbmaxrenewableage = self.get_text('label[name="krbmaxrenewableage"]')
krbmaxticketlife = self.get_text('label[name="krbmaxticketlife"]')
assert "Max renew (seconds)" in krbmaxrenewableage
assert "Max life (seconds)" in krbmaxticketlife
| 6,326
|
Python
|
.py
| 155
| 33.606452
| 78
| 0.654415
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,403
|
test_subid.py
|
freeipa_freeipa/ipatests/test_webui/test_subid.py
|
"""
Tests for subordinateid.
"""
from ipatests.test_webui.ui_driver import UI_driver
import ipatests.test_webui.data_config as config_data
import ipatests.test_webui.data_user as user_data
from ipatests.test_webui.ui_driver import screenshot
import re
import pytest
try:
from selenium.common.exceptions import NoSuchElementException
except ImportError:
pass
class test_subid(UI_driver):
def add_user(self, pkey, name, surname):
self.add_record('user', {
'pkey': pkey,
'add': [
('textbox', 'uid', pkey),
('textbox', 'givenname', name),
('textbox', 'sn', surname),
]
})
def set_default_subid(self):
self.navigate_to_entity(config_data.ENTITY)
self.check_option('ipauserdefaultsubordinateid', 'checked')
self.facet_button_click('save')
def get_user_count(self, user_pkey):
self.navigate_to_entity('subid', facet='search')
self.apply_search_filter(user_pkey)
self.wait_for_request()
return self.get_rows()
@screenshot
def test_set_defaultsubid(self):
"""
Test to verify that enable/disable is working for
adding subids to new users.
"""
self.init_app()
self.add_record(user_data.ENTITY, user_data.DATA2)
self.navigate_to_entity(config_data.ENTITY)
# test subid can be enabled/disabled.
self.set_default_subid()
assert self.get_field_checked('ipauserdefaultsubordinateid')
self.set_default_subid()
assert not self.get_field_checked('ipauserdefaultsubordinateid')
@screenshot
def test_user_defaultsubid(self):
"""
Test to verify that subid is generated for new user.
"""
self.init_app()
user_pkey = "some-user"
self.set_default_subid()
assert self.get_field_checked('ipauserdefaultsubordinateid')
before_count = self.get_user_count(user_pkey)
assert len(before_count) == 0
self.add_user(user_pkey, 'Some', 'User')
after_count = self.get_user_count(user_pkey)
assert len(after_count) == 1
@screenshot
def test_user_subid_mod_desc(self):
"""
Test to verify that auto-assigned subid description is modified.
"""
self.init_app()
self.navigate_to_record("some-user")
self.switch_to_facet('memberof_subid')
rows = self.get_rows()
self.navigate_to_row_record(rows[-1])
self.fill_textbox("description", "some-user-subid-desc")
self.facet_button_click('save')
@screenshot
def test_admin_subid(self):
"""
Test to verify that subid range is created with owner admin.
"""
self.init_app()
self.navigate_to_entity('subid', facet='search')
self.facet_button_click('add')
self.select_combobox('ipaowner', 'admin')
self.dialog_button_click('add')
self.wait(0.3)
self.assert_no_error_dialog()
@screenshot
def test_admin_subid_negative(self):
"""
Test to verify that readding the subid fails with error.
"""
self.init_app()
self.navigate_to_entity('subid', facet='search')
self.facet_button_click('add')
self.select_combobox('ipaowner', 'admin')
self.dialog_button_click('add')
self.wait(0.3)
err_dialog = self.get_last_error_dialog(dialog_name='error_dialog')
text = self.get_text('.modal-body div p', err_dialog)
text = text.strip()
pattern = r'Subordinate id with with name .* already exists.'
assert re.search(pattern, text) is not None
self.close_all_dialogs()
@screenshot
def test_user_subid_add(self):
"""
Test to verify that subid range is created for given user.
"""
self.init_app()
self.navigate_to_entity('subid', facet='search')
before_count = self.get_rows()
self.facet_button_click('add')
self.select_combobox('ipaowner', user_data.PKEY2)
self.dialog_button_click('add')
self.wait(0.3)
self.assert_no_error_dialog()
after_count = self.get_rows()
assert len(before_count) < len(after_count)
@screenshot
def test_subid_range_deletion_not_allowed(self):
"""
Test to check that subid range delete is not
allowed from WebUI i.e Delete button is not available.
"""
self.init_app()
self.navigate_to_entity('subid', facet='search')
admin_uid = self.get_record_pkey("admin", "ipaowner",
table_name="ipauniqueid")
with pytest.raises(NoSuchElementException) as excinfo:
self.delete_record(admin_uid, table_name="ipauniqueid")
# Ensure that the exception is really related to missing remove button
msg = r"Unable to locate element: .facet-controls button\[name=remove\]"
assert excinfo.match(msg)
| 5,042
|
Python
|
.py
| 131
| 30.099237
| 80
| 0.626533
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,404
|
test_idviews.py
|
freeipa_freeipa/ipatests/test_webui/test_idviews.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
from ipatests.test_webui.ui_driver import UI_driver
from ipatests.test_webui.ui_driver import screenshot
import ipatests.test_webui.data_idviews as idview
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
DATA_USER = {
'pkey': user.PKEY,
'add': [
('combobox', 'ipaanchoruuid', user.PKEY),
('textbox', 'uid', 'iduser'),
('textbox', 'gecos', 'id user'),
('textbox', 'uidnumber', 1),
('textbox', 'gidnumber', 1),
('textbox', 'loginshell', 'shell'),
('textbox', 'homedirectory', 'home'),
('textarea', 'description', 'desc'),
],
'mod': [
('textbox', 'uid', 'moduser'),
('textbox', 'uidnumber', 3),
],
}
DATA_GROUP = {
'pkey': group.PKEY,
'add': [
('combobox', 'ipaanchoruuid', group.PKEY),
('textbox', 'cn', 'idgroup'),
('textbox', 'gidnumber', 2),
('textarea', 'description', 'desc'),
],
'mod': [
('textbox', 'cn', 'modgroup'),
('textbox', 'gidnumber', 3),
],
}
@pytest.mark.tier1
class test_idviews(UI_driver):
@screenshot
def test_crud(self):
"""
Basic CRUD: ID view
"""
self.init_app()
self.basic_crud(
idview.ENTITY, idview.DATA, default_facet=idview.USER_FACET)
@screenshot
def test_overrides(self):
"""
User and group overrides
"""
self.init_app()
self.add_record(user.ENTITY, user.DATA, navigate=False)
self.add_record(group.ENTITY, group.DATA)
self.add_record(idview.ENTITY, idview.DATA)
self.navigate_to_record(idview.PKEY)
parent_entity = 'idview'
# user override
self.add_record(parent_entity, DATA_USER, facet=idview.USER_FACET)
self.navigate_to_record(user.PKEY)
self.mod_record(idview.USER_FACET, DATA_USER)
self.delete_action(idview.ENTITY, user.PKEY)
# group override
self.navigate_to_record(idview.PKEY)
self.switch_to_facet(idview.GROUP_FACET)
self.add_record(parent_entity, DATA_GROUP, facet=idview.GROUP_FACET)
self.navigate_to_record(group.PKEY)
self.mod_record(idview.GROUP_FACET, DATA_GROUP)
self.delete_action(idview.ENTITY, group.PKEY)
# cleanup
self.delete(idview.ENTITY, [idview.DATA])
self.delete(user.ENTITY, [user.DATA])
self.delete(group.ENTITY, [group.DATA])
@screenshot
def test_hosts(self):
"""
Apply to hosts and host groups
"""
self.init_app()
host = host_tasks()
host.driver = self.driver
host.config = self.config
host.prep_data()
self.add_record(HOST_ENTITY, host.data)
self.add_record(hostgroup.ENTITY, hostgroup.DATA)
self.navigate_to_record(hostgroup.PKEY)
self.add_associations([host.pkey])
self.add_record(idview.ENTITY, idview.DATA)
self.navigate_to_record(idview.PKEY)
self.switch_to_facet(idview.HOST_FACET)
# apply to host
self.add_associations(
[host.pkey], facet='appliedtohosts', facet_btn='idview_apply')
self.delete_record([host.pkey], facet_btn='idview_unapply')
# apply to hostgroup
self.add_associations(
[hostgroup.PKEY], facet_btn='idview_apply_hostgroups',
member_pkeys=[host.pkey])
self.delete_associations(
[hostgroup.PKEY], facet_btn='idview_unapply_hostgroups',
member_pkeys=[host.pkey])
# cleanup
self.delete(idview.ENTITY, [idview.DATA])
self.delete(hostgroup.ENTITY, [hostgroup.DATA])
self.delete(HOST_ENTITY, [host.data])
| 3,965
|
Python
|
.py
| 110
| 28.481818
| 76
| 0.622361
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,405
|
__init__.py
|
freeipa_freeipa/ipatests/test_webui/__init__.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/>.
"""
Sub-package containing Web UI integration tests
"""
import ipatests.util
ipatests.util.check_ipaclient_unittests()
ipatests.util.check_no_ipaapi() # also ignore in make fasttest
| 959
|
Python
|
.py
| 24
| 38.833333
| 71
| 0.780043
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,406
|
data_loginscreen.py
|
freeipa_freeipa/ipatests/test_webui/data_loginscreen.py
|
#
# Copyright (C) 2018 FreeIPA Contributors see COPYING for license
#
ENTITY = 'user'
PKEY = 'itest-user'
PASSWD_ITEST_USER = '12345678'
PASSWD_ITEST_USER_NEW = '87654321'
ROOT_PKEY = 'root'
# used for add/delete fixture test user
DATA_ITEST_USER = {
'pkey': PKEY,
'add': [
('textbox', 'uid', PKEY),
('textbox', 'givenname', 'itest-user-name'),
('textbox', 'sn', 'itest-user-surname'),
('password', 'userpassword', PASSWD_ITEST_USER),
('password', 'userpassword2', PASSWD_ITEST_USER),
]
}
# used for checking login form after click Cancel on 'reset' view
FILLED_LOGIN_FORM = {
# structure of rows
# label_name, label_text,
# required, editable,
# input_type, input_name,
# input_text, placeholder
'rows': [
('username', 'Username', True, True, 'text', 'username',
PKEY, 'Username'),
('password', 'Password', True, True, 'password', 'password',
PASSWD_ITEST_USER, 'Password or Password+One-Time Password'),
],
# structure of buttons
# button_name, button_title
'buttons': [
('cert_auth', 'Log in using personal certificate'),
('sync', 'Sync OTP Token'),
('login', 'Log in'),
],
'required_msg': [
('Username: Required field',),
('Password: Required field',),
],
}
# used for checking 'reset_and_login' view
RESET_AND_LOGIN_FORM = {
# structure of rows
# label_name, label_text,
# required, editable,
# input_type, input_name,
# input_text, placeholder
'rows': [
('username_r', 'Username', False, False, None, 'username_r',
PKEY, None),
('current_password', 'Current Password', False, True, 'password',
'current_password', '', 'Current Password'),
('new_password', 'New Password', True, True, 'password',
'new_password', '', 'New Password'),
('verify_password', 'Verify Password', True, True, 'password',
'verify_password', '', 'New Password'),
('otp', 'OTP', False, True, 'password', 'otp', '',
'One-Time Password'),
],
# structure of buttons
# button_name, button_title
'buttons': [
('cancel', 'Cancel'),
('reset_and_login', 'Reset Password and Log in'),
],
'required_msg': [
('New Password: Required field',),
('Verify Password: Required field',),
],
}
# used for checking 'reset' view
RESET_PASSWORD_FORM = {
# structure of rows
# label_name, label_text,
# required, editable,
# input_type, input_name,
# input_text, placeholder
'rows': [
('username', 'Username', True, True, 'text', 'username', '',
'Username'),
('current_password', 'Current Password', True, True, 'password',
'current_password', '', 'Current Password'),
('new_password', 'New Password', True, True, 'password',
'new_password', '', 'New Password'),
('verify_password', 'Verify Password', True, True, 'password',
'verify_password', '', 'New Password'),
('otp', 'OTP', False, True, 'password', 'otp', '',
'One-Time Password'),
],
# structure of buttons
# button_name, button_title
'buttons': [
('reset', 'Reset Password'),
],
'required_msg': [
('Username: Required field',),
('Current Password: Required field',),
('New Password: Required field',),
('Verify Password: Required field',),
],
}
# used for checking empty 'login' view
EMPTY_LOGIN_FORM = {
# structure of rows
# label_name, label_text,
# required, editable,
# input_type, input_name,
# input_text, placeholder
'rows': [
('username', 'Username', False, True, 'text', 'username', '',
'Username'),
('password', 'Password', False, True, 'password', 'password', '',
'Password or Password+One-Time Password'),
],
# structure of buttons
# button_name, button_title
'buttons': [
('cert_auth', 'Log in using personal certificate'),
('sync', 'Sync OTP Token'),
('login', 'Log in'),
],
'required_msg': [
('Authentication with Kerberos failed',),
],
}
# used for checking 'login' view
LOGIN_FORM = {
# structure of rows
# label_name, label_text,
# required, editable,
# input_type, input_name,
# input_text, placeholder
'rows': [
('username', 'Username', True, True, 'text', 'username', PKEY,
'Username'),
('password', 'Password', True, True, 'password', 'password', '',
'Password or Password+One-Time Password'),
],
# structure of buttons
# button_name, button_title
'buttons': [
('cert_auth', 'Log in using personal certificate'),
('sync', 'Sync OTP Token'),
('login', 'Log in'),
],
'required_msg': [
('Password: Required field',),
],
}
| 4,927
|
Python
|
.py
| 153
| 26.169935
| 73
| 0.579975
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,407
|
data_group.py
|
freeipa_freeipa/ipatests/test_webui/data_group.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 = 'group'
DEFAULT_FACET = 'member_user'
PKEY = 'itest-group'
DATA = {
'pkey': PKEY,
'add': [
('textbox', 'cn', PKEY),
('textarea', 'description', 'test-group desc'),
('radio', 'type', 'nonposix'),
],
'mod': [
('textarea', 'description', 'test-group desc modified'),
],
}
PKEY2 = 'itest-group2'
DATA2 = {
'pkey': PKEY2,
'add': [
('textbox', 'cn', PKEY2),
('textarea', 'description', 'test-group2 desc'),
]
}
PKEY3 = 'itest-group3'
DATA3 = {
'pkey': PKEY3,
'add': [
('textbox', 'cn', PKEY3),
('textarea', 'description', 'test-group3 desc'),
]
}
PKEY4 = 'itest-group4'
DATA4 = {
'pkey': PKEY4,
'add': [
('textbox', 'cn', PKEY4),
('textarea', 'description', 'test-group4 desc'),
]
}
PKEY5 = 'itest-group5'
DATA5 = {
'pkey': PKEY5,
'add': [
('textbox', 'cn', PKEY5),
('textarea', 'description', 'test-group5 desc'),
]
}
PKEY6 = 'itest-group6'
DATA6 = {
'pkey': PKEY6,
'add': [
('textbox', 'cn', PKEY6),
('textarea', 'description', 'test-group6 desc'),
('textbox', 'gidnumber', '77777'),
]
}
PKEY7 = ''
DATA7 = {
'pkey': PKEY7,
'add': [
('textbox', 'cn', PKEY7),
('textarea', 'description', 'Empty Group name'),
]
}
PKEY8 = ';test-gr@up'
DATA8 = {
'pkey': PKEY8,
'add': [
('textbox', 'cn', PKEY8),
('textarea', 'description', 'Invalid Group name'),
]
}
PKEY9 = 'itest-group9'
DATA9 = {
'pkey': PKEY9,
'add': [
('textbox', 'cn', PKEY9),
('textarea', 'description', 'test-group9 desc'),
('radio', 'type', 'nonposix'),
]
}
PKEY10 = 'itest-group10'
DATA10 = {
'pkey': PKEY10,
'add': [
('textbox', 'cn', PKEY10),
('textarea', 'description', 'test-group10 desc'),
('radio', 'type', 'nonposix'),
]
}
PKEY_SPECIAL_CHAR_GROUP = 'itest...group_-$'
DATA_SPECIAL_CHAR_GROUP = {
'pkey': PKEY_SPECIAL_CHAR_GROUP,
'add': [
('textbox', 'cn', PKEY_SPECIAL_CHAR_GROUP),
('textarea', 'description', 'special characters group desc'),
]
}
| 2,960
|
Python
|
.py
| 115
| 21.53913
| 71
| 0.589834
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,408
|
test_vault.py
|
freeipa_freeipa/ipatests/test_webui/test_vault.py
|
# Authors:
# Pavel Vomacka <pvomacka@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/>.
"""
Vault tests
"""
from ipatests.test_webui.ui_driver import UI_driver
from ipatests.test_webui.ui_driver import screenshot
import ipatests.test_webui.data_vault as vault
import ipatests.test_webui.data_user as user
import ipatests.test_webui.data_group as group
import pytest
@pytest.mark.tier1
class vault_tasks(UI_driver):
@pytest.fixture(autouse=True)
def vault_tasks_setup(self, ui_driver_fsetup):
pass
def prep_service_data(self):
host = self.config.get('ipa_server')
realm = self.config.get('ipa_realm')
pkey = 'itest'
return {
'entity': 'service',
'pkey': '%s/%s@%s' % (pkey, host, realm),
'add': [
('textbox', 'service', pkey),
('combobox', 'host', host)
]
}
def prepare_vault_service_data(self, data):
s_data = self.prep_service_data()
service = s_data['pkey']
serv_field = [('combobox', 'service', service)]
data['add'].extend(serv_field)
def prepare_vault_user_data(self, data, user='admin'):
user_field = [('combobox', 'username', user)]
data['add'].extend(user_field)
@pytest.mark.tier1
class test_vault(vault_tasks):
@pytest.fixture(autouse=True)
def vault_setup(self, vault_tasks_setup):
if not self.has_kra():
self.skip('KRA not configured')
@screenshot
def test_crud(self):
"""
Basic basic CRUD: user vault
"""
self.init_app()
self.prepare_vault_user_data(vault.DATA)
self.basic_crud(vault.ENTITY, vault.DATA)
@screenshot
def test_add_service_vault(self):
"""
Add Service vault
"""
self.init_app()
# Add itest service
s_data = self.prep_service_data()
self.add_record(s_data['entity'], s_data)
self.prepare_vault_service_data(vault.DATA2)
# Add and remove service vault
self.add_record(vault.ENTITY, vault.DATA2, facet=vault.DATA2['facet'],
delete=True)
# Remove test service
self.navigate_to_entity(s_data['entity'])
self.delete_record(s_data['pkey'])
@screenshot
def test_add_shared_vault(self):
"""
Add Shared vault
"""
self.init_app()
# Add shared vault
self.add_record(vault.ENTITY, vault.DATA3, facet=vault.DATA3['facet'],
delete=True)
@screenshot
def test_member_owner_vault(self):
"""
Add User Vault and try to add member and owner
"""
def fill_tables():
self.add_table_associations('member_user', [user.PKEY])
self.add_table_associations('member_group', [group.PKEY])
self.add_table_associations('member_service', [s_data['pkey']])
self.add_table_associations('owner_user', [user.PKEY])
self.add_table_associations('owner_group', [group.PKEY])
self.add_table_associations('owner_service', [s_data['pkey']])
# Add user
self.init_app()
self.add_record(user.ENTITY, user.DATA)
# Prepare items - user already exists
s_data = self.prep_service_data()
self.add_record(s_data['entity'], s_data)
self.add_record(group.ENTITY, group.DATA)
# USER
# Add user vault
self.add_record(vault.ENTITY, vault.DATA, facet='user_search')
# Navigate to record
self.navigate_to_record(vault.DATA['pkey'])
# Try add values into table
fill_tables()
# Remove user vault record
self.navigate_to_entity(vault.ENTITY, vault.DATA['facet'])
self.delete_record(vault.PKEY)
# SERVICE
# Add service vault
self.prepare_vault_service_data(vault.DATA2)
self.add_record(vault.ENTITY, vault.DATA2, facet=vault.DATA2['facet'])
# Navigate to record
self.navigate_to_record(vault.DATA2['pkey'])
# Try add values into table
fill_tables()
# Remove service vault record
self.navigate_to_entity(vault.ENTITY, vault.DATA2['facet'])
self.delete_record(vault.DATA2['pkey'])
# SHARED
# Add shared vault
self.add_record(vault.ENTITY, vault.DATA3, facet=vault.DATA3['facet'])
# Navigate to record
self.navigate_to_record(vault.DATA3['pkey'])
# Try add values into table
fill_tables()
# Remove shared vault record
self.navigate_to_entity(vault.ENTITY, vault.DATA3['facet'])
self.delete_record(vault.DATA3['pkey'])
# Clean up
self.navigate_to_entity(s_data['entity'])
self.delete_record(s_data['pkey'])
self.navigate_to_entity(user.ENTITY)
self.delete_record(user.PKEY)
self.navigate_to_entity(group.ENTITY)
self.delete_record(group.PKEY)
| 5,694
|
Python
|
.py
| 148
| 30.662162
| 78
| 0.632219
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,409
|
data_idviews.py
|
freeipa_freeipa/ipatests/test_webui/data_idviews.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
ENTITY = 'idview'
USER_FACET = 'idoverrideuser'
GROUP_FACET = 'idoverridegroup'
HOST_FACET = 'appliedtohosts'
PKEY = 'itest-view'
DATA = {
'pkey': PKEY,
'add': [
('textbox', 'cn', PKEY),
('textarea', 'description', 'Description of ID view'),
],
'mod': [
('textarea', 'description', 'Different description'),
],
}
| 430
|
Python
|
.py
| 18
| 20.333333
| 66
| 0.626829
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,410
|
data_vault.py
|
freeipa_freeipa/ipatests/test_webui/data_vault.py
|
# Authors:
# Pavel Vomacka <pvomacka@redhat.com>
#
# Copyright (C) 2016 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 = 'vault'
PKEY = 'itest-user-vault'
DATA = {
'pkey': PKEY,
'facet': 'user_search',
'add': [
('radio', 'type', 'user'),
('textbox', 'cn', PKEY),
('textbox', 'description', 'test-desc')
],
'mod': [
('textbox', 'description', 'test-desc-mod'),
],
}
PKEY2 = 'itest-service-vault'
DATA2 = {
'pkey': PKEY2,
'facet': 'service_search',
'add': [
('radio', 'type', 'service'),
# service
('textbox', 'cn', PKEY2),
('textbox', 'description', 'test-desc')
],
'mod': [
('textbox', 'description', 'test-desc-mod'),
],
}
PKEY3 = 'itest-shared-vault'
DATA3 = {
'pkey': PKEY3,
'facet': 'shared_search',
'add': [
('radio', 'type', 'shared'),
('textbox', 'cn', PKEY3),
('textbox', 'description', 'test-desc')
],
'mod': [
('textbox', 'description', 'test-desc-mod'),
],
}
| 1,711
|
Python
|
.py
| 59
| 24.949153
| 71
| 0.619539
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,411
|
test_selfservice.py
|
freeipa_freeipa/ipatests/test_webui/test_selfservice.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/>.
"""
Selfservice tests
"""
from ipatests.test_webui.ui_driver import UI_driver
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui import data_selfservice
import ipatests.test_webui.data_user as user
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
ENTRY_EXIST = 'This entry already exists'
FIELD_REQ = 'Required field'
INV_NAME = ("invalid 'name': Leading and trailing spaces are "
"not allowed")
ERR_INCLUDE = 'May only contain letters, numbers, -, _, and space'
SERVICE_ADDED = 'Self Service Permission successfully added'
def reset_passwd(self, login, pwd):
self.navigate_to_entity(user.ENTITY)
self.navigate_to_record(login)
self.action_list_action('reset_password', False)
self.fill_password('password', pwd)
self.fill_password('password2', pwd)
self.dialog_button_click('confirm')
@pytest.mark.tier1
class test_selfservice(UI_driver):
@screenshot
def test_crud(self):
"""
Basic CRUD: selfservice entity
"""
self.init_app()
self.basic_crud(data_selfservice.ENTITY, data_selfservice.DATA)
@screenshot
def test_add_all_attr(self):
"""
Add self service with all attribute
"""
self.init_app()
self.add_record(data_selfservice.ENTITY, data_selfservice.DATA_ALL,
delete=True)
@screenshot
def test_add_scenarios(self):
"""
Test various add scenarios
"""
# Add self service with Add and Add Another button
self.init_app()
records = [data_selfservice.DATA, data_selfservice.DATA1]
self.add_record(data_selfservice.ENTITY, records)
# check if record is added
for record in records:
self.assert_record(record['pkey'])
# cleanup
self.navigate_to_entity(data_selfservice.ENTITY)
self.select_multiple_records(records)
self.facet_button_click('remove')
self.dialog_button_click('ok')
for record in records:
self.assert_record(record['pkey'], negative=True)
# Add self service with Add and edit button
self.add_record(data_selfservice.ENTITY,
data_selfservice.DATA1,
dialog_btn='add_and_edit')
# cleanup
self.navigate_to_entity(data_selfservice.ENTITY)
self.delete(data_selfservice.ENTITY, [data_selfservice.DATA1])
# Add self service with Add and cancel button
self.add_record(data_selfservice.ENTITY, data_selfservice.DATA1,
dialog_btn='cancel')
@screenshot
def test_undo_reset(self):
"""
Test undo and reset operation
"""
# Add self service permission and perform undo
self.init_app()
self.add_record(data_selfservice.ENTITY, data_selfservice.DATA1)
self.navigate_to_record(data_selfservice.PKEY1)
self.fill_fields(data_selfservice.DATA2)
self.click_undo_button('attrs')
self.wait_for_request()
# if undo succeed, 'save' button remains disabled
self.assert_facet_button_enabled('save', enabled=False)
# Add self service permission and perform reset
self.add_record(data_selfservice.ENTITY, data_selfservice.DATA1)
self.navigate_to_record(data_selfservice.PKEY1)
self.fill_fields(data_selfservice.DATA2)
self.facet_button_click('revert')
# if revert succeed, 'save' button remains disabled
self.assert_facet_button_enabled('save', enabled=False)
@screenshot
def test_permission_negative(self):
"""
Negative test cases for self service permission
"""
self.init_app()
# try to add duplicate entry
self.add_record(data_selfservice.ENTITY, data_selfservice.DATA1)
self.add_record(data_selfservice.ENTITY, data_selfservice.DATA1,
negative=True, pre_delete=False)
self.assert_last_error_dialog(ENTRY_EXIST)
self.close_all_dialogs()
self.delete(data_selfservice.ENTITY, [data_selfservice.DATA1])
self.close_notifications()
# try to add permission without name and attribute
self.navigate_to_entity(data_selfservice.ENTITY)
self.wait_for_request()
self.facet_button_click('add')
self.dialog_button_click('add')
self.assert_field_validation(FIELD_REQ, field='aciname')
self.dialog_button_click('cancel')
# try to add permission without name but having attribute
self.navigate_to_entity(data_selfservice.ENTITY)
self.wait_for_request()
self.facet_button_click('add')
self.check_option('attrs', 'displayname')
self.dialog_button_click('add')
self.assert_field_validation(FIELD_REQ, field='aciname')
self.dialog_button_click('cancel')
# try to add permission without having attribute.
self.navigate_to_entity(data_selfservice.ENTITY)
self.wait_for_request()
self.facet_button_click('add')
self.fill_textbox('aciname', data_selfservice.DATA1['pkey'])
self.dialog_button_click('add')
self.assert_field_validation(FIELD_REQ, field='attrs')
self.dialog_button_click('cancel')
# try to add aciname with leading space.
self.navigate_to_entity(data_selfservice.ENTITY)
self.wait_for_request()
self.facet_button_click('add')
self.fill_textbox('aciname',
' {}'.format(data_selfservice.DATA1['pkey']))
self.check_option('attrs', 'audio')
self.dialog_button_click('add')
self.assert_last_error_dialog(INV_NAME)
self.close_all_dialogs()
# try to add aciname with trailing space
self.navigate_to_entity(data_selfservice.ENTITY)
self.wait_for_request()
self.facet_button_click('add')
self.fill_textbox('aciname',
'{} '.format(data_selfservice.DATA1['pkey']))
self.check_option('attrs', 'audio')
self.dialog_button_click('add')
self.assert_last_error_dialog(INV_NAME)
self.dialog_button_click('cancel')
self.dialog_button_click('cancel')
# try to add aciname with special char
self.navigate_to_entity(data_selfservice.ENTITY)
self.wait_for_request()
self.facet_button_click('add')
self.fill_textbox('aciname', '#%^')
self.dialog_button_click('add')
self.assert_field_validation(ERR_INCLUDE, field='aciname')
self.dialog_button_click('cancel')
# try to modify pesmission by removing all attributes
self.add_record(data_selfservice.ENTITY, data_selfservice.DATA1)
self.navigate_to_record(data_selfservice.DATA1['pkey'])
self.check_option('attrs', 'businesscategory')
self.facet_button_click('save')
self.assert_field_validation(FIELD_REQ, field='attrs')
@screenshot
def test_del_multiple_permission(self):
"""
Try to delete multiple self service permission
"""
self.init_app()
self.add_record(data_selfservice.ENTITY, data_selfservice.DATA1)
self.add_record(data_selfservice.ENTITY, data_selfservice.DATA)
self.delete(data_selfservice.ENTITY,
[data_selfservice.DATA1,
data_selfservice.DATA])
# check if record deleted
for key in [data_selfservice.DATA1['pkey'],
data_selfservice.DATA['pkey']]:
self.assert_record(key, negative=True)
@screenshot
def test_permission_using_enter_key(self):
"""
Try to add/delete persmission using enter key
"""
# try to add using enter key
self.init_app()
self.add_record(data_selfservice.ENTITY,
data_selfservice.DATA1,
dialog_btn=None)
actions = ActionChains(self.driver)
actions.send_keys(Keys.ENTER).perform()
self.wait()
self.assert_notification(assert_text=SERVICE_ADDED)
self.assert_record(data_selfservice.DATA1['pkey'])
self.close_notifications()
# try to delete using enter key
self.navigate_to_entity(data_selfservice.ENTITY)
self.select_record(data_selfservice.DATA1['pkey'])
self.facet_button_click('remove')
actions = ActionChains(self.driver)
actions.send_keys(Keys.ENTER).perform()
self.wait()
self.assert_notification(assert_text='1 item(s) deleted')
self.close_notifications()
@screenshot
def test_reset_sshkey_permsission(self):
"""
Try to delete sshkey after altering sshkey permission
"""
pwd = self.config.get('ipa_password')
self.init_app()
self.add_record(user.ENTITY, user.DATA, navigate=False)
reset_passwd(self, user.PKEY, pwd)
self.logout()
self.login(user.PKEY, password=pwd, new_password=pwd)
self.add_sshkey_to_record(user.SSH_RSA, user.PKEY, navigate=True)
self.assert_num_ssh_keys(1)
self.close_notifications()
self.logout()
self.init_app()
self.navigate_to_entity(data_selfservice.ENTITY)
self.navigate_to_record('Users can manage their own SSH public keys')
# to pass the validator, check some option from the options
self.check_option('attrs', 'carlicense')
# uncheck the ipasshpubkey checkbox.
self.check_option('attrs', 'ipasshpubkey')
self.facet_button_click('save')
self.close_notifications()
self.logout()
# check if delete button is visible for ssh key.
self.login(user.PKEY, password=pwd)
s = "div[name='ipasshpubkey'].multivalued-widget"
facet = self.get_facet()
btn = self.find(s, By.CSS_SELECTOR, facet, strict=True)
assert btn.is_displayed is not True
| 10,975
|
Python
|
.py
| 255
| 34.462745
| 77
| 0.657089
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,412
|
data_config.py
|
freeipa_freeipa/ipatests/test_webui/data_config.py
|
#
# Copyright (C) 2018 FreeIPA Contributors see COPYING for license
#
ENTITY = 'config'
GRP_SEARCH_FIELD_DEFAULT = 'cn,description'
USR_SEARCH_FIELD_DEFAULT = 'uid,givenname,sn,telephonenumber,ou,title'
DATA = {
'mod': [
('textbox', 'ipasearchrecordslimit', '200'),
('textbox', 'ipasearchtimelimit', '3'),
],
}
DATA2 = {
'mod': [
('textbox', 'ipasearchrecordslimit', '100'),
('textbox', 'ipasearchtimelimit', '2'),
],
}
DATA_SIZE_LIMIT_LETTER = {
'mod': [
('textbox', 'ipasearchrecordslimit', 'a'),
],
}
DATA_SIZE_LIMIT_SPACE = {
'mod': [
('textbox', 'ipasearchrecordslimit', ' space'),
],
}
DATA_SIZE_LIMIT_NEG = {
'mod': [
('textbox', 'ipasearchrecordslimit', '-2'),
],
}
DATA_TIME_LIMIT_LETTER = {
'mod': [
('textbox', 'ipasearchtimelimit', 'a'),
],
}
DATA_TIME_LIMIT_SPACE = {
'mod': [
('textbox', 'ipasearchtimelimit', ' space'),
],
}
DATA_TIME_LIMIT_NEG = {
'mod': [
('textbox', 'ipasearchtimelimit', '-2'),
],
}
| 1,074
|
Python
|
.py
| 48
| 18.166667
| 70
| 0.572835
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,413
|
test_sudo.py
|
freeipa_freeipa/ipatests/test_webui/test_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/>.
"""
Sudo tests
"""
from ipatests.test_webui.ui_driver import UI_driver
from ipatests.test_webui.ui_driver import screenshot
import ipatests.test_webui.data_sudo as sudo
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
@pytest.mark.tier1
class test_sudo(UI_driver):
@screenshot
def test_crud(self):
"""
Basic CRUD: sudo
"""
self.init_app()
self.basic_crud(sudo.RULE_ENTITY, sudo.RULE_DATA)
self.basic_crud(sudo.CMDENTITY, sudo.CMD_DATA)
self.basic_crud(sudo.CMDGROUP_ENTITY, sudo.CMDGROUP_DATA,
default_facet=sudo.CMDGROUP_DEF_FACET)
@screenshot
def test_mod(self):
"""
Mod: sudo
"""
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(sudo.CMDENTITY, sudo.CMD_DATA)
self.add_record(sudo.CMDENTITY, sudo.CMD_DATA2, navigate=False)
self.add_record(sudo.CMDGROUP_ENTITY, sudo.CMDGROUP_DATA)
self.add_record(sudo.CMDGROUP_ENTITY, sudo.CMDGROUP_DATA2, navigate=False)
self.add_record(sudo.RULE_ENTITY, sudo.RULE_DATA)
self.navigate_to_record(sudo.RULE_PKEY, entity=sudo.RULE_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], ],
['memberallowcmd_sudocmd', [sudo.CMD_PKEY, sudo.CMD_PKEY2], ],
['memberallowcmd_sudocmdgroup', [sudo.CMD_GROUP_PKEY, sudo.CMD_GROUP_PKEY2], ],
['memberdenycmd_sudocmd', [sudo.CMD_PKEY, sudo.CMD_PKEY2], ],
['memberdenycmd_sudocmdgroup', [sudo.CMD_GROUP_PKEY, sudo.CMD_GROUP_PKEY2], ],
['ipasudorunas_user', ['admin'], ],
['ipasudorunas_group', ['editors', 'admins'], ],
['ipasudorunasgroup_group', ['editors', 'admins'], ],
]
categories = [
'usercategory',
'hostcategory',
'cmdcategory',
'ipasudorunasusercategory',
'ipasudorunasgroupcategory',
]
no_cats = [
'memberdenycmd_sudocmd',
'memberdenycmd_sudocmdgroup',
]
self.mod_rule_tables(tables, categories, no_cats)
# cleanup
# -------
self.delete(sudo.RULE_ENTITY, [sudo.RULE_DATA])
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])
self.delete(sudo.CMDENTITY, [sudo.CMD_DATA, sudo.CMD_DATA2])
self.delete(sudo.CMDGROUP_ENTITY, [sudo.CMDGROUP_DATA, sudo.CMDGROUP_DATA2])
@screenshot
def test_actions(self):
"""
Test sudo rule actions
"""
self.init_app()
self.add_record(sudo.RULE_ENTITY, sudo.RULE_DATA)
self.navigate_to_record(sudo.RULE_PKEY)
self.disable_action()
self.enable_action()
self.delete_action(sudo.RULE_ENTITY, sudo.RULE_PKEY)
| 4,853
|
Python
|
.py
| 113
| 35.451327
| 91
| 0.660661
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,414
|
data_selinuxusermap.py
|
freeipa_freeipa/ipatests/test_webui/data_selinuxusermap.py
|
#
# Copyright (C) 2018 FreeIPA Contributors see COPYING for license
#
from ipaplatform.constants import constants as platformconstants
# for example, user_u:s0
selunux_users = platformconstants.SELINUX_USERMAP_ORDER.split("$")
selinuxuser1 = selunux_users[0]
selinuxuser2 = selunux_users[1]
selinux_mcs_max = platformconstants.SELINUX_MCS_MAX
selinux_mls_max = platformconstants.SELINUX_MLS_MAX
second_mls_level = 's{}'.format(list(range(0, selinux_mls_max + 1))[0])
second_mcs_level = 'c{}'.format(list(range(0, selinux_mcs_max + 1))[0])
mcs_range = '{0}.{0}'.format(second_mcs_level)
ENTITY = 'selinuxusermap'
PKEY = 'itest-selinuxusermap'
DATA = {
'pkey': PKEY,
'add': [
('textbox', 'cn', PKEY),
('textbox', 'ipaselinuxuser', selinuxuser1),
],
'mod': [
('textarea', 'description', 'itest-selinuxusermap desc'),
],
}
PKEY2 = 'itest-selinuxusermap2'
DATA2 = {
'pkey': PKEY2,
'add': [
('textbox', 'cn', PKEY2),
('textbox', 'ipaselinuxuser', selinuxuser2),
],
'mod': [
('textarea', 'description', 'itest-selinuxusermap desc2'),
],
}
PKEY_MLS_RANGE = 'itest-selinuxusermap_MLS_range'
DATA_MLS_RANGE = {
'pkey': PKEY_MLS_RANGE,
'add': [
('textbox', 'cn', PKEY_MLS_RANGE),
('textbox', 'ipaselinuxuser', 'foo:s0-{}'.format(second_mls_level)),
],
}
PKEY_MCS_RANGE = 'itest-selinuxusermap_MLS_range'
DATA_MCS_RANGE = {
'pkey': PKEY_MCS_RANGE,
'add': [
('textbox', 'cn', PKEY_MCS_RANGE),
('textbox', 'ipaselinuxuser',
'foo:s0-s{}:c0.c{}'.format(selinux_mls_max, selinux_mcs_max)
),
],
}
PKEY_MCS_COMMAS = 'itest-selinuxusermap_MCS_commas'
DATA_MCS_COMMAS = {
'pkey': PKEY_MCS_COMMAS,
'add': [
('textbox', 'cn', PKEY_MCS_COMMAS),
('textbox', 'ipaselinuxuser',
'foo:s0-{}:c0,{},{}'.format(
second_mls_level, second_mcs_level, mcs_range),
),
],
}
PKEY_MLS_SINGLE_VAL = 'itest-selinuxusermap_MLS_single_val'
DATA_MLS_SINGLE_VAL = {
'pkey': PKEY_MLS_SINGLE_VAL,
'add': [
('textbox', 'cn', PKEY_MLS_SINGLE_VAL),
('textbox', 'ipaselinuxuser',
'foo:s0-s0:c0.c{}'.format(selinux_mcs_max)
),
],
}
PKEY_NON_EXIST_SEUSER = 'itest-selinuxusermap_nonexistent_user'
DATA_NON_EXIST_SEUSER = {
'pkey': PKEY_NON_EXIST_SEUSER,
'add': [
('textbox', 'cn', PKEY_NON_EXIST_SEUSER),
('textbox', 'ipaselinuxuser', 'foo:s0'),
],
}
PKEY_INVALID_MCS = 'itest-selinuxusermap_invalid_MCS'
DATA_INVALID_MCS = {
'pkey': PKEY_INVALID_MCS,
'add': [
('textbox', 'cn', PKEY_INVALID_MCS),
('textbox', 'ipaselinuxuser', 'foo:s0:c'),
],
}
PKEY_INVALID_MLS = 'itest-selinuxusermap_invalid_MLS'
DATA_INVALID_MLS = {
'pkey': PKEY_INVALID_MLS,
'add': [
('textbox', 'cn', PKEY_INVALID_MLS),
('textbox', 'ipaselinuxuser', 'foo'),
],
}
PKEY_FIELD_REQUIRED = 'itest-selinuxusermap_without_SELinux_user'
DATA_FIELD_REQUIRED = {
'pkey': PKEY_FIELD_REQUIRED,
'add': [
('textbox', 'cn', PKEY_FIELD_REQUIRED),
],
}
| 3,142
|
Python
|
.py
| 106
| 25
| 76
| 0.616352
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,415
|
test_realmdomains.py
|
freeipa_freeipa/ipatests/test_webui/test_realmdomains.py
|
# -*- coding: utf-8 -*-
# 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/>.
"""
Realm domains tests
Update means Check DNS in WebUI.
Force udpate means Force Update in WebUI.
"""
import uuid
from ipatests.test_webui.ui_driver import UI_driver
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui.data_dns import (
ZONE_ENTITY, FORWARD_ZONE_ENTITY, ZONE_DATA, FORWARD_ZONE_DATA,
ZONE_DEFAULT_FACET
)
import pytest
ENTITY = 'realmdomains'
@pytest.mark.tier1
class test_realmdomains(UI_driver):
def del_realm_domain(self, realmdomain, button):
self.del_multivalued('associateddomain', realmdomain)
self.facet_button_click('save')
self.dialog_button_click(button)
self.wait_for_request()
self.close_notifications()
def prepare_dns_zone(self, realmdomain):
"""
Prepare dns zone record for realmdomain
"""
# DNS check expects that the added domain will have DNS record:
# TXT _kerberos.$domain "$REALM"
# When a new domain is added using dnszone-add it automatically adds
# this TXT record and adds a realm domain. So in order to test without
# external DNS we must get into state where realm domain is not added
# (in order to add it) but DNS domain with the TXT record
# exists.
# add DNS domain
self.navigate_to_entity(ZONE_ENTITY)
self.add_record(ZONE_ENTITY, self.copy_zone_data(realmdomain))
realm = self.config.get('ipa_realm')
# remove the added domain from Realm Domain
self.navigate_to_entity(ENTITY)
self.del_realm_domain(realmdomain, 'ok')
self.close_notifications()
# re-add _TXT kerberos.$domain "$REALM"
self.navigate_to_entity(ZONE_ENTITY)
self.navigate_to_record(realmdomain + '.')
DNS_RECORD_ADD_DATA = {
'pkey': '_kerberos',
'add': [
('textbox', 'idnsname', '_kerberos'),
('selectbox', 'record_type', 'txtrecord'),
('textbox', 'txt_part_data', realm),
]
}
self.add_record(ZONE_ENTITY, DNS_RECORD_ADD_DATA,
facet=ZONE_DEFAULT_FACET, navigate=False)
def _add_associateddomain(self, values, force=False):
"""
Add values to associated domains and click OK or Force
"""
for val in values:
self.add_multivalued('associateddomain', val)
self.facet_button_click('save')
self.dialog_button_click('force' if force else 'ok')
self.wait_for_request()
self.close_notifications()
@staticmethod
def copy_zone_data(realmdomain, zone_data=ZONE_DATA):
data = zone_data.copy()
data['pkey'] = realmdomain
for i, field in enumerate(data['add']):
if field[1] == 'idnsname':
data['add'][i] = (field[0], field[1], realmdomain)
return data
@staticmethod
def rand_realmdomain():
return 'zone-{}.itest'.format(uuid.uuid4().hex[:8])
@screenshot
def test_read(self):
"""
Realm domains mod tests
"""
self.init_app()
self.navigate_to_entity(ENTITY)
# add with force - skipping DNS check
self._add_associateddomain(['itest.bar'], force=True)
self.close_notifications()
# delete
self.del_realm_domain('itest.bar', 'force')
self.wait_for_request()
realmdomain = self.rand_realmdomain()
self.prepare_dns_zone(realmdomain)
# add Realm Domain and Check DNS
self.navigate_to_entity(ENTITY)
self._add_associateddomain([realmdomain])
# cleanup
self.del_realm_domain(realmdomain, 'ok')
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_add_single_labeled_domain(self):
"""
Add single label domain
"""
self.init_app()
self.navigate_to_entity(ENTITY)
single_label_domain = u'single-label-domain'
# add with force - skipping DNS check
self._add_associateddomain([single_label_domain], force=True)
dialog = self.get_last_error_dialog()
assert ("invalid 'domain': single label domains are not supported"
in dialog.text)
@screenshot
def test_add_domain_with_special_char(self):
"""
Add domain with special_character
"""
self.init_app()
self.navigate_to_entity(ENTITY)
domain_with_special_char = u'ipa@123#.com'
# add with force - skipping DNS check
self._add_associateddomain([domain_with_special_char], force=True)
dialog = self.get_last_error_dialog()
assert ("invalid 'domain': only letters, numbers, '-' are allowed. "
"DNS label may not start or end with '-'"
in dialog.text)
@screenshot
def test_add_domain_and_undo(self):
"""
Add domain and undo
"""
self.init_app()
self.navigate_to_entity(ENTITY)
test_domain = u'itest.bar'
# add and undo
self.add_multivalued('associateddomain', test_domain)
self.undo_multivalued('associateddomain', test_domain)
# check
domains = self.get_multivalued_value('associateddomain')
assert test_domain not in domains
@screenshot
def test_add_domain_and_undo_all(self):
"""
Add domain and undo all
"""
self.init_app()
self.navigate_to_entity(ENTITY)
test_domain = u'itest.bar'
# add and undo all
self.add_multivalued('associateddomain', test_domain)
self.undo_all_multivalued('associateddomain')
# check
domains = self.get_multivalued_value('associateddomain')
assert test_domain not in domains
@screenshot
def test_add_domain_and_update(self):
"""
Add domain and update
"""
self.init_app()
self.navigate_to_entity(ENTITY)
realmdomain = self.rand_realmdomain()
self.prepare_dns_zone(realmdomain)
# add Realm Domain and Check DNS
self.navigate_to_entity(ENTITY)
self._add_associateddomain([realmdomain])
# check
domains = self.get_multivalued_value('associateddomain')
assert realmdomain in domains
# cleanup
self.del_realm_domain(realmdomain, 'ok')
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_add_domain_and_refresh(self):
"""
Add domain and refresh
"""
self.init_app()
self.navigate_to_entity(ENTITY)
test_domain = u'itest.bar'
# add and refresh
self.add_multivalued('associateddomain', test_domain)
self.facet_button_click('refresh')
# check
domains = self.get_multivalued_value('associateddomain')
assert test_domain not in domains
@screenshot
def test_add_domain_and_revert(self):
"""
Add domain and revert
"""
self.init_app()
self.navigate_to_entity(ENTITY)
test_domain = u'itest.bar'
# add and revert
self.add_multivalued('associateddomain', test_domain)
self.facet_button_click('revert')
# check
domains = self.get_multivalued_value('associateddomain')
assert test_domain not in domains
@screenshot
def test_add_duplicate_domain(self):
"""
Add duplicate domain
"""
self.init_app()
realmdomain = self.rand_realmdomain()
self.prepare_dns_zone(realmdomain)
self.navigate_to_entity(ENTITY)
# add two (same) domains with force - skipping DNS check
self._add_associateddomain([realmdomain, realmdomain], force=True)
# check
domains = self.get_multivalued_value('associateddomain')
assert realmdomain in domains
# cleanup
self.del_realm_domain(realmdomain, 'force')
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_add_empty_domain(self):
"""
Add empty domain
"""
self.init_app()
self.navigate_to_entity(ENTITY)
# add with force - skipping DNS check
self._add_associateddomain([''], force=True)
# check
dialog = self.get_last_error_dialog()
assert ("no modifications to be performed" in dialog.text)
@screenshot
def test_add_domain_with_leading_space(self):
"""
Add domain with leading space
"""
self.init_app()
self.navigate_to_entity(ENTITY)
# add with force - skipping DNS check
self._add_associateddomain([' ipa.test'], force=True)
# check
dialog = self.get_last_error_dialog()
assert ("invalid 'domain': Leading and trailing spaces are not allowed"
in dialog.text)
@screenshot
def test_add_domain_with_trailing_space(self):
"""
Add domain with trailing space
"""
self.init_app()
self.navigate_to_entity(ENTITY)
# add with force - skipping DNS check
self._add_associateddomain(['ipa.test '], force=True)
# check
dialog = self.get_last_error_dialog()
assert ("invalid 'domain': Leading and trailing spaces are not allowed"
in dialog.text)
@screenshot
def test_del_domain_undo(self):
"""
Undo after deleting existing domain
"""
self.init_app()
realmdomain = self.rand_realmdomain()
self.prepare_dns_zone(realmdomain)
# add
self.navigate_to_entity(ENTITY)
self._add_associateddomain([realmdomain])
# check that domain is present
domains = self.get_multivalued_value('associateddomain')
assert realmdomain in domains
# delete and undo
self.navigate_to_entity(ENTITY)
self.del_multivalued('associateddomain', realmdomain)
self.undo_multivalued('associateddomain', realmdomain)
# check that domain is present
domains = self.get_multivalued_value('associateddomain')
assert realmdomain in domains
# cleanup
self.del_realm_domain(realmdomain, 'ok')
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_del_domain_undo_all(self):
"""
Undo all after deleting existing domain
"""
self.init_app()
realmdomain = self.rand_realmdomain()
self.prepare_dns_zone(realmdomain)
# add
self.navigate_to_entity(ENTITY)
self._add_associateddomain([realmdomain])
# check that domain is present
domains = self.get_multivalued_value('associateddomain')
assert realmdomain in domains
# delete and undo
self.navigate_to_entity(ENTITY)
self.del_multivalued('associateddomain', realmdomain)
self.undo_all_multivalued('associateddomain')
# check that domain is present
domains = self.get_multivalued_value('associateddomain')
assert realmdomain in domains
# cleanup
self.del_realm_domain(realmdomain, 'ok')
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_del_domain_revert(self):
"""
Revert after deleting existing domain
"""
self.init_app()
realmdomain = self.rand_realmdomain()
self.prepare_dns_zone(realmdomain)
# add
self.navigate_to_entity(ENTITY)
self._add_associateddomain([realmdomain])
# del and revert
self.navigate_to_entity(ENTITY)
self.del_multivalued('associateddomain', realmdomain)
self.facet_button_click('revert')
# check
domains = self.get_multivalued_value('associateddomain')
assert realmdomain in domains
# cleanup
self.del_realm_domain(realmdomain, 'ok')
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_del_domain_and_refresh(self):
"""
Delete domain and refresh
"""
self.init_app()
realmdomain = self.rand_realmdomain()
self.prepare_dns_zone(realmdomain)
# add
self.navigate_to_entity(ENTITY)
self._add_associateddomain([realmdomain])
self.navigate_to_entity(ENTITY)
# delete
self.del_multivalued('associateddomain', realmdomain)
self.facet_button_click('refresh')
# check
domains = self.get_multivalued_value('associateddomain')
assert realmdomain in domains
# cleanup
self.del_realm_domain(realmdomain, 'ok')
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_del_domain_and_update(self):
"""
Delete and update
"""
self.init_app()
realmdomain = self.rand_realmdomain()
self.prepare_dns_zone(realmdomain)
# add
self.navigate_to_entity(ENTITY)
self._add_associateddomain([realmdomain])
self.navigate_to_entity(ENTITY)
# delete
self.del_multivalued('associateddomain', realmdomain)
self.facet_button_click('save')
self.dialog_button_click('ok')
self.wait_for_request()
self.close_notifications()
# check
domains = self.get_multivalued_value('associateddomain')
assert realmdomain not in domains
# cleanup
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_del_domain_with_force_update(self):
"""
Delete and force update
"""
self.init_app()
realmdomain = self.rand_realmdomain()
self.prepare_dns_zone(realmdomain)
# add
self.navigate_to_entity(ENTITY)
self._add_associateddomain([realmdomain])
self.navigate_to_entity(ENTITY)
# force delete
self.del_multivalued('associateddomain', realmdomain)
self.facet_button_click('save')
self.dialog_button_click('force')
self.wait_for_request()
self.close_notifications()
# check
domains = self.get_multivalued_value('associateddomain')
assert realmdomain not in domains
# cleanup
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_add_non_dns_configured_domain_negative(self):
"""
Domain shouldn't be added after:
1) add DNS non configured domain
2) click update
3) check DNS
"""
self.init_app()
realmdomain = self.rand_realmdomain()
self.navigate_to_entity(ENTITY)
self._add_associateddomain([realmdomain])
dialog = self.get_last_error_dialog()
assert ("invalid 'domain': DNS zone for each realmdomain must contain "
"SOA or NS records. "
"No records found for: " + realmdomain
in dialog.text)
@screenshot
def test_add_non_dns_configured_domain_positive(self):
"""
Domain should be added fter:
1) add DNS non configured domain
2) click update
3) click force
"""
self.init_app()
realmdomain = self.rand_realmdomain()
self.navigate_to_entity(ENTITY)
self._add_associateddomain([realmdomain], force=True)
domains = self.get_multivalued_value('associateddomain')
assert realmdomain in domains
# cleanup
self.del_realm_domain(realmdomain, 'ok')
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_del_domain_of_ipa_server_bug1035286(self):
"""
Error should occur when:
1) delete Domain of Ipa server
2) select update
3) select force update
4) click "Cancel"
"""
self.init_app()
ipadomain = self.config.get('ipa_domain')
realmdomain = self.rand_realmdomain()
self.prepare_dns_zone(realmdomain)
self.navigate_to_entity(ENTITY)
self._add_associateddomain([realmdomain])
self.navigate_to_entity(ENTITY)
self.del_multivalued('associateddomain', ipadomain)
self.facet_button_click('save')
self.dialog_button_click('force')
self.wait_for_request()
dialog = self.get_last_error_dialog()
assert ("invalid 'realmdomain list': "
"IPA server domain cannot be omitted" in dialog.text)
self.dialog_button_click('cancel')
self.facet_button_click('refresh')
# cleanup
self.del_realm_domain(realmdomain, 'ok')
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_dnszone_add_hooked_to_realmdomains_mod(self):
"""
DNSZone is hooked to realmdomains:
1) Navigate Identity >> DNS
2) Add Dnszone (newdom.com)
3) go to DNS Resource Records(DNS Zone >> newdom.com)
4) verify TXT record is exists
5) navigate Identity >> RealmDomain
6) verify newly added domain (newdom.com) exists in realmdomain list
7) Delete domain (newdom.com) from realmdomain list
8) go to DNS Resource Records(DNS Zone >> newdom.com)
9) verify TXT record is not exists
"""
self.init_app()
realmdomain = self.rand_realmdomain()
realm = self.config.get('ipa_realm')
# add DNS domain
self.navigate_to_entity(ZONE_ENTITY)
self.add_record(ZONE_ENTITY, self.copy_zone_data(realmdomain))
self.assert_record(realmdomain + '.')
self.navigate_to_record(realmdomain + '.')
self.assert_record('_kerberos')
self.assert_record_value('TXT', '_kerberos', 'type')
self.assert_record_value(realm, '_kerberos', 'data')
self.navigate_to_entity(ENTITY)
domains = self.get_multivalued_value('associateddomain')
assert realmdomain in domains
self.del_multivalued('associateddomain', realmdomain)
self.facet_button_click('save')
self.dialog_button_click('ok')
self.wait_for_request()
self.navigate_to_entity(ZONE_ENTITY)
self.assert_record(realmdomain + '.')
self.navigate_to_record(realmdomain + '.')
self.facet_button_click('refresh')
self.assert_record('_kerberos', negative=True)
# cleanup
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_dns_reversezone_add_hooked_to_realmdomains_mod(self):
"""
Reverse DNS domain is not automatically add domain to the list of
domain associated with IPA realm
1) Navigate Identity >> DNS
2) Add Dns Reverse Zone (222.65.10.in-addr.arpa.)
3) navigate Identity >> RealmDomain
4) verify newly added domain (222.65.10.in-addr.arpa.) is not exists
in realmdomain list
"""
self.init_app()
realmdomain = self.rand_realmdomain()
# add DNS Reverse zone
self.navigate_to_entity(FORWARD_ZONE_ENTITY)
self.add_record(FORWARD_ZONE_ENTITY,
self.copy_zone_data(realmdomain, FORWARD_ZONE_DATA))
self.assert_record(realmdomain + '.')
self.navigate_to_entity(ENTITY)
domains = self.get_multivalued_value('associateddomain')
assert realmdomain not in domains
# cleanup
self.navigate_to_entity(FORWARD_ZONE_ENTITY)
self.delete_record(realmdomain + '.')
@screenshot
def test_dnszone_del_hooked_to_realmdomains_mod(self):
"""
ipa dnszone-del also removes the entry from realmdomains list
1) Navigate Identity >> DNS
2) Add Dnszone (newdom.com)
3) navigate Identity >> RealmDomain
4) verify newly added domain (newdom.com) exists in realmdomain list
7) Navigate Identity >> DNS
8) Delete Dnszone(newdom.com)
9) navigate Identity >> RealmDomain
10) verify domain (newdom.com) is not exists in realmdomain list
"""
self.init_app()
realmdomain = self.rand_realmdomain()
# add DNS domain
self.navigate_to_entity(ZONE_ENTITY)
self.add_record(ZONE_ENTITY, self.copy_zone_data(realmdomain))
self.assert_record(realmdomain + '.')
self.navigate_to_entity(ENTITY)
domains = self.get_multivalued_value('associateddomain')
assert realmdomain in domains
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record(realmdomain + '.')
self.navigate_to_entity(ENTITY)
domains = self.get_multivalued_value('associateddomain')
assert realmdomain not in domains
| 22,023
|
Python
|
.py
| 571
| 29.868651
| 79
| 0.632926
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,416
|
test_config.py
|
freeipa_freeipa/ipatests/test_webui/test_config.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/>.
"""
Config tests
"""
from ipatests.test_webui.ui_driver import UI_driver
from ipatests.test_webui.ui_driver import screenshot
import ipatests.test_webui.data_config as config_data
import ipatests.test_webui.data_user as user_data
import ipatests.test_webui.data_group as group_data
import pytest
try:
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
except ImportError:
pass
ERR_USR_SEARCH_SPACES = ("invalid 'usersearch': Leading and trailing spaces "
"are not allowed")
ERR_USR_SEARCH_INV = ("invalid 'ipausersearchfields': attribute {} not "
"allowed")
ERR_GRP_SEARCH_SPACES = ("invalid 'groupsearch': Leading and trailing spaces "
"are not allowed")
ERR_GRP_SEARCH_INV = ("invalid 'ipagroupsearchfields': attribute {} not "
"allowed")
ERR_MAX_CHAR = "invalid 'login': can be at most {} characters"
ERR_HOMEDIR_SPACES = ("invalid 'homedirectory': Leading and trailing spaces "
"are not allowed")
ERR_EMAIL_SPACES = ("invalid 'emaildomain': Leading and trailing spaces are "
"not allowed")
ERR_SHELL_SPACES = ("invalid 'defaultshell': Leading and trailing spaces are "
"not allowed")
LEADING_SPACE = ' leading_space'
TRAILING_SPACE = 'trailing_space '
@pytest.mark.tier1
class test_config(UI_driver):
def search_by_field(self, field):
search_field_s = '.search-filter input[name=filter]'
self.fill_text(search_field_s, field)
self.action_button_click('find', parent=None)
self.wait_for_request(n=2)
def verify_btn_action(self, field, mod_value, negative=False):
"""
Comparing current field with modified field
"""
current_value = self.get_field_value(field)
if negative:
assert current_value != mod_value
else:
assert current_value == mod_value
def verify_user_cfg_change(self, field, name, multivalued=False):
"""
Helper function to verify that user config changes were reflected on
newly created user
"""
self.add_record(user_data.ENTITY, user_data.DATA2)
self.navigate_to_record(user_data.DATA2['pkey'])
if multivalued:
s = "div[name={0}] input[name={0}-0]".format(field)
else:
s = "div[name={0}] input[name={0}]".format(field)
assert self.get_value(s) == name
self.delete(user_data.ENTITY, [user_data.DATA2])
def assert_field_negative(self, field, value, err_msg, dialog=False):
"""
Helper function for negative field tests
"""
if value == '':
field_s = "input[type='text'][name='{}']".format(field)
input_el = self.find(field_s, By.CSS_SELECTOR,
strict=True)
input_el.clear()
input_el.send_keys(Keys.BACKSPACE)
self.facet_button_click('save')
self.assert_field_validation(err_msg, field=field)
self.facet_button_click('revert')
else:
self.fill_input(field, value)
self.facet_button_click('save')
if dialog:
self.assert_last_error_dialog(err_msg)
self.dialog_button_click('cancel')
self.facet_button_click('revert')
else:
self.assert_field_validation(err_msg, field=field)
self.facet_button_click('revert')
@screenshot
def test_mod(self):
"""
Config mod tests
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
self.mod_record(config_data.ENTITY, config_data.DATA)
self.mod_record(config_data.ENTITY, config_data.DATA2)
@screenshot
def test_size_limits(self):
"""
Test "Search size limit" field
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
size_limit_s = 'ipasearchrecordslimit'
def_val = self.get_field_value(size_limit_s)
# test field with blank field
self.assert_field_negative(size_limit_s, '',
'Required field')
# test field with invalid value
self.assert_field_negative(size_limit_s, 'abc',
'Must be an integer')
# test field with negative value
self.assert_field_negative(
size_limit_s, '-10',
"invalid 'searchrecordslimit': must be at least 10",
dialog=True,
)
# test field with space
self.assert_field_negative(size_limit_s, ' 11',
'Must be an integer')
# test minimum value
self.fill_input(size_limit_s, '-1')
self.facet_button_click('save')
assert self.get_field_value(size_limit_s) == '-1'
# restore previous value
self.fill_input(size_limit_s, def_val)
self.facet_button_click('save')
@screenshot
def test_size_limit_notification(self):
"""
Test if no notification is shown when size limit exceeded
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
size_limit_s = 'ipasearchrecordslimit'
def_val = self.get_field_value(size_limit_s)
self.fill_input(size_limit_s, '10')
self.facet_button_click('save')
self.navigate_to_entity('cert')
# wait for a half sec for notification to appear
self.wait(0.5)
warning = self.find_by_selector('div.notification-area .alert-warning')
try:
assert not warning, "Warning present: {}".format(warning.text)
finally:
# restore previous value
self.navigate_to_entity(config_data.ENTITY)
self.fill_input(size_limit_s, def_val)
self.facet_button_click('save')
@screenshot
def test_time_limits(self):
"""
Test "Search time limit" field
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
time_limit_s = 'ipasearchtimelimit'
def_val = self.get_field_value(time_limit_s)
# test field with blank field
self.assert_field_negative(time_limit_s, '',
'Required field')
# test field with invalid value
self.assert_field_negative(time_limit_s, 'abc',
'Must be an integer')
# test field with negative value
self.assert_field_negative(time_limit_s, '-10',
'Minimum value is -1')
# test field with space
self.assert_field_negative(time_limit_s, ' 11',
'Must be an integer')
# test no limit (-1) can be set
self.fill_input(time_limit_s, '-1')
self.facet_button_click('save')
assert self.get_field_value(time_limit_s) == '-1'
# restore previous value
self.fill_input(time_limit_s, def_val)
self.facet_button_click('save')
@screenshot
def test_username_lenght(self):
"""
Test "Maximum username length" field
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
usr_length_s = 'ipamaxusernamelength'
def_val = self.get_field_value(usr_length_s)
# test field with blank field
self.assert_field_negative(usr_length_s, '',
'Required field')
# test field with invalid value
self.assert_field_negative(usr_length_s, 'abc',
'Must be an integer')
# test field with exceeding value
self.assert_field_negative(usr_length_s, '9999',
'Maximum value is 255')
# test field with space in-between numbers
self.assert_field_negative(usr_length_s, '1 2',
'Must be an integer')
# test field with special char
self.assert_field_negative(usr_length_s, '*',
'Must be an integer')
# test if change of value is reflected
self.fill_input(usr_length_s, 3)
self.facet_button_click('save')
self.add_record(user_data.ENTITY, user_data.DATA, negative=True)
self.assert_last_error_dialog(ERR_MAX_CHAR.format(3))
self.close_all_dialogs()
self.navigate_to_entity(config_data.ENTITY)
# restore previous value
self.fill_input(usr_length_s, def_val)
self.facet_button_click('save')
@screenshot
def test_passwd_exp_notice(self):
"""
Test "Password Expiration Notification" field
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
exp_notice_s = 'ipapwdexpadvnotify'
# test field with blank field
self.assert_field_negative(exp_notice_s, '',
'Required field')
# test field with invalid value
self.assert_field_negative(exp_notice_s, 'abc',
'Must be an integer')
# test field with exceeding value
self.assert_field_negative(exp_notice_s, '9999999999',
'Maximum value is 2147483647')
# test field with space in-between numbers
self.assert_field_negative(exp_notice_s, '1 2',
'Must be an integer')
# test field with special char
self.assert_field_negative(exp_notice_s, '*',
'Must be an integer')
@screenshot
def test_group_search_field(self):
"""
Test "Group search fields"
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
group_search_s = 'ipagroupsearchfields'
def_val = self.get_field_value(group_search_s)
# test field with blank field
self.assert_field_negative(group_search_s, '',
'Required field')
# test field with invalid value
self.assert_field_negative(group_search_s, 'abc',
ERR_GRP_SEARCH_INV.format('"abc"'),
dialog=True)
# test field with leading space
self.assert_field_negative(group_search_s, LEADING_SPACE,
ERR_GRP_SEARCH_SPACES, dialog=True)
# test field with trailing space
self.assert_field_negative(group_search_s, TRAILING_SPACE,
ERR_GRP_SEARCH_SPACES, dialog=True)
# test default values are ok
assert config_data.GRP_SEARCH_FIELD_DEFAULT == def_val
@screenshot
def test_user_search_field(self):
"""
Test "User search fields"
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
user_search_s = 'ipausersearchfields'
def_val = self.get_field_value(user_search_s)
# test field with blank field
self.assert_field_negative(user_search_s, '',
'Required field')
# test field with invalid value
self.assert_field_negative(user_search_s, 'abc',
ERR_USR_SEARCH_INV.format('"abc"'),
dialog=True)
# test field with leading space
self.assert_field_negative(user_search_s, LEADING_SPACE,
ERR_USR_SEARCH_SPACES, dialog=True)
# test field with trailing space
self.assert_field_negative(user_search_s, TRAILING_SPACE,
ERR_USR_SEARCH_SPACES, dialog=True)
# test if changing "User search fields" is being reflected
self.fill_input(user_search_s, 'postalcode')
self.facet_button_click('save')
self.close_all_dialogs()
self.add_record(user_data.ENTITY, user_data.DATA2)
self.navigate_to_record(user_data.DATA2['pkey'])
self.mod_record(user_data.ENTITY, user_data.DATA2)
self.navigate_to_entity(user_data.ENTITY)
self.search_by_field(user_data.DATA2['mod'][2][2])
self.assert_record(user_data.DATA2['pkey'])
self.delete(user_data.ENTITY, [user_data.DATA2])
self.navigate_to_entity(config_data.ENTITY)
# restore previous value
self.fill_input(user_search_s, def_val)
self.facet_button_click('save')
@screenshot
def test_user_homedir_field(self):
"""
Test "Home directory base" field
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
homedir_s = 'ipahomesrootdir'
def_val = self.get_field_value(homedir_s)
# test field with blank field
self.assert_field_negative(homedir_s, '',
'Required field')
# test field with leading space
self.assert_field_negative(homedir_s, LEADING_SPACE,
ERR_HOMEDIR_SPACES, dialog=True)
# test field with trailing space
self.assert_field_negative(homedir_s, TRAILING_SPACE,
ERR_HOMEDIR_SPACES, dialog=True)
# test field with special chars
self.fill_input(homedir_s, '^&/*)(h*o@m%e/!u^s:e~r`s')
self.facet_button_click('save')
self.verify_user_cfg_change('homedirectory', '{}/{}'.format(
'^&/*)(h*o@m%e/!u^s:e~r`s', user_data.DATA2['pkey']))
# test field with numbers
self.navigate_to_entity(config_data.ENTITY)
self.fill_input(homedir_s, '1/home2/3users4')
self.facet_button_click('save')
self.verify_user_cfg_change('homedirectory', '{}/{}'.format(
'1/home2/3users4', user_data.DATA2['pkey']))
# test field with spaces in between
self.navigate_to_entity(config_data.ENTITY)
self.fill_input(homedir_s, '12 34')
self.facet_button_click('save')
self.verify_user_cfg_change('homedirectory', '{}/{}'.format(
'12 34', user_data.DATA2['pkey']))
# restore previous value
self.navigate_to_entity(config_data.ENTITY)
self.fill_input(homedir_s, def_val)
self.facet_button_click('save')
@screenshot
def test_user_email_field(self):
"""
Test "Default e-mail domain" field
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
def_mail_s = 'ipadefaultemaildomain'
def_val = self.get_field_value(def_mail_s)
# test field with leading space
self.assert_field_negative(def_mail_s, LEADING_SPACE,
ERR_EMAIL_SPACES, dialog=True)
# test field with trailing space
self.assert_field_negative(def_mail_s, TRAILING_SPACE,
ERR_EMAIL_SPACES, dialog=True)
# test if changing "Default e-mail domain" is being reflected
self.fill_input(def_mail_s, 'ipaui.test')
self.facet_button_click('save')
new_email = '{}@ipaui.test'.format(user_data.DATA2['pkey'])
self.verify_user_cfg_change('mail', new_email, multivalued=True)
# restore previous value
self.navigate_to_entity(config_data.ENTITY)
self.fill_input(def_mail_s, def_val)
self.facet_button_click('save')
@screenshot
def test_user_default_shell(self):
"""
Test "Default shell" field
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
def_shell_s = 'ipadefaultloginshell'
def_val = self.get_field_value(def_shell_s)
# test field with blank field
self.assert_field_negative(def_shell_s, '',
'Required field')
# test field with leading space
self.assert_field_negative(def_shell_s, LEADING_SPACE,
ERR_SHELL_SPACES, dialog=True)
# test field with trailing space
self.assert_field_negative(def_shell_s, TRAILING_SPACE,
ERR_SHELL_SPACES, dialog=True)
# test if changing "Default e-mail domain" is being reflected
self.fill_input(def_shell_s, '/bin/supershell')
self.facet_button_click('save')
self.verify_user_cfg_change('loginshell', '/bin/supershell')
# restore previous value
self.navigate_to_entity(config_data.ENTITY)
self.fill_input(def_shell_s, def_val)
self.facet_button_click('save')
@screenshot
def test_undo_reset(self):
"""
Test undo and reset buttons
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
group_search_s = 'ipagroupsearchfields'
# test selinux usermap undo button
self.fill_input(group_search_s, 'test_string')
self.click_undo_button(group_search_s)
self.verify_btn_action(group_search_s, 'test_string', negative=True)
# test revert button
self.fill_input(group_search_s, 'test_string')
self.facet_button_click('revert')
self.verify_btn_action(group_search_s, 'test_string', negative=True)
@screenshot
def test_default_user_group(self):
"""
Test "Default users group" field
"""
self.init_app()
def_usr_grp_s = 'ipadefaultprimarygroup'
self.add_record(group_data.ENTITY, group_data.DATA)
self.navigate_to_entity(config_data.ENTITY)
self.select_combobox(def_usr_grp_s, group_data.DATA['pkey'])
self.facet_button_click('save')
self.add_record(user_data.ENTITY, user_data.DATA2)
self.navigate_to_entity(group_data.ENTITY)
self.navigate_to_record(group_data.DATA['pkey'])
self.assert_record(user_data.DATA2['pkey'])
self.delete(user_data.ENTITY, [user_data.DATA2])
# restore previous value
self.navigate_to_entity(config_data.ENTITY)
self.select_combobox(def_usr_grp_s, 'ipausers')
self.facet_button_click('save')
self.delete(group_data.ENTITY, [group_data.DATA])
@screenshot
def test_misc(self):
"""
Test various miscellaneous cases under one roof
"""
self.init_app()
self.navigate_to_entity(config_data.ENTITY)
# test we can switch migration mode (enabled/disabled)
self.check_option('ipamigrationenabled', 'checked')
self.facet_button_click('save')
assert self.get_field_checked('ipamigrationenabled')
self.check_option('ipamigrationenabled', 'checked')
self.facet_button_click('save')
assert not self.get_field_checked('ipamigrationenabled')
| 19,710
|
Python
|
.py
| 449
| 33.024499
| 79
| 0.60049
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,417
|
test_navigation.py
|
freeipa_freeipa/ipatests/test_webui/test_navigation.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/>.
"""
Basic ui tests
"""
from ipatests.test_webui.ui_driver import UI_driver
from ipatests.test_webui.ui_driver import screenshot
import pytest
ENTITIES = [
'group',
'user',
'host',
'hostgroup',
'netgroup',
'service',
'dnszone',
'dnsforwardzone',
# TODO: dnsrecord
'dnsconfig',
'cert',
'otptoken',
'radiusproxy',
'realmdomains',
'hbacrule',
'hbacsvc',
'hbacsvcgroup',
'hbactest',
'sudorule',
'sudocmd',
'sudocmdgroup',
'automountlocation',
# TODO: add nested maps, keys
'pwpolicy',
'krbtpolicy',
'selinuxusermap',
'automember',
# TODO: add different types
'role',
'privilege',
'permission',
'selfservice',
'delegation',
'idrange',
'config',
# TODO: add conditional
]
@pytest.mark.tier1
class test_navigation(UI_driver):
@screenshot
def test_url_navigation(self):
"""
Navigation test: direct url change
"""
self.init_app()
unsupported = []
if not self.has_dns():
unsupported.extend([
'dnszone',
'dnsforwardzone',
'dnsconfig',
])
if not self.has_ca():
unsupported.append('cert')
entities = [e for e in ENTITIES if e not in unsupported]
for e in entities:
self.wait_for_request()
self.navigate_to_entity(e)
self.assert_facet(e)
url = self.get_url(e)
self.assert_e_url(url, e)
@screenshot
def test_menu_navigation(self):
"""
Navigation test: menu items
"""
self.init_app()
# Identity
# don't start by users (default)
self.navigate_by_menu('identity/group_search', False)
# navigate on the side bar
self.click_on_link('User Groups')
self.click_on_link('Host Groups')
self.navigate_by_menu('identity/user_search', False)
self.navigate_by_menu('identity/host', False)
self.navigate_by_menu('identity/service', False)
self.navigate_by_menu('identity/idview', False)
self.navigate_by_menu('identity/automember', False)
self.navigate_by_menu('identity/automember/amhostgroup')
self.navigate_by_menu('identity/automember/amgroup')
# Policy
self.navigate_by_menu('policy')
self.navigate_by_menu('policy/hbac', False)
self.navigate_by_menu('policy/hbac/hbacsvc', False)
self.navigate_by_menu('policy/hbac/hbacrule')
self.navigate_by_menu('policy/hbac/hbacsvcgroup')
self.navigate_by_menu('policy/hbac/hbactest')
self.navigate_by_menu('policy/sudo', False)
self.navigate_by_menu('policy/sudo/sudorule', False)
self.navigate_by_menu('policy/sudo/sudocmd')
self.navigate_by_menu('policy/sudo/sudocmdgroup')
self.navigate_by_menu('policy/selinuxusermap', False)
self.navigate_by_menu('policy/pwpolicy', False)
self.navigate_by_menu('policy/krbtpolicy', False)
# Authentication
self.navigate_by_menu('authentication')
self.navigate_by_menu('authentication/radiusproxy', False)
self.navigate_by_menu('authentication/otptoken', False)
if self.has_ca():
self.navigate_by_menu('authentication/cert_search', False)
else:
self.assert_menu_item('authentication/cert_search', False)
# Network Services
self.navigate_by_menu('network_services')
self.navigate_by_menu('network_services/automount')
if self.has_dns():
self.navigate_by_menu('network_services/dns/dnsconfig', True)
self.navigate_by_menu('network_services/dns', False)
self.navigate_by_menu('network_services/dns/dnszone', False)
self.navigate_by_menu('network_services/dns/dnsforwardzone')
else:
self.assert_menu_item('network_services/dns', False)
# IPA Server
self.navigate_by_menu('ipaserver')
self.navigate_by_menu('ipaserver/rbac', False)
self.navigate_by_menu('ipaserver/rbac/privilege', False)
self.navigate_by_menu('ipaserver/rbac/role')
self.navigate_by_menu('ipaserver/rbac/permission')
self.navigate_by_menu('ipaserver/rbac/selfservice')
self.navigate_by_menu('ipaserver/rbac/delegation')
self.navigate_by_menu('ipaserver/idrange', False)
self.navigate_by_menu('ipaserver/realmdomains', False)
if self.has_trusts():
self.navigate_by_menu('ipaserver/trusts', False)
self.navigate_by_menu('ipaserver/trusts/trust', False)
self.navigate_by_menu('ipaserver/trusts/trustconfig')
else:
self.assert_menu_item('ipaserver/trusts', False)
self.navigate_by_menu('ipaserver/config', False)
def test_new_tab_navigation(self):
"""
Test for PF#7137: [RFE]: Able to browse different links
from IPA web gui in new tabs
Test verifies whether opening target link in new tab
navigates to target (desired behaviour) compared to creation of copy of
current state of page on new tab (old behaviour).
Related: https://pagure.io/freeipa/issue/7137
"""
self.init_app()
crubs = {
'identity/host': 'host',
'identity/user_search': 'user',
'identity/group_search': 'group',
'policy': 'hbacrule',
'policy/pwpolicy': 'pwpolicy',
'authentication': 'cert',
'network_services': 'automountlocation',
'ipaserver': 'role'
}
for crub, active_facet in crubs.items():
self.navigate_by_menu(crub, False)
initial_url = self.driver.current_url
rows = self.get_rows()
if len(rows) > 0:
self.navigate_to_row_record_in_new_tab(rows[-1])
assert self.driver.current_url != initial_url
assert self.get_facet_info()['entity'] == active_facet
def assert_e_url(self, url, e):
"""
Assert correct url for entity
"""
if not self.driver.current_url.startswith(url):
msg = 'Invalid url for: %s' % e
raise AssertionError(msg)
| 7,171
|
Python
|
.py
| 189
| 29.608466
| 79
| 0.625718
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,418
|
test_loginscreen.py
|
freeipa_freeipa/ipatests/test_webui/test_loginscreen.py
|
#
# Copyright (C) 2018 FreeIPA Contributors see COPYING for license
#
"""
Test LoginScreen widget and all it's views
"""
import urllib
from ipatests.test_webui.ui_driver import UI_driver
from ipatests.test_webui.ui_driver import screenshot
import ipatests.test_webui.data_loginscreen as loginscreen
try:
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.wait import WebDriverWait
except ImportError:
pass
import pytest
@pytest.mark.tier1
class TestLoginScreen(UI_driver):
@pytest.fixture(autouse=True)
def loginscreen_setup(self, request, ui_driver_fsetup):
self.init_app()
self.add_test_user()
self.logout()
def fin():
# log out first
if (self.logged_in()):
self.logout()
else:
self.load_url(self.get_base_url())
# log in as administrator
self.login()
self.delete_test_user()
request.addfinalizer(fin)
def delete_test_user(self):
"""
Delete user for tests
"""
# User is not logged in
assert self.logged_in()
self.navigate_to_entity(loginscreen.ENTITY)
self.delete_record(loginscreen.PKEY)
def add_test_user(self):
"""
Add user for tests
"""
# User is not logged in
assert self.logged_in()
self.add_record(loginscreen.ENTITY, loginscreen.DATA_ITEST_USER,
navigate=False)
def assert_notification(self, type='success', assert_text=None,
link_text=None, link_url=None):
"""
Assert whether we have a notification of particular type
"""
notification_type = 'div.validation-summary .alert-{}'.format(type)
# wait for a half sec for notification to appear
self.wait(0.5)
is_present = self.find(notification_type, By.CSS_SELECTOR)
# Notification not present
assert is_present
if assert_text:
assert assert_text in is_present.text
if link_text and link_url:
link = self.find_xelement(".//a", is_present)
# Text on link placed on validation widget
assert link_text == link.text
# URL of link placed on validation widget
assert link_url == link.get_attribute('href')
def find_xelement(self, expression, parent, strict=True):
"""
Find element by xpath related to a given parent
"""
return self.find(expression, By.XPATH, parent, many=False,
strict=strict)
def find_xelements(self, expression, parent, strict=True):
"""
Find elements by xpath related to the given parent
"""
return self.find(expression, By.XPATH, parent, many=True,
strict=strict)
def button_click_on_login_screen(self, name):
"""
Find a button with the given name on LoginScreen widget and
then click on
"""
login_screen = self.get_login_screen()
button = self.find_xelement(".//button[@name='{}']".format(name),
login_screen)
assert button.is_displayed()
button.click()
def get_input_field(self, name, parent):
"""
Find a input field with the given name and parent
"""
return self.find_xelement(
".//input[@name='{}']".format(name),
parent
)
def load_url(self, url):
"""
Navigate to Web page and wait for loading of all dependencies.
"""
self.driver.get(url)
runner = self
WebDriverWait(self.driver, 10).until(
lambda d: runner.files_loaded()
)
self.wait()
def relogin_with_new_password(self):
"""
Log out and then log in using a new password.
It is need to check a new password
"""
if (self.logged_in()):
self.logout()
else:
self.load_url(self.get_base_url())
self.login(loginscreen.PKEY, loginscreen.PASSWD_ITEST_USER_NEW)
# User is not logged in
assert self.logged_in()
def reset_password(self, username=None, current_password=None,
new_password=None, link_text=None, link_url=None):
"""
Reset password with the given one
"""
login_screen = self.get_login_screen()
if username is not None:
username_field = self.get_input_field('username', login_screen)
cur_pass_field = self.get_input_field('current_password', login_screen)
new_pass_field = self.get_input_field('new_password', login_screen)
verify_pass_field = self.get_input_field('verify_password',
login_screen)
if username is not None:
username_field.send_keys(username)
cur_pass_field.send_keys(current_password)
new_pass_field.send_keys(new_password)
verify_pass_field.send_keys(new_password)
verify_pass_field.send_keys(Keys.RETURN)
self.wait(0.5)
self.assert_notification(assert_text='Password change complete',
link_text=link_text, link_url=link_url)
def get_data_from_form_row(self, form_row):
"""
Parse data from the form record to a comparable structure
"""
result = []
label = self.find_xelement(".//label", form_row)
assert label.is_displayed()
result.append(label.get_attribute('name'))
result.append(label.text)
req = self.find_xelement("./../..", label)
result.append(self.has_class(req, 'required'))
field = self.find_xelement(".//input", form_row)
# not editable field
editable = field.is_displayed()
if not editable:
field = self.find_xelement(".//p", form_row)
result.append(editable)
assert field.is_displayed()
result.append(field.get_attribute('type'))
result.append(field.get_attribute('name'))
if not editable:
result.append(field.text)
else:
result.append(field.get_attribute('value'))
result.append(field.get_attribute('placeholder'))
return tuple(result)
def get_data_from_button(self, button):
"""
Parse data from the button to a comparable structure
"""
result = []
result.append(button.get_attribute('name'))
result.append(button.get_attribute('title'))
return tuple(result)
def assert_form_equals(self, actual_form, expected_form):
"""
Compare two forms
"""
assert len(actual_form) == len(expected_form)
for act_row, exp_row in zip(actual_form, expected_form):
# structure of rows
# label_name, label_text,
# required, editable,
# input_type, input_name,
# input_text, placeholder
assert self.get_data_from_form_row(act_row) == exp_row
def assert_buttons_equal(self, actual_buttons, expected_buttons):
"""
Compare button sets
"""
assert len(actual_buttons) == len(expected_buttons)
for act_button, exp_button in zip(actual_buttons, expected_buttons):
assert self.get_data_from_button(act_button) == exp_button
def assert_validations_equal(self, actual_alerts, expected_alerts):
"""
Compare validation sets
"""
assert len(actual_alerts) == len(expected_alerts)
for act_alert, exp_alert in zip(actual_alerts, expected_alerts):
assert (act_alert.text,) == exp_alert
def has_validation(self, parent):
return self.find_xelement(".//div[@name='validation']", parent,
strict=False)
def check_elements_of_form(self, form_data):
login_screen = self.get_login_screen()
form = self.find_xelement(".//div[@class='form-horizontal']",
login_screen)
# rows
form_rows = self.find_xelements(
".//div[contains(@class, 'form-group')]", form
)
form_rows = [el for el in form_rows if el.is_displayed() and not
self.has_validation(el)]
self.assert_form_equals(form_rows, form_data['rows'])
# buttons
buttons = self.find_xelements(".//button", login_screen)
buttons = [el for el in buttons if el.is_displayed()]
self.assert_buttons_equal(buttons, form_data['buttons'])
def check_alerts(self, form_data):
login_screen = self.get_login_screen()
# Push the the most rigth button to see the Required fields
# it should be either 'Reset' or 'Reset and Login' or 'Login' button
self.button_click_on_login_screen(form_data['buttons'][-1][0])
alerts = self.find_xelements(
".//*[@data-name][contains(@class, 'alert-danger')]", login_screen
)
required_msgs = form_data['required_msg']
self.assert_validations_equal(alerts, required_msgs)
def load_reset_and_login_view(self):
self.load()
assert self.login_screen_visible()
username = loginscreen.PKEY
current_password = loginscreen.PASSWD_ITEST_USER
login_screen = self.get_login_screen()
username_field = self.get_input_field('username', login_screen)
cur_pass_field = self.get_input_field('password', login_screen)
username_field.send_keys(username)
cur_pass_field.send_keys(current_password)
cur_pass_field.send_keys(Keys.RETURN)
self.wait()
self.assert_notification(
type='info',
assert_text=(
'Your password has expired. Please enter a new password.'
)
)
def check_cancel(self):
"""
Check 'login' view after a cancel of password reset
"""
self.button_click_on_login_screen('cancel')
self.check_elements_of_form(loginscreen.FILLED_LOGIN_FORM)
@screenshot
def test_reset_password_view(self):
self.load_url('/'.join((self.get_base_url(), 'reset_password.html')))
assert self.login_screen_visible()
self.check_elements_of_form(loginscreen.RESET_PASSWORD_FORM)
self.check_alerts(loginscreen.RESET_PASSWORD_FORM)
username = loginscreen.PKEY
current_password = loginscreen.PASSWD_ITEST_USER
new_password = loginscreen.PASSWD_ITEST_USER_NEW
self.reset_password(username, current_password, new_password)
self.relogin_with_new_password()
@screenshot
def test_reset_password_view_with_redirect(self):
redir_url = self.get_base_url().lower()
encoded_redir_url = urllib.parse.urlencode({'url': redir_url})
target_url = '/'.join((self.get_base_url(), 'reset_password.html?{}'))
self.load_url(target_url.format(encoded_redir_url))
assert self.login_screen_visible()
self.check_elements_of_form(loginscreen.RESET_PASSWORD_FORM)
self.check_alerts(loginscreen.RESET_PASSWORD_FORM)
username = loginscreen.PKEY
current_password = loginscreen.PASSWD_ITEST_USER
new_password = loginscreen.PASSWD_ITEST_USER_NEW
self.reset_password(username, current_password, new_password,
link_text='Continue to next page',
link_url=redir_url,
)
self.relogin_with_new_password()
@screenshot
def test_reset_password_view_with_delayed_redirect(self):
redir_url = self.get_base_url().lower() + '/'
encoded_redir_url = urllib.parse.urlencode(
{'url': redir_url, 'delay': 5}
)
target_url = '/'.join((self.get_base_url(), 'reset_password.html?{}'))
self.load_url(target_url.format(encoded_redir_url))
assert self.login_screen_visible()
self.check_elements_of_form(loginscreen.RESET_PASSWORD_FORM)
self.check_alerts(loginscreen.RESET_PASSWORD_FORM)
username = loginscreen.PKEY
current_password = loginscreen.PASSWD_ITEST_USER
new_password = loginscreen.PASSWD_ITEST_USER_NEW
self.reset_password(username, current_password, new_password,
link_text='Continue to next page',
link_url=redir_url,
)
self.assert_notification(type='info',
assert_text='You will be redirected in ')
self.wait(3)
# check url after start delay timer, but before end
assert self.driver.current_url != redir_url
self.wait(5)
assert self.driver.current_url == redir_url
self.relogin_with_new_password()
@screenshot
def test_reset_password_and_login_view(self):
self.load_reset_and_login_view()
self.check_elements_of_form(loginscreen.RESET_AND_LOGIN_FORM)
self.check_alerts(loginscreen.RESET_AND_LOGIN_FORM)
# check click on 'Cancel' button
self.check_cancel()
self.button_click_on_login_screen('login')
self.wait_for_request()
# check if user is not logged
assert not self.logged_in()
current_password = loginscreen.PASSWD_ITEST_USER
new_password = loginscreen.PASSWD_ITEST_USER_NEW
# username is already here, do not fill up
self.reset_password(current_password=current_password,
new_password=new_password)
# waiting for auto login process
self.wait(5)
assert self.logged_in()
# check again if new password is valid
self.relogin_with_new_password()
@screenshot
def test_login_view(self):
self.load()
# check empty 'login' view
self.check_elements_of_form(loginscreen.EMPTY_LOGIN_FORM)
self.check_alerts(loginscreen.EMPTY_LOGIN_FORM)
# check non empty 'login' view
login_screen = self.get_login_screen()
username_field = self.get_input_field('username', login_screen)
username_field.send_keys(loginscreen.PKEY)
self.wait(0.5)
self.check_elements_of_form(loginscreen.LOGIN_FORM)
self.check_alerts(loginscreen.LOGIN_FORM)
@screenshot
def test_root_login(self):
"""
Verify logging as root, using admin password.
Root should be recognized as an alias for admin user.
Related: https://pagure.io/freeipa/issue/9226
"""
self.load()
assert self.login_screen_visible()
self.login(loginscreen.ROOT_PKEY, self.config['ipa_password'])
assert self.logged_in()
| 14,908
|
Python
|
.py
| 353
| 32.186969
| 79
| 0.613001
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,419
|
test_translation.py
|
freeipa_freeipa/ipatests/test_webui/test_translation.py
|
#
# Copyright (C) 2018 FreeIPA Contributors see COPYING for license
#
"""
Test translations
"""
from ipatests.test_webui.ui_driver import UI_driver
from ipatests.test_webui.ui_driver import screenshot
try:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
except ImportError:
pass
import pytest
from re import sub
from lxml import html
from ipalib import api, util
class ConfigPageBase(UI_driver):
"""
Base class to test translation of pages which are located at /ipa/config/
"""
page_name = ''
def init_app(self):
"""
Load a web page
"""
self.url = '/'.join((self.get_base_url(), self.page_name))
self.load()
def get_base_url(self):
"""
Get FreeIPA Web UI config url
"""
host = self.config.get('ipa_server')
if not host:
self.skip('FreeIPA server hostname not configured')
return 'https://%s/ipa/config' % host
def files_loaded(self):
"""
Test if dependencies were loaded. (Checks if page has been rendered)
"""
indicator = self.find(".info-page", By.CSS_SELECTOR)
return indicator is not None
def load(self):
"""
Navigate to Web page and wait for loading of all dependencies.
"""
self.driver.get(self.url)
runner = self
WebDriverWait(self.driver, 10).until(
lambda d: runner.files_loaded()
)
def page_raw_source(self):
"""
Retrieve a raw source of the web page
"""
host = api.env.host
cacert = api.env.tls_ca_cert
conn = util.create_https_connection(host, cafile=cacert)
conn.request('GET', self.url)
response = conn.getresponse()
# check successful response from a server
assert response.status == 200
return response.read().decode('utf-8')
def has_no_child(self, tag, child_tag):
"""
Check if element with the given tag has no child with the given one
"""
parent = self.find("#{}".format(tag), By.CSS_SELECTOR)
if parent is None:
return True
child_element = self.find(".//{}".format(child_tag), By.XPATH, parent)
return child_element is None
def innerhtml(self, id):
"""
Extract html text from the current opened page by the given id
"""
dom_element = self.find("#{}".format(id), By.CSS_SELECTOR)
return dom_element.get_attribute('innerHTML').split('\n')
def innerhtml_noscript(self, id, raw_page):
"""
Extract html text from the given raw source of the page under the
'noscript' html tag with the given id
"""
html_tree = html.fromstring(raw_page)
noscript_tree = html_tree.xpath(
"//div[@id='{}']/noscript/*".format(id)
)
noscript_html_text = ''.join([html.tostring(elem, encoding="unicode")
for elem in noscript_tree])
noscript_html = []
# remove trailing whitespaces between close and open tags
for html_row in noscript_html_text.split('\n'):
noscript_html.append(sub('^[ ]+(?=(<|[ ]*$))', '', html_row))
return noscript_html
def check_noscript_innerhtml(self, html_id):
"""
Compare inner html under enabled javascript and disabled one
"""
# check if js is enabled in browser
assert self.has_no_child(html_id, 'noscript')
html_js_enabled = self.innerhtml(html_id)
raw_page = self.page_raw_source()
html_js_disabled = self.innerhtml_noscript(html_id, raw_page)
assert html_js_enabled == html_js_disabled
@pytest.mark.tier1
class TestSsbrowserPage(ConfigPageBase):
"""
Test translation of ssbrowser.html page
"""
page_name = 'ssbrowser.html'
@screenshot
def test_long_text_of_ssbrowser_page(self):
"""
Tests whether the text from '@i18n:ssbrowser-page' is synced
against '<noscript>' tag to ensure a similarity of the behavior.
"""
self.init_app()
self.check_noscript_innerhtml('ssbrowser-msg')
@pytest.mark.tier1
class TestUnauthorizedPage(ConfigPageBase):
"""
Test translation of unauthorized.html page
"""
page_name = 'unauthorized.html'
@screenshot
def test_long_text_of_unauthorized_page(self):
"""
Tests whether the text from '@i18n:unauthorized-page' is synced
against '<noscript>' tag to ensure a similarity of the behavior.
"""
self.init_app()
self.check_noscript_innerhtml('unauthorized-msg')
| 4,731
|
Python
|
.py
| 132
| 28.257576
| 78
| 0.622922
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,420
|
data_pwpolicy.py
|
freeipa_freeipa/ipatests/test_webui/data_pwpolicy.py
|
#
# Copyright (C) 2018 FreeIPA Contributors see COPYING for license
#
import ipatests.test_webui.data_group as group
ENTITY = 'pwpolicy'
DEFAULT_POLICY = 'global_policy'
DATA = {
'pkey': 'admins',
'add': [
('combobox', 'cn', 'admins'),
('textbox', 'cospriority', '364'),
],
'mod': [
('textbox', 'krbmaxpwdlife', '3000'),
('textbox', 'krbminpwdlife', '1'),
('textbox', 'krbpwdhistorylength', '0'),
('textbox', 'krbpwdmindiffchars', '2'),
('textbox', 'krbpwdminlength', '2'),
('textbox', 'krbpwdmaxfailure', '15'),
('textbox', 'krbpwdfailurecountinterval', '5'),
('textbox', 'krbpwdlockoutduration', '3600'),
('textbox', 'cospriority', '365'),
],
}
PKEY1 = group.PKEY
DATA1 = {
'pkey': group.PKEY,
'add': [
('combobox', 'cn', group.PKEY),
('textbox', 'cospriority', '1'),
],
}
PKEY2 = group.PKEY2
DATA2 = {
'pkey': group.PKEY2,
'add': [
('combobox', 'cn', group.PKEY2),
('textbox', 'cospriority', '2'),
],
}
PKEY3 = group.PKEY3
DATA3 = {
'pkey': group.PKEY3,
'add': [
('combobox', 'cn', group.PKEY3),
('textbox', 'cospriority', '3'),
],
}
PKEY6 = group.PKEY6
DATA_RESET = {
'pkey': group.PKEY6,
'add': [
('combobox', 'cn', group.PKEY6),
('textbox', 'cospriority', '6'),
],
'mod': [
('textbox', 'krbmaxpwdlife', '1000'),
('textbox', 'krbminpwdlife', '2'),
('textbox', 'krbpwdhistorylength', '0'),
('textbox', 'krbpwdmindiffchars', '3'),
('textbox', 'krbpwdminlength', '4'),
('textbox', 'krbpwdmaxfailure', '17'),
('textbox', 'krbpwdfailurecountinterval', '4'),
('textbox', 'krbpwdlockoutduration', '4200'),
('textbox', 'cospriority', '38'),
('textbox', 'passwordgracelimit', '42'),
],
}
PKEY_SPECIAL_CHAR = group.PKEY_SPECIAL_CHAR_GROUP
DATA_SPECIAL_CHAR = {
'pkey': group.PKEY_SPECIAL_CHAR_GROUP,
'add': [
('combobox', 'cn', group.PKEY_SPECIAL_CHAR_GROUP),
('textbox', 'cospriority', '7'),
],
}
PKEY7 = group.PKEY4
DATA7 = {
'pkey': group.PKEY4,
'add': [
('combobox', 'cn', group.PKEY4),
('textbox', 'cospriority', '4'),
],
}
PKEY8 = group.PKEY
DATA8 = {
'pkey': PKEY8,
'add': [
('combobox', 'cn', PKEY8),
('textbox', 'cospriority', '364'),
],
'mod': [
('textbox', 'krbmaxpwdlife', '3000'),
('textbox', 'krbminpwdlife', '1'),
('textbox', 'krbpwdhistorylength', '0'),
('textbox', 'krbpwdmindiffchars', '2'),
('textbox', 'krbpwdminlength', '2'),
('textbox', 'krbpwdmaxfailure', '15'),
('textbox', 'krbpwdfailurecountinterval', '5'),
('textbox', 'krbpwdlockoutduration', '3600'),
('textbox', 'cospriority', '364'),
('textbox', 'passwordgracelimit', '42'),
],
}
| 2,947
|
Python
|
.py
| 104
| 22.625
| 66
| 0.541828
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,421
|
test_selinuxusermap.py
|
freeipa_freeipa/ipatests/test_webui/test_selinuxusermap.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/>.
"""
SELinux user map tests
"""
from ipaplatform.constants import constants as platformconstants
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_selinuxusermap as selinuxmap
import ipatests.test_webui.data_hostgroup as hostgroup
import ipatests.test_webui.data_hbac as hbac
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
RULE_ALR_EXIST = 'SELinux User Map rule with name "{}" already exists'
RULE_UPDATED = 'SELinux User Map {} updated'
RULE_ADDED = 'SELinux User Map successfully added'
INVALID_SEUSER = 'SELinux user {} not found in ordering list (in config)'
INVALID_MCS = ("invalid 'selinuxuser': Invalid MCS value, must match {}, "
"where max category {}").format(
platformconstants.SELINUX_MCS_REGEX,
platformconstants.SELINUX_MCS_MAX)
INVALID_MLS = ("invalid 'selinuxuser': Invalid MLS value, must match {}, "
"where max level {}").format(
platformconstants.SELINUX_MLS_REGEX,
platformconstants.SELINUX_MLS_MAX)
HBAC_DEL_ERR = ('{} cannot be deleted because SELinux User Map {} requires '
'it')
HBAC_MEMBER_ERR = 'HBAC rule and local members cannot both be set'
BATCH_ERR = 'Some operations failed.'
@pytest.mark.tier1
class test_selinuxusermap(UI_driver):
@screenshot
def test_crud(self):
"""
Basic CRUD: selinuxusermap
"""
self.init_app()
self.basic_crud(selinuxmap.ENTITY, selinuxmap.DATA)
@screenshot
def test_mod(self):
"""
Mod: selinuxusermap
"""
self.init_app()
host = host_tasks()
host.driver = self.driver
host.config = self.config
host.prep_data()
host.prep_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.close_notifications()
self.add_record(HOST_ENTITY, host.data2, navigate=False)
self.close_notifications()
self.add_record(hostgroup.ENTITY, hostgroup.DATA)
self.add_record(hostgroup.ENTITY, hostgroup.DATA2, navigate=False)
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA)
self.navigate_to_record(selinuxmap.PKEY)
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
for t in tables:
table = t[0]
keys = t[1]
self.add_table_associations(table, [keys[0]], confirm_btn='cancel')
# cleanup
# -------
self.delete(selinuxmap.ENTITY, [selinuxmap.DATA])
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])
@screenshot
def test_actions(self):
"""
Test SELinux user map actions
"""
self.init_app()
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA)
self.navigate_to_record(selinuxmap.PKEY)
self.disable_action()
self.enable_action()
self.delete_action(selinuxmap.ENTITY, selinuxmap.PKEY)
@screenshot
def test_misc(self):
"""
Test various miscellaneous test cases under one roof to save init time
"""
self.init_app()
# test add and add another record
self.add_record(selinuxmap.ENTITY, [selinuxmap.DATA, selinuxmap.DATA2])
# test delete multiple records
self.delete_record([selinuxmap.PKEY, selinuxmap.PKEY2])
# test add and cancel adding record
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA,
dialog_btn='cancel')
# test add and edit record
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA,
dialog_btn='add_and_edit')
# test add duplicate rule (should FAIL)
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA, negative=True,
pre_delete=False)
self.assert_last_error_dialog(RULE_ALR_EXIST.format(selinuxmap.PKEY))
self.close_all_dialogs()
# test add disabled HBAC rule to SElinux rule
self.add_record(hbac.RULE_ENTITY, hbac.RULE_DATA)
self.navigate_to_record(hbac.RULE_PKEY)
self.disable_action()
self.navigate_to_record(selinuxmap.PKEY, entity=selinuxmap.ENTITY)
self.facet_button_click('refresh')
self.select_combobox('seealso', hbac.RULE_PKEY)
self.facet_button_click('save')
self.wait_for_request()
self.assert_notification(assert_text=RULE_UPDATED.format(
selinuxmap.PKEY))
self.close_all_dialogs()
# test deleting HBAC rule used in SELinux user map (should FAIL)
self.delete(hbac.RULE_ENTITY, [hbac.RULE_DATA])
self.assert_last_error_dialog(
HBAC_DEL_ERR.format(hbac.RULE_PKEY, selinuxmap.PKEY), details=True)
self.close_all_dialogs()
self.select_record(hbac.RULE_PKEY, unselect=True)
# test adding user to SELinux map together with HBAC rule (should FAIL)
self.navigate_to_record(selinuxmap.PKEY, entity=selinuxmap.ENTITY)
self.add_table_associations('memberuser_user', ['admin'],
negative=True)
self.assert_last_error_dialog(BATCH_ERR)
self.close_all_dialogs()
# test adding HBAC rule together with user (should FAIL)
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA2)
self.navigate_to_record(selinuxmap.PKEY2)
self.add_table_associations('memberuser_user', ['admin'],
negative=True)
self.select_combobox('seealso', hbac.RULE_PKEY)
self.facet_button_click('save')
self.assert_last_error_dialog(HBAC_MEMBER_ERR)
self.close_all_dialogs()
# test add rule without "SELinux user" (requires the field)
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA_FIELD_REQUIRED,
negative=True)
self.assert_field_validation_required(field='ipaselinuxuser')
self.close_all_dialogs()
# test add rule with non-existent SELinux user
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA_NON_EXIST_SEUSER,
negative=True)
self.assert_last_error_dialog(expected_err=INVALID_SEUSER.format(
selinuxmap.DATA_NON_EXIST_SEUSER['add'][1][2]))
self.close_all_dialogs()
# test add invalid MCS
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA_INVALID_MCS,
negative=True)
self.assert_last_error_dialog(expected_err=INVALID_MCS)
self.close_all_dialogs()
# test add invalid MLS
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA_INVALID_MLS,
negative=True)
self.assert_last_error_dialog(expected_err=INVALID_MLS)
self.close_all_dialogs()
# test search SELinux usermap
self.find_record(selinuxmap.ENTITY, selinuxmap.DATA)
# test disable enable multiple SELinux rules
self.select_multiple_records([selinuxmap.DATA, selinuxmap.DATA2])
self.facet_button_click('disable')
self.dialog_button_click('ok')
self.assert_notification(assert_text='2 item(s) disabled')
self.close_notifications()
self.assert_record_value('Disabled',
[selinuxmap.PKEY, selinuxmap.PKEY2],
'ipaenabledflag')
self.select_multiple_records([selinuxmap.DATA, selinuxmap.DATA2])
self.facet_button_click('enable')
self.dialog_button_click('ok')
self.assert_notification(assert_text='2 item(s) enabled')
self.close_notifications()
self.assert_record_value('Enabled',
[selinuxmap.PKEY, selinuxmap.PKEY2],
'ipaenabledflag')
self.delete(selinuxmap.ENTITY, [selinuxmap.DATA])
# test add / delete SELinux usermap confirming using ENTER key
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA, 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=RULE_ADDED)
self.assert_record(selinuxmap.PKEY)
self.close_notifications()
self.delete_record(selinuxmap.PKEY, 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(selinuxmap.PKEY, negative=True)
self.close_notifications()
# cleanup
self.delete(selinuxmap.ENTITY, [selinuxmap.DATA2])
self.delete(hbac.RULE_ENTITY, [hbac.RULE_DATA])
@screenshot
def test_add_different_rules(self):
"""
Test adding different SELinux usermap rules
"""
self.init_app()
self.navigate_to_entity('config')
old_selinux_order = self.get_field_value('ipaselinuxusermaporder')
new_selinux_order = '{}${}${}${}${}'.format(
old_selinux_order,
selinuxmap.DATA_MLS_RANGE['add'][1][2],
selinuxmap.DATA_MCS_RANGE['add'][1][2],
selinuxmap.DATA_MCS_COMMAS['add'][1][2],
selinuxmap.DATA_MLS_SINGLE_VAL['add'][1][2])
self.fill_input('ipaselinuxusermaporder', new_selinux_order)
self.facet_button_click('save')
# test add MLS range rule
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA_MLS_RANGE)
self.assert_record(selinuxmap.PKEY_MLS_RANGE)
# test add MCS range rule
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA_MCS_RANGE)
self.assert_record(selinuxmap.PKEY_MCS_RANGE)
# test add MCS rule with commas
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA_MCS_COMMAS)
self.assert_record(selinuxmap.PKEY_MCS_COMMAS)
# test add MLS single value rule
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA_MLS_SINGLE_VAL)
self.assert_record(selinuxmap.PKEY_MLS_SINGLE_VAL)
# restore original SELinux user map order
self.navigate_to_entity('config')
self.fill_input('ipaselinuxusermaporder', old_selinux_order)
self.facet_button_click('save')
# cleanup
self.delete(selinuxmap.ENTITY,
[selinuxmap.DATA_MLS_RANGE,
selinuxmap.DATA_MCS_RANGE,
selinuxmap.DATA_MCS_COMMAS,
selinuxmap.DATA_MLS_SINGLE_VAL]
)
@screenshot
def test_undo_refresh_reset_update_cancel(self):
"""
Test undo/refresh/reset/update/cancel buttons
"""
self.init_app()
mod_description = (selinuxmap.DATA['mod'][0][2])
# test selinux usermap undo button
self.add_record(selinuxmap.ENTITY, selinuxmap.DATA)
self.navigate_to_record(selinuxmap.PKEY)
self.fill_fields(selinuxmap.DATA['mod'])
self.click_undo_button('description')
self.verify_btn_action(mod_description)
# test refresh button
self.fill_fields(selinuxmap.DATA['mod'], undo=True)
self.facet_button_click('refresh')
self.verify_btn_action(mod_description)
# test reset button
self.mod_record(selinuxmap.ENTITY, selinuxmap.DATA, facet_btn='revert')
self.wait_for_request()
self.verify_btn_action(mod_description)
# test update button
self.fill_fields(selinuxmap.DATA['mod'], undo=True)
self.facet_button_click('refresh')
self.verify_btn_action(mod_description)
# test reset button after trying to leave the details page
self.fill_fields(selinuxmap.DATA2['mod'], undo=True)
self.click_on_link('SELinux User Maps')
self.dialog_button_click('revert')
self.navigate_to_record(selinuxmap.PKEY)
self.verify_btn_action(mod_description)
self.wait_for_request(n=2)
# test update button after trying to leave the details page
self.fill_fields(selinuxmap.DATA['mod'], undo=True)
self.click_on_link('SELinux User Maps')
self.dialog_button_click('save')
self.close_notifications()
self.navigate_to_record(selinuxmap.PKEY)
self.verify_btn_action(mod_description, negative=True)
self.wait_for_request(n=2)
# cleanup
self.delete(selinuxmap.ENTITY, [selinuxmap.DATA])
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
| 14,827
|
Python
|
.py
| 322
| 36.568323
| 79
| 0.651166
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,422
|
test_automount.py
|
freeipa_freeipa/ipatests/test_webui/test_automount.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/>.
"""
Automount tests
"""
from ipatests.test_webui.ui_driver import UI_driver, screenshot
try:
from selenium.webdriver.common.keys import Keys
except ImportError:
pass
import pytest
LOC_ENTITY = 'automountlocation'
MAP_ENTITY = 'automountmap'
KEY_ENTITY = 'automountkey'
LOC_PKEY = 'itestloc'
LOC_DATA = {
'pkey': LOC_PKEY,
'add': [
('textbox', 'cn', LOC_PKEY),
],
}
MAP_PKEY = 'itestmap'
MAP_DATA = {
'pkey': MAP_PKEY,
'add': [
('textbox', 'automountmapname', MAP_PKEY),
('textarea', 'description', 'map desc'),
],
'mod': [
('textarea', 'description', 'map desc mod'),
]
}
KEY_PKEY = 'itestkey'
KEY_DATA = {
'pkey': KEY_PKEY,
'add': [
('textbox', 'automountkey', KEY_PKEY),
('textbox', 'automountinformation', '/itest/key'),
],
'mod': [
('textbox', 'automountinformation', '/itest/key2'),
]
}
DIRECT_MAPS = [
{
'pkey': 'map1',
'add': [
('radio', 'method', 'add'),
('textbox', 'automountmapname', 'map1'),
('textarea', 'description', 'foobar'),
],
},
{
'pkey': 'map2',
'add': [
('radio', 'method', 'add'),
('textbox', 'automountmapname', 'map2'),
('textarea', 'description', 'foobar'),
],
},
{
'pkey': 'map3',
'add': [
('radio', 'method', 'add'),
('textbox', 'automountmapname', 'map3'),
('textarea', 'description', 'foobar'),
],
},
{
'pkey': 'map4',
'add': [
('radio', 'method', 'add'),
('textbox', 'automountmapname', 'map4'),
('textarea', 'description', 'foobar'),
],
},
]
INDIRECT_MAPS = [
{
'pkey': 'map1',
'add': [
('radio', 'method', 'add'),
('textbox', 'automountmapname', 'map1'),
('textarea', 'description', 'foobar'),
],
},
{
'pkey': 'map2',
'add': [
('radio', 'method', 'add_indirect'),
('textbox', 'automountmapname', 'map2'),
('textarea', 'description', 'foobar'),
('textbox', 'key', 'mount1'),
('textbox', 'parentmap', 'map1'),
],
'mod': [
('textarea', 'description', 'modified'),
]
},
{
'pkey': 'map3',
'add': [
('radio', 'method', 'add_indirect'),
('textbox', 'automountmapname', 'map3'),
('textarea', 'description', 'foobar'),
('textbox', 'key', 'mount2'),
('textbox', 'parentmap', 'map1'),
],
},
{
'pkey': 'map4',
'add': [
('radio', 'method', 'add_indirect'),
('textbox', 'automountmapname', 'map4'),
('textarea', 'description', 'foobar'),
('textbox', 'key', 'mount3'),
('textbox', 'parentmap', 'map1'),
],
},
]
DIRECT_MAP_MOD = {
'pkey': 'map1',
'add': [
('radio', 'method', 'add'),
('textbox', 'automountmapname', 'map1'),
('textarea', 'description', 'desc'),
],
'mod': [
('textarea', 'description', 'modified'),
]
}
INDIRECT_MAP_MOD = {
'pkey': 'map1',
'add': [
('radio', 'method', 'add_indirect'),
('textbox', 'automountmapname', 'map1'),
('textarea', 'description', 'desc'),
('textbox', 'key', 'mount1'),
],
'mod': [
('textarea', 'description', 'modified'),
]
}
class Location:
def __init__(self, location, ui):
self.ui = ui
self.location = location
def __enter__(self):
self.ui.add_record(LOC_ENTITY, self.location)
self.ui.navigate_to_record(self.location['pkey'])
return self
def __exit__(self, *args):
self.ui.delete(LOC_ENTITY, [self.location])
return False
@pytest.mark.tier1
class TestAutomount(UI_driver):
@pytest.fixture(autouse=True)
def automount_setup(self, ui_driver_fsetup):
self.init_app()
def add_key(self, key, mount_info, **kwargs):
self.add_record(MAP_ENTITY, {
'pkey': key,
'add': [
('textbox', 'automountkey', key),
('textbox', 'automountinformation', mount_info),
],
}, facet='keys', **kwargs)
def _add_record_with_enter_key(self, record):
self.delete_record(record['pkey'])
self.assert_no_dialog()
self.facet_button_click('add')
self.assert_dialog('add')
self.fill_fields(record['add'])
dialog = self.get_dialog('add')
dialog.send_keys(Keys.ENTER)
self.wait_for_request()
def _delete_record_with_enter_key(self, pkey):
assert self.has_record(pkey)
self.select_record(pkey)
self.facet_button_click('remove')
dialog = self.get_dialog('add')
dialog.send_keys(Keys.ENTER)
self.wait_for_request(n=2)
self.wait()
@screenshot
def test_crud(self):
"""
Basic CRUD: automount
"""
self.init_app()
# location
self.basic_crud(LOC_ENTITY, LOC_DATA,
default_facet='maps',
delete=False,
breadcrumb='Automount Locations'
)
# map
self.navigate_to_record(LOC_PKEY)
self.basic_crud(MAP_ENTITY, MAP_DATA,
parent_entity=LOC_ENTITY,
search_facet='maps',
default_facet='keys',
delete=False,
navigate=False,
breadcrumb=LOC_PKEY,
)
# key
self.navigate_to_record(MAP_PKEY)
self.basic_crud(KEY_ENTITY, KEY_DATA,
parent_entity=MAP_ENTITY,
search_facet='keys',
navigate=False,
breadcrumb=MAP_PKEY,
)
# delete
self.navigate_by_breadcrumb(LOC_PKEY)
self.delete_record(MAP_PKEY)
# test indirect maps
direct_pkey = 'itest-direct'
indirect_pkey = 'itest-indirect'
self.add_record(LOC_ENTITY,
{
'pkey': direct_pkey,
'add': [
('radio', 'method', 'add'),
('textbox', 'automountmapname', direct_pkey),
('textarea', 'description', 'foobar'),
],
},
facet='maps',
navigate=False)
self.add_record(LOC_ENTITY,
{
'pkey': indirect_pkey,
'add': [
('radio', 'method', 'add_indirect'),
('textbox', 'automountmapname', indirect_pkey),
('textarea', 'description', 'foobar'),
('textbox', 'key', 'baz'),
('textbox', 'parentmap', direct_pkey),
],
},
facet='maps',
navigate=False)
self.assert_record(direct_pkey)
self.assert_record(indirect_pkey)
# delete
self.delete_record(direct_pkey)
self.delete_record(indirect_pkey)
self.navigate_by_breadcrumb('Automount Locations')
self.delete_record(LOC_PKEY)
@screenshot
def test_add_location_dialog(self):
"""
Test 'Add Automount Location' dialog behaviour
"""
pkeys = ['loc1', 'loc2', 'loc3', 'loc4']
locations = [{
'pkey': pkey,
'add': [('textbox', 'cn', pkey)]
} for pkey in pkeys]
self.navigate_to_entity(LOC_ENTITY)
# Add and add another
self.add_record(LOC_ENTITY, [locations[0], locations[1]],
navigate=False)
self.assert_record(locations[0]['pkey'])
self.assert_record(locations[1]['pkey'])
# Add and edit
self.add_record(LOC_ENTITY, locations[2], dialog_btn='add_and_edit',
navigate=False)
self.assert_facet(LOC_ENTITY, facet='maps')
# Cancel dialog
self.add_record(LOC_ENTITY, locations[3], dialog_btn='cancel')
self.assert_record(locations[3]['pkey'], negative=True)
# Add duplicated
self.add_record(LOC_ENTITY, locations[0], navigate=False,
negative=True, pre_delete=False)
self.assert_last_error_dialog(
'automount location with name "{}" already exists'
.format(locations[0]['pkey'])
)
self.close_all_dialogs()
# Missing field
self.add_record(LOC_ENTITY, {'pkey': 'loc5', 'add': []},
navigate=False, negative=True)
assert self.has_form_error('cn')
self.close_all_dialogs()
# Delete multiple locations
self.delete_record(pkeys)
@screenshot
@pytest.mark.parametrize('maps', [DIRECT_MAPS, INDIRECT_MAPS])
def test_add_map_dialog(self, maps):
"""
Test 'Add Automount Map' dialog behaviour
"""
with Location(LOC_DATA, ui=self):
# Add and add another
self.add_record(LOC_ENTITY, [maps[0], maps[1]],
facet='maps', navigate=False)
self.assert_record(maps[0]['pkey'])
self.assert_record(maps[1]['pkey'])
# Add and edit
self.add_record(LOC_ENTITY, maps[2], dialog_btn='add_and_edit',
facet='maps', navigate=False)
self.assert_facet(MAP_ENTITY, facet='keys')
# Cancel dialog
self.add_record(LOC_ENTITY, maps[3], facet='maps',
dialog_btn='cancel')
self.assert_record(maps[3]['pkey'], negative=True)
# Delete multiple maps
self.delete_record([m['pkey'] for m in maps])
@screenshot
def test_add_indirect_map_with_missing_fields(self):
"""
Test creating automount map without mapname and mountpoint
"""
maps = {
'automountmapname': {
'pkey': 'map1',
'add': [
('radio', 'method', 'add_indirect'),
('textarea', 'description', 'desc'),
('textbox', 'key', 'mount1'),
],
},
'key': {
'pkey': 'map2',
'add': [
('radio', 'method', 'add_indirect'),
('textbox', 'automountmapname', 'map1'),
('textarea', 'description', 'desc'),
],
}
}
with Location(LOC_DATA, ui=self):
for missing_field, map_data in maps.items():
self.add_record(LOC_ENTITY, map_data, negative=True,
facet='maps', navigate=False)
assert self.has_form_error(missing_field)
self.dialog_button_click('cancel')
self.assert_record(map_data['pkey'], negative=True)
@screenshot
def test_add_duplicated_indirect_map(self):
"""
Test creating indirect automount map with duplicated field values
"""
original_name = 'map1'
original_key = 'mount1'
with Location(LOC_DATA, ui=self):
self.add_record(LOC_ENTITY, {
'pkey': original_name,
'add': [
('radio', 'method', 'add_indirect'),
('textbox', 'automountmapname', original_name),
('textarea', 'description', 'desc'),
('textbox', 'key', original_key),
],
}, facet='maps', navigate=False)
self.add_record(LOC_ENTITY, {
'pkey': 'map2',
'add': [
('radio', 'method', 'add_indirect'),
('textbox', 'automountmapname', original_name),
('textarea', 'description', 'desc'),
('textbox', 'key', 'mount2'),
],
}, negative=True, facet='maps', navigate=False, pre_delete=False)
self.assert_last_error_dialog(
'automount map with name "{}" already exists'
.format(original_name)
)
self.close_all_dialogs()
self.add_record(LOC_ENTITY, {
'pkey': 'map3',
'add': [
('radio', 'method', 'add_indirect'),
('textbox', 'automountmapname', 'map3'),
('textarea', 'description', 'desc'),
('textbox', 'key', original_key),
],
}, negative=True, facet='maps', navigate=False, pre_delete=False)
self.assert_last_error_dialog(
'key named {} already exists'.format(original_key)
)
self.close_all_dialogs()
@screenshot
@pytest.mark.parametrize('map_data', [DIRECT_MAP_MOD, INDIRECT_MAP_MOD])
def test_modify_map(self, map_data):
"""
Test automount map 'Settings' tab
"""
with Location(LOC_DATA, ui=self):
self.add_record(LOC_ENTITY, map_data,
facet='maps', navigate=False)
self.navigate_to_record(map_data['pkey'])
self.switch_to_facet('details')
# Refresh
self.fill_fields(map_data['mod'], undo=True)
self.assert_facet_button_enabled('refresh')
self.facet_button_click('refresh')
self.wait_for_request()
self.assert_facet_button_enabled('refresh')
# Revert
self.mod_record(MAP_ENTITY, map_data, facet_btn='revert')
@screenshot
def test_add_key_dialog(self):
"""
Test 'Add Automount Key' dialog behaviour
"""
pkeys = ['key1', 'key2', 'key3', 'key4']
keys = [
{
'pkey': pkey,
'add': [
('textbox', 'automountkey', pkey),
('textbox', 'automountinformation', '/itest/%s' % pkey),
],
} for pkey in pkeys
]
with Location(LOC_DATA, ui=self):
self.add_record(LOC_ENTITY, MAP_DATA, facet='maps', navigate=False)
self.navigate_to_record(MAP_PKEY)
# Add and add another
self.add_record(MAP_ENTITY, [keys[0], keys[1]],
facet='keys', navigate=False)
self.assert_record(keys[0]['pkey'])
self.assert_record(keys[1]['pkey'])
# Add and edit
self.add_record(MAP_ENTITY, keys[2], dialog_btn='add_and_edit',
facet='keys', navigate=False)
self.assert_facet(KEY_ENTITY, facet='details')
# Cancel dialog
self.add_record(MAP_ENTITY, keys[3], facet='keys',
dialog_btn='cancel')
self.assert_record(keys[3]['pkey'], negative=True)
# Delete multiple keys
self.delete_record(pkeys)
@screenshot
def test_add_key_with_missing_fields(self):
"""
Test creating automount key without key name and mount information
"""
keys = {
'automountkey': {
'pkey': 'key1',
'add': [('textbox', 'automountinformation', '/itest/key')],
},
'automountinformation': {
'pkey': 'key2',
'add': [('textbox', 'automountkey', 'key2')],
},
}
with Location(LOC_DATA, ui=self):
self.add_record(LOC_ENTITY, MAP_DATA, facet='maps', navigate=False)
self.navigate_to_record(MAP_PKEY)
for missing_field, key in keys.items():
self.add_record(MAP_ENTITY, key, negative=True,
facet='keys', navigate=False)
assert self.has_form_error(missing_field)
self.dialog_button_click('cancel')
self.assert_record(key['pkey'], negative=True)
@screenshot
def test_add_duplicated_key(self):
"""
Test creating automount key with duplicated field values
"""
with Location(LOC_DATA, ui=self):
self.add_record(LOC_ENTITY, MAP_DATA, facet='maps', navigate=False)
self.navigate_to_record(MAP_PKEY)
key = 'mount1'
self.add_key(key, '/itest/key', navigate=False)
self.add_key(key, '/itest/key2', negative=True, navigate=False,
pre_delete=False)
self.assert_last_error_dialog(
'key named {} already exists'.format(key)
)
self.close_all_dialogs()
@screenshot
def test_modify_key(self):
"""
Test automount key 'Settings'
"""
with Location(LOC_DATA, ui=self):
self.add_record(LOC_ENTITY, MAP_DATA, facet='maps', navigate=False)
self.navigate_to_record(MAP_PKEY)
self.add_record(MAP_ENTITY, KEY_DATA, facet='keys', navigate=False)
self.navigate_to_record(KEY_PKEY)
# Refresh
self.fill_fields(KEY_DATA['mod'])
self.assert_facet_button_enabled('refresh')
self.facet_button_click('refresh')
self.wait_for_request()
self.assert_facet_button_enabled('refresh')
# Revert
self.mod_record(KEY_ENTITY, KEY_DATA, facet_btn='revert')
@screenshot
def test_confirm_dialogs_with_enter_key(self):
"""
Test dialogs can be closed by pressing ENTER
"""
# Add location
self.navigate_to_entity(LOC_ENTITY, 'search')
self._add_record_with_enter_key(LOC_DATA)
# Add map
self.navigate_to_record(LOC_PKEY)
self._add_record_with_enter_key(MAP_DATA)
# Add key
self.navigate_to_record(MAP_PKEY)
self._add_record_with_enter_key(KEY_DATA)
# Delete key
self._delete_record_with_enter_key(KEY_PKEY)
# Delete map
self.navigate_by_breadcrumb(LOC_PKEY)
self._delete_record_with_enter_key(MAP_PKEY)
# Delete location
self.navigate_to_entity(LOC_ENTITY)
self._delete_record_with_enter_key(LOC_PKEY)
| 19,588
|
Python
|
.py
| 533
| 25.138837
| 79
| 0.510652
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,423
|
test_service.py
|
freeipa_freeipa/ipatests/test_webui/test_service.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/>.
"""
Service tests
"""
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 pytest
try:
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
except ImportError:
pass
ENTITY = 'service'
@pytest.mark.tier1
class sevice_tasks(UI_driver):
def prep_data(self):
host = self.config.get('ipa_server')
realm = self.config.get('ipa_realm')
pkey = 'itest'
return {
'pkey': '%s/%s@%s' % (pkey, host, realm),
'add': [
('textbox', 'service', pkey),
('combobox', 'host', host)
],
'mod': [
('checkbox', 'ipakrbokasdelegate', None),
],
}
def load_file(self, path):
# ENHANCEMENT: generate csr dynamically
with open(path, 'r') as file_d:
content = file_d.read()
return content
def get_service_pkey(self, service, host=None):
if not host:
host = self.config.get('ipa_server')
realm = self.config.get('ipa_realm')
pkey = '{}/{}@{}'.format(service, host, realm)
return pkey
def add_host(self, hostname, dns_zone, force=False):
self.navigate_to_entity('host')
self.facet_button_click('add')
self.fill_textbox('hostname', hostname)
self.fill_textbox('dnszone', dns_zone)
if force:
self.check_option('force', 'checked')
self.dialog_button_click('add')
def add_service(self, service,
host=None,
textbox=None,
force=False,
cancel=False,
confirm=True):
if not host:
host = self.config.get('ipa_server')
self.navigate_to_entity(ENTITY)
self.facet_button_click('add')
self.select_combobox('service', service, combobox_input=textbox)
self.select_combobox('host', host)
if force:
self.wait(0.5)
self.check_option('force', 'checked')
if cancel:
self.dialog_button_click('cancel')
return
if not confirm:
return
self.dialog_button_click('add')
self.wait(0.3)
self.assert_no_error_dialog()
def run_keytab_on_host(self, principal, action):
"""
Run ipa-get/rmkeytab command on UI host in order to test whether
we have the key un/provisioned.
Actions:
'get' for /usr/sbin/ipa-getkeytab
'rm' for /usr/sbin/ipa-rmkeytab
"""
kt_path = '/tmp/test.keytab'
if action == 'get':
cmd = '/usr/sbin/ipa-getkeytab -p {} -k {}'.format(principal,
kt_path)
self.run_cmd_on_ui_host(cmd)
elif action == 'rm':
cmd = '/usr/sbin/ipa-rmkeytab -p {} -k {}'.format(principal,
kt_path)
kt_rm_cmd = 'rm -f {}'.format(kt_path)
self.run_cmd_on_ui_host(cmd)
self.run_cmd_on_ui_host(kt_rm_cmd)
else:
raise ValueError("Bad action specified")
@pytest.mark.tier1
class test_service(sevice_tasks):
@screenshot
def test_crud(self):
"""
Basic CRUD: service
"""
self.init_app()
data = self.prep_data()
self.basic_crud(ENTITY, data)
@screenshot
def test_certificates(self):
"""
Test service certificate actions
Requires to have CA installed.
"""
if not self.has_ca():
self.skip('CA is not configured')
self.init_app()
data = self.prep_data()
pkey = data.get('pkey')
hostname = self.config.get('ipa_server')
csr = generate_csr(hostname)
cert_widget_sel = "div.certificate-widget"
self.add_record(ENTITY, data)
self.navigate_to_record(pkey)
# cert request
self.action_list_action('request_cert', confirm=False)
# testing if cancel button works
self.dialog_button_click('cancel')
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 text area 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/hold cancel
self.action_list_action('revoke', confirm=False,
parents_css_sel=cert_widget_sel)
self.wait()
self.select('select', '6')
self.dialog_button_click('cancel')
# cert revoke/hold
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 cancel
self.action_list_action('remove_hold', confirm=False,
parents_css_sel=cert_widget_sel)
self.dialog_button_click('cancel')
# 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)
# cert revoke cancel
self.action_list_action('revoke', confirm=False,
parents_css_sel=cert_widget_sel)
self.wait()
self.select('select', '1')
self.dialog_button_click('cancel')
# cert revoke
self.action_list_action('revoke', confirm=False,
parents_css_sel=cert_widget_sel)
self.wait()
self.select('select', '1')
self.dialog_button_click('ok')
self.close_notifications()
self.wait_while_working(widget)
# 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 not is 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(pkey, data.get('del'))
@screenshot
def test_arbitrary_certificates(self):
"""
Test managing service arbitrary certificate.
"""
self.init_app()
data = self.prep_data()
pkey = data.get('pkey')
hostname = self.config.get('ipa_server')
cert = generate_certificate(hostname)
cert_widget_sel = "div.certificate-widget"
self.add_record(ENTITY, data)
self.close_notifications()
self.navigate_to_record(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')
self.fill_textarea('new_cert', cert)
self.dialog_button_click('ok')
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 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 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(pkey, data.get('del'))
@screenshot
def test_ca_less(self):
"""
Test service 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()
data = self.prep_data()
pkey = data.get('pkey')
self.add_record(ENTITY, data)
self.navigate_to_record(pkey)
self.assert_action_list_action('request_cert', visible=False)
self.navigate_by_breadcrumb('Services')
self.delete_record(pkey, data.get('del'))
@screenshot
def test_kerberos_flags(self):
"""
Test Kerberos flags
http://www.freeipa.org/page/V3/Kerberos_Flags
"""
pkey = self.get_service_pkey('HTTP')
name = 'ipakrbokasdelegate'
mod = {'mod': [('checkbox', name, None)]}
checked = ['checked']
self.init_app()
self.navigate_to_record(pkey, entity=ENTITY)
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, [])])
@screenshot
def test_add_remove_services(self):
"""
Test add/remove common services on default host
"""
self.init_app()
services = ['cifs', 'ftp', 'imap', 'libvirt', 'nfs', 'qpidd', 'smtp']
added_services = []
# add services
for service in services:
pkey = self.get_service_pkey(service)
self.add_service(service)
self.wait(0.5)
assert self.has_record(pkey)
added_services.append(pkey)
# delete single service
svc_tbd = added_services.pop()
self.delete_record(svc_tbd)
self.assert_notification()
assert not self.has_record(svc_tbd)
# delete multiple services (rest of them)
self.delete_record(added_services)
self.assert_notification()
for service in added_services:
assert not self.has_record(service)
@screenshot
def test_add_remove_services_force(self):
"""
Test add/remove services using force (on different host)
"""
self.init_app()
services = ['DNS', 'HTTP', 'ldap']
added_services = []
# add temp host without DNS
temp_host = 'host-no-dns.ipa.test'
self.add_host('host-no-dns', 'ipa.test', force=True)
for service in services:
pkey = self.get_service_pkey(service, host=temp_host)
self.add_service(service, host=temp_host, force=True)
assert self.has_record(pkey)
added_services.append(pkey)
# delete single service
svc_tbd = added_services.pop()
self.delete_record(svc_tbd)
self.assert_notification()
assert not self.has_record(svc_tbd)
# delete multiple services (rest of them)
self.delete_record(added_services)
self.assert_notification()
for service in added_services:
assert not self.has_record(service)
# host cleanup
self.navigate_to_entity('host')
self.delete_record(temp_host)
@screenshot
def test_add_custom_service(self):
"""
Test add custom service using textbox
"""
self.init_app()
pkey = self.get_service_pkey('test_service')
self.add_service('test_service', textbox='service')
assert self.has_record(pkey)
# service cleanup
self.delete_record(pkey)
self.assert_notification()
assert not self.has_record(pkey)
@screenshot
def test_cancel_adding_service(self):
"""
Test cancel when adding a service
"""
self.init_app()
pkey = self.get_service_pkey('cifs')
self.add_service('cifs', cancel=True)
assert not self.has_record(pkey)
@screenshot
def test_cancel_delete_service(self):
"""
Test cancel deleting a service
"""
self.init_app()
pkey = self.get_service_pkey('HTTP')
self.navigate_to_entity(ENTITY)
self.delete_record(pkey, confirm_btn='cancel')
assert self.has_record(pkey)
@screenshot
def test_cancel_add_delete_managedby_host(self):
"""
Test cancel/add/delete managed by host
"""
pkey = self.get_service_pkey('HTTP')
temp_host = 'host-no-dns.ipa.test'
self.init_app()
# add another host for "managedby" testing
self.add_host('host-no-dns', 'ipa.test', force=True)
self.navigate_to_record(pkey, entity=ENTITY)
self.add_associations([temp_host], facet='managedby_host',
confirm_btn='cancel')
self.add_associations([temp_host], facet='managedby_host',
delete=True)
# host cleanup
self.navigate_to_entity('host')
self.delete_record(temp_host)
@screenshot
def test_add_service_missing_hostname_field(self):
"""
Test add service "hostname" field required
"""
self.init_app()
self.navigate_to_entity(ENTITY)
self.facet_button_click('add')
self.select_combobox('service', 'cifs', combobox_input='service')
self.dialog_button_click('add')
host_elem = self.find(".widget[name='host']", By.CSS_SELECTOR)
self.assert_field_validation_required(parent=host_elem)
@screenshot
def test_add_service_missing_service_field(self):
"""
Test add service "service field required
"""
self.init_app()
host = self.config.get('ipa_server')
self.navigate_to_entity(ENTITY)
self.facet_button_click('add')
self.select_combobox('host', host)
self.dialog_button_click('add')
self.wait()
service_elem = self.find(".widget[name='service']", By.CSS_SELECTOR)
self.assert_field_validation_required(parent=service_elem)
@screenshot
def test_search_services(self):
"""
Search different services
"""
# keywords to search (find_record accepts data dict)
http_search = {'pkey': self.get_service_pkey('HTTP')}
ldap_search = {'pkey': self.get_service_pkey('ldap')}
dns_search = {'pkey': self.get_service_pkey('DNS')}
self.init_app()
self.navigate_to_entity(ENTITY)
self.find_record('service', http_search)
self.find_record('service', ldap_search)
self.find_record('service', dns_search)
@screenshot
def test_dropdown(self):
"""
Test service combobox dropdowns with UP/DOWN arrows
"""
self.init_app()
self.navigate_to_entity(ENTITY)
self.facet_button_click('add')
actions = ActionChains(self.driver)
actions.send_keys(Keys.ARROW_DOWN)
# all actions are performed at once with perform()
actions.send_keys(Keys.ARROW_DOWN).perform()
actions.send_keys(Keys.ENTER)
actions.send_keys(Keys.TAB)
actions.send_keys(Keys.ARROW_DOWN)
actions.send_keys(Keys.ARROW_DOWN)
actions.send_keys(Keys.ENTER).perform()
# evaluate value fields are not empty
service_cb = "input[name='service']"
service = self.find(service_cb, By.CSS_SELECTOR)
assert service.get_attribute('value') != ""
host_cb = "[name='host'].combobox-widget"
host = self.find(host_cb, By.CSS_SELECTOR)
assert host.get_attribute('value') != ""
@screenshot
def test_add_service_using_enter(self):
"""
Add a service using enter key
"""
self.init_app()
pkey = self.get_service_pkey('smtp')
self.add_service('smtp', confirm=False)
actions = ActionChains(self.driver)
actions.click()
actions.send_keys(Keys.ENTER).perform()
self.wait(1)
assert self.has_record(pkey)
# service cleanup
self.delete_record(pkey)
assert not self.has_record(pkey)
@screenshot
def test_delete_service_using_enter(self):
"""
Delete a service using enter key
"""
self.init_app()
pkey = self.get_service_pkey('smtp')
self.add_service('smtp')
assert self.has_record(pkey)
self.delete_record(pkey, confirm_btn=None)
actions = ActionChains(self.driver)
actions.send_keys(Keys.ENTER).perform()
self.wait(1)
assert not self.has_record(pkey)
@screenshot
def test_provision_unprovision_keytab(self):
"""
Test provision / unprovision keytab
Requires to run a ipa-get/rmkeytab on UI host.
"""
if not self.has_ca():
self.skip('CA is not configured')
hostname = self.config.get('ipa_server')
csr = generate_csr(hostname)
self.init_app()
pkey = self.get_service_pkey('cifs')
self.navigate_to_entity(ENTITY)
# provision service
self.add_service('cifs')
self.navigate_to_record(pkey, entity=ENTITY)
self.action_list_action('request_cert', confirm=False)
self.assert_dialog()
self.fill_text("textarea[name='csr'", csr)
self.dialog_button_click('issue')
self.run_keytab_on_host(pkey, 'get')
self.wait(1)
self.facet_button_click('refresh')
# assert key present
no_key_selector = 'div[name="kerberos-key-valid"] label'
provisioned_assert = 'Kerberos Key Present, Service Provisioned'
self.assert_text(no_key_selector, provisioned_assert)
# unprovision service
self.action_list_action('unprovision', confirm_btn='unprovision')
self.facet_button_click('refresh')
self.run_keytab_on_host(pkey, 'rm')
# assert key not present
no_key_selector = 'div[name="kerberos-key-missing"] label'
provisioned_assert = 'Kerberos Key Not Present'
self.assert_text(no_key_selector, provisioned_assert)
# service cleanup
self.navigate_to_entity(ENTITY)
self.delete_record(pkey)
| 22,479
|
Python
|
.py
| 554
| 29.84657
| 79
| 0.588238
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,424
|
task_range.py
|
freeipa_freeipa/ipatests/test_webui/task_range.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/>.
"""
Range tasks
"""
import uuid
from ipatests.test_webui.ui_driver import UI_driver
LOCAL_ID_RANGE = 'ipa-local'
TRUSTED_ID_RANGE = 'ipa-ad-trust'
class range_tasks(UI_driver):
BASE_RANGE_OVERLAPS_ERROR = (
"Constraint violation: "
"New base range overlaps with existing base range."
)
PRIMARY_RID_RANGE_OVERLAPS_ERROR = (
"Constraint violation: "
"New primary rid range overlaps with existing primary rid range."
)
SECONDARY_RID_RANGE_OVERLAPS_ERROR = (
"Constraint violation: "
"New secondary rid range overlaps with existing secondary rid range."
)
PRIMARY_AND_SECONDARY_RID_OVERLAP_ERROR = (
"invalid 'ID Range setup': "
"Primary RID range and secondary RID range cannot overlap"
)
DELETE_PRIMARY_LOCAL_RANGE_ERROR = (
"invalid 'ipabaseid,ipaidrangesize': range modification "
"leaving objects with ID out of the defined range is not allowed"
)
def get_shifts(self):
result = self.execute_api_from_ui('idrange_find', [], {})
idranges = result['result']['result']
max_id = 0
max_rid = 0
for idrange in idranges:
# IPA.TEST_subid_range is automatically created near the end
# of the allowed ids, taking from 2,147,483,648 to 4,294,836,224
# Ignore this range when looking for available ids otherwise
# we won't find any value < max baseid 4,294,967,295
if idrange['cn'][0].endswith("_subid_range"):
continue
size = int(idrange['ipaidrangesize'][0])
base_id = int(idrange['ipabaseid'][0])
id_end = base_id + size
rid_end = 0
if 'ipabaserid' in idrange:
base_rid = int(idrange['ipabaserid'][0])
rid_end = base_rid + size
if 'ipasecondarybaserid' in idrange:
secondary_base_rid = int(idrange['ipasecondarybaserid'][0])
rid_end = max(base_rid, secondary_base_rid) + size
if max_id < id_end:
max_id = id_end + 1000000
if max_rid < rid_end:
max_rid = rid_end + 1000000
self.max_id = max_id
self.max_rid = max_rid
def get_domain(self):
result = self.execute_api_from_ui('trust_find', [], {})
trusts = result['result']['result']
domain = None
if trusts:
domain = trusts[0]['cn']
return domain
def get_data(self, pkey=None, form_data=None, **kwargs):
if not pkey:
pkey = 'itest-range-{}'.format(uuid.uuid4().hex[:8])
if form_data:
form_data.cn = pkey
else:
form_data = self.get_add_form_data(pkey, **kwargs)
data = {
'pkey': pkey,
'add': form_data.serialize(),
'mod': [
('textbox', 'ipaidrangesize', str(form_data.size + 1)),
],
}
return data
def get_add_form_data(self, pkey, range_type=LOCAL_ID_RANGE, size=50,
domain=None, **kwargs):
"""
Generate RangeAddFormData instance with initial data based on existing
ID ranges.
:param kwargs: overrides default fields values (base_id, base_rid,
secondary_base_rid)
"""
shift = 100
base_id = kwargs.get('base_id', self.max_id + shift)
self.max_id = base_id + size
if 'base_rid' in kwargs:
base_rid = kwargs['base_rid']
else:
base_rid = self.max_rid + shift
self.max_rid = base_rid + size
secondary_base_rid = None
if not domain:
if 'secondary_base_rid' in kwargs:
secondary_base_rid = kwargs['secondary_base_rid']
else:
secondary_base_rid = self.max_rid + shift
self.max_rid = secondary_base_rid + size
return RangeAddFormData(
pkey, base_id, base_rid,
secondary_base_rid=secondary_base_rid,
range_type=range_type,
size=size,
domain=domain,
auto_private_groups=kwargs.get('auto_private_groups'),
callback=self.check_range_type_mod
)
def get_mod_form_data(self, **kwargs):
return RangeModifyFormData(**kwargs)
def check_range_type_mod(self, range_type):
if range_type == LOCAL_ID_RANGE:
self.assert_disabled("[name=ipanttrusteddomainname]")
self.assert_disabled("[name=ipasecondarybaserid]", negative=True)
elif range_type == TRUSTED_ID_RANGE:
self.assert_disabled("[name=ipanttrusteddomainname]",
negative=True)
self.assert_disabled("[name=ipasecondarybaserid]")
class RangeAddFormData:
"""
Class for storing and serializing of new ID Range form data.
Warning: Only for data transformation.
Do not put any additional logic here!
"""
def __init__(self, cn, base_id, base_rid=None, secondary_base_rid=None,
range_type=LOCAL_ID_RANGE, size=50, domain=None,
auto_private_groups='', callback=None):
self.cn = cn
self.base_id = base_id
self.base_rid = base_rid
self.secondary_base_rid = secondary_base_rid
self.range_type = range_type
self.size = size
self.domain = domain
self.auto_private_groups = auto_private_groups
self.callback = callback
def serialize(self):
serialized = [
('textbox', 'cn', self.cn),
('textbox', 'ipabaseid', str(self.base_id)),
('textbox', 'ipaidrangesize', str(self.size)),
('textbox', 'ipabaserid', str(self.base_rid)),
('radio', 'iparangetype', self.range_type),
('callback', self.callback, self.range_type),
]
if self.domain:
serialized.append(('textbox',
'ipanttrusteddomainname',
self.domain))
else:
serialized.append(('textbox',
'ipasecondarybaserid',
str(self.secondary_base_rid)))
if self.range_type != LOCAL_ID_RANGE:
serialized.append(('selectbox',
'ipaautoprivategroups',
self.auto_private_groups))
return serialized
class RangeModifyFormData:
"""
Class for storing and serializing of modified ID Range form data.
"""
def __init__(self, base_id=None, base_rid=None, secondary_base_rid=None,
size=None):
self.base_id = base_id
self.base_rid = base_rid
self.secondary_base_rid = secondary_base_rid
self.size = size
def serialize(self):
serialized = []
if self.base_id is not None:
serialized.append(('textbox', 'ipabaseid', str(self.base_id)))
if self.size is not None:
serialized.append(('textbox', 'ipaidrangesize', str(self.size)))
if self.base_rid is not None:
serialized.append(('textbox', 'ipabaserid', str(self.base_rid)))
if self.secondary_base_rid is not None:
serialized.append(('textbox',
'ipasecondarybaserid',
str(self.secondary_base_rid)))
return serialized
| 8,309
|
Python
|
.py
| 201
| 30.900498
| 79
| 0.585659
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,425
|
test_dns.py
|
freeipa_freeipa/ipatests/test_webui/test_dns.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/>.
"""
DNS tests
"""
from ipatests.test_webui.ui_driver import UI_driver
from ipatests.test_webui.ui_driver import screenshot
from ipatests.test_webui.data_dns import (
ZONE_ENTITY, FORWARD_ZONE_ENTITY, CONFIG_ENTITY, RECORD_ENTITY,
ZONE_DEFAULT_FACET, ZONE_PKEY, ZONE_DATA, FORWARD_ZONE_PKEY,
FORWARD_ZONE_DATA, RECORD_PKEY, A_IP, RECORD_ADD_DATA, RECORD_MOD_DATA,
CONFIG_MOD_DATA
)
import pytest
@pytest.mark.tier1
class test_dns(UI_driver):
@pytest.fixture(autouse=True)
def dns_setup(self, ui_driver_fsetup):
if not self.has_dns():
self.skip('DNS not configured')
@screenshot
def test_zone_record_crud(self):
"""
Basic CRUD: dns
"""
self.init_app()
# add and mod zone
self.basic_crud(ZONE_ENTITY, ZONE_DATA,
default_facet=ZONE_DEFAULT_FACET, delete=False)
# add and mod record
self.navigate_to_record(ZONE_PKEY)
self.add_record(ZONE_ENTITY, RECORD_ADD_DATA,
facet=ZONE_DEFAULT_FACET, navigate=False)
self.navigate_to_record(RECORD_PKEY)
self.add_table_record('arecord', RECORD_MOD_DATA)
# del record, del zone
self.navigate_by_breadcrumb(ZONE_PKEY)
self.delete_record(RECORD_PKEY)
self.navigate_by_breadcrumb("DNS Zones")
self.delete_record(ZONE_PKEY)
@screenshot
def test_forward_zone(self):
"""
Forward DNS zones
"""
self.init_app()
# add and mod zone
self.basic_crud(FORWARD_ZONE_ENTITY, FORWARD_ZONE_DATA, delete=False)
# enable/disable
self.navigate_to_record(FORWARD_ZONE_PKEY)
self.disable_action()
self.enable_action()
self.action_list_action('add_permission')
self.action_list_action('remove_permission')
# del zone
self.navigate_by_breadcrumb("DNS Forward Zones")
self.delete_record(FORWARD_ZONE_PKEY)
@screenshot
def test_last_entry_deletion(self):
"""
Test last entry deletion
"""
self.init_app()
self.add_record(ZONE_ENTITY, ZONE_DATA)
self.navigate_to_record(ZONE_PKEY)
self.add_record(ZONE_ENTITY, RECORD_ADD_DATA,
facet=ZONE_DEFAULT_FACET)
self.navigate_to_record(RECORD_PKEY)
self.delete_record(A_IP, parent=self.get_facet(), table_name='arecord')
self.assert_dialog('message_dialog')
self.dialog_button_click('ok')
self.wait_for_request(n=2)
self.assert_facet(ZONE_ENTITY, ZONE_DEFAULT_FACET)
self.navigate_by_breadcrumb("DNS Zones")
self.delete_record(ZONE_PKEY)
@screenshot
def test_config_crud(self):
"""
Basic CRUD: dnsconfig
"""
self.init_app()
self.navigate_by_menu('network_services/dns/dnsconfig')
self.mod_record(CONFIG_ENTITY, CONFIG_MOD_DATA)
def test_ptr_from_host_creation(self):
"""
Test scenario for RHBZ 2009114 - a PTR record is created correctly
with trailing dot when navigated to DNS Records page from host details
page.
"""
self.init_app()
zone = "ptrzone.test."
reverse_zone = "12.168.192.in-addr.arpa."
hostname = "server"
fqdn = "server.ptrzone.test"
dns_fqdn = fqdn + "."
ip = "192.168.12.20"
zone_add_data = {
"add": [
("textbox", "idnsname", zone),
],
}
reverse_zone_add_data = {
"add": [
("radio", "dnszone_name_type", "name_from_ip"),
("textbox", "name_from_ip", ip + "/24"),
],
}
record_add_data = {
"add": [
("textbox", "idnsname", "server"),
("textbox", "a_part_ip_address", ip),
]
}
host_add_data = {
"add": [
("textbox", "hostname", hostname),
("combobox", "dnszone", zone),
],
}
# Create needed DNS zones and record
self.add_record(ZONE_ENTITY, zone_add_data, navigate=True)
self.add_record(ZONE_ENTITY, reverse_zone_add_data, navigate=False)
self.navigate_to_record(zone)
self.add_record(ZONE_ENTITY, record_add_data,
facet=ZONE_DEFAULT_FACET)
# Create host record
self.navigate_by_menu("identity/host")
self.add_record("host", host_add_data, navigate=False)
self.navigate_to_record(fqdn)
self.click_on_link(fqdn)
self.wait_for_request(n=2, d=0.5)
self.assert_facet(RECORD_ENTITY, "details")
self.click_on_link(ip)
self.wait_for_request(n=2, d=0.5)
self.assert_dialog()
self.click_on_link("Create dns record")
self.wait_for_request(n=3, d=0.5)
self.assert_facet(RECORD_ENTITY, "details")
self.assert_record(dns_fqdn, table_name="ptrrecord")
# Cleanup
self.navigate_to_entity(ZONE_ENTITY)
self.delete_record([zone, reverse_zone])
self.navigate_to_entity("host")
self.delete_record([fqdn])
| 5,989
|
Python
|
.py
| 160
| 29.1
| 79
| 0.616219
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,426
|
crypto_utils.py
|
freeipa_freeipa/ipatests/test_webui/crypto_utils.py
|
#
# Copyright (C) 2018 FreeIPA Contributors see COPYING for license
#
from datetime import datetime, timedelta, timezone
UTC = timezone.utc
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization, hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
def generate_csr(cn, is_hostname=True):
"""
Generate certificate signing request
:param cn: common name (str|unicode)
:param is_hostname: is the common name a hostname (default: True)
"""
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
if isinstance(cn, bytes):
cn = cn.decode()
csr = x509.CertificateSigningRequestBuilder()
csr = csr.subject_name(
x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn)])
)
if is_hostname:
csr = csr.add_extension(
x509.SubjectAlternativeName([x509.DNSName(cn)]),
critical=False
)
csr = csr.sign(key, hashes.SHA256(), default_backend())
return csr.public_bytes(serialization.Encoding.PEM).decode()
def generate_certificate(hostname):
"""
Generate self-signed certificate for some DNS name.
The certificate is valid for 100 days from moment of generation.
:param hostname: DNS name (str|unicode)
"""
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
if isinstance(hostname, bytes):
hostname = hostname.decode()
subject = issuer = x509.Name(
[x509.NameAttribute(NameOID.COMMON_NAME, hostname)]
)
cert = x509.CertificateBuilder()
cert = cert.subject_name(subject).issuer_name(issuer).public_key(
key.public_key()
).serial_number(
x509.random_serial_number()
).not_valid_before(
datetime.now(tz=UTC)
).not_valid_after(
datetime.now(tz=UTC) + timedelta(days=100)
).add_extension(
x509.SubjectAlternativeName([x509.DNSName(hostname)]),
critical=False
).sign(key, hashes.SHA256(), default_backend())
return cert.public_bytes(serialization.Encoding.PEM).decode()
| 2,285
|
Python
|
.py
| 64
| 29.9375
| 69
| 0.695298
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,427
|
test_group.py
|
freeipa_freeipa/ipatests/test_webui/test_group.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/>.
"""
Group 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_user as user
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 pytest
try:
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
except ImportError:
pass
@pytest.mark.tier1
class test_group(UI_driver):
@screenshot
def test_crud(self):
"""
Basic CRUD: group
"""
self.init_app()
self.basic_crud(group.ENTITY, group.DATA,
default_facet=group.DEFAULT_FACET)
@screenshot
def test_group_types(self):
"""
Test group types in adder dialog
"""
self.init_app()
pkey = 'itest-group'
data = {
'pkey': pkey,
'add': [
('callback', self.check_posix_enabled, True),
('textbox', 'cn', pkey),
('textarea', 'description', 'test-group desc'),
('radio', 'type', 'nonposix'),
('callback', self.check_posix_enabled, False),
('radio', 'type', 'posix'),
('callback', self.check_posix_enabled, True),
('radio', 'type', 'external'),
('callback', self.check_posix_enabled, False),
('radio', 'type', 'posix'),
('callback', self.check_posix_enabled, True),
],
}
self.add_record(group.ENTITY, data)
self.delete(group.ENTITY, [data], navigate=False)
def check_posix_enabled(self, enabled):
self.assert_disabled("[name=gidnumber]", negative=enabled)
@screenshot
def test_add_group_negative(self):
"""
Negative test for adding groups
"""
self.init_app()
self.empty_group_name()
self.invalid_group_name()
self.duplicate_group_name()
self.tailing_spaces_in_group_description()
self.leading_spaces_in_group_description()
def empty_group_name(self):
self.navigate_to_entity(group.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')
def invalid_group_name(self):
expected_error = 'may only include letters, numbers, _, -, . and $'
pkey = ';test-gr@up'
self.navigate_to_entity(group.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 duplicate_group_name(self):
pkey = 'editors'
expected_error = 'group with name "editors" already exists'
self.navigate_to_entity(group.ENTITY)
self.facet_button_click('add')
self.fill_input('cn', pkey)
self.cancel_retry_dialog(expected_error)
def tailing_spaces_in_group_description(self):
pkey = 'itest_group0'
desc = 'with_trailing_space '
expected_error = 'invalid \'desc\': Leading and trailing ' \
'spaces are not allowed'
self.navigate_to_entity(group.ENTITY)
self.facet_button_click('add')
self.fill_input('cn', pkey)
self.fill_textarea('description', desc)
self.cancel_retry_dialog(expected_error)
def leading_spaces_in_group_description(self):
pkey = 'itest_group0'
desc = ' with_leading_space'
expected_error = 'invalid \'desc\': Leading and trailing' \
' spaces are not allowed'
self.navigate_to_entity(group.ENTITY)
self.facet_button_click('add')
self.fill_input('cn', pkey)
self.fill_textarea('description', desc)
self.cancel_retry_dialog(expected_error)
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_add_multiple_group(self):
"""
Use 'add and add another' button to create multiple groups at one shot
"""
self.init_app()
# adding a POSIX and a Non-POSIX group
self.add_record(group.ENTITY, [group.DATA, group.DATA2])
# adding Two Non-POSIX groups
self.add_record(group.ENTITY, [group.DATA9, group.DATA10])
# adding Two POSIX groups
self.add_record(group.ENTITY, [group.DATA5, group.DATA6])
# delete multiple records
records = [group.DATA, group.DATA2, group.DATA5, group.DATA6,
group.DATA9, group.DATA10]
self.select_multiple_records(records)
self.facet_button_click('remove')
self.dialog_button_click('ok')
@screenshot
def test_add_and_edit_group(self):
"""
1. add and switch to edit mode
2. add and cancel
"""
self.init_app()
# add and edit record
self.add_record(group.ENTITY, group.DATA, dialog_btn='add_and_edit')
self.switch_to_facet('details')
self.delete_action()
# add then cancel
self.add_record(group.ENTITY, group.DATA, dialog_btn='cancel')
@screenshot
def test_actions(self):
"""
Test group actions
"""
self.init_app()
self.add_record(group.ENTITY, group.DATA)
self.navigate_to_record(group.PKEY)
self.switch_to_facet('details')
self.make_posix_action()
self.delete_action()
self.add_record(group.ENTITY, group.DATA, navigate=False)
self.navigate_to_record(group.PKEY)
self.switch_to_facet('details')
self.facet_button_click('refresh') # workaround for BUG: #3702
self.make_external_action()
self.delete_action()
def make_external_action(self):
self.action_list_action('make_external')
self.wait_for_request(n=2)
self.assert_no_error_dialog()
self.assert_text_field('external', 'External', element='span')
def make_posix_action(self):
self.action_list_action('make_posix')
self.wait_for_request(n=2)
self.assert_no_error_dialog()
self.assert_text_field('external', 'POSIX', element='span')
def delete_action(self, entity=group.ENTITY, pkey=group.PKEY):
self.action_list_action('delete')
self.wait_for_request(n=4)
self.assert_no_error_dialog()
self.assert_facet(entity, 'search')
self.assert_record(pkey, negative=True)
@screenshot
def test_associations(self):
"""
Test group associations
"""
self.init_app()
# prepare
# -------
self.add_record(group.ENTITY, [group.DATA, group.DATA2, group.DATA3])
self.add_record(user.ENTITY, [user.DATA, user.DATA2])
self.add_record(netgroup.ENTITY, [netgroup.DATA, netgroup.DATA2])
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_record(group.PKEY, entity=group.ENTITY)
# "members" add with multiple select
self.add_associations([group.PKEY2, group.PKEY3], facet='member_group',
delete=True)
self.add_associations([user.PKEY, user.PKEY2], facet='member_user',
delete=True)
# TODO: external
# "member of": add with search
self.add_associations([group.PKEY3, group.PKEY2],
facet='memberof_group', delete=True, search=True)
self.add_associations([netgroup.PKEY, netgroup.PKEY2],
facet='memberof_netgroup',
delete=True, search=True)
self.add_associations([rbac.ROLE_PKEY], facet='memberof_role',
delete=True)
self.add_associations([hbac.RULE_PKEY], facet='memberof_hbacrule',
delete=True)
self.navigate_to_record(group.PKEY, entity=group.ENTITY)
self.add_associations([sudo.RULE_PKEY], facet='memberof_sudorule',
delete=True, search=True)
# cleanup
# -------
self.delete(group.ENTITY, [group.DATA, group.DATA2, group.DATA3])
self.delete(user.ENTITY, [user.DATA, user.DATA2])
self.delete(netgroup.ENTITY, [netgroup.DATA, netgroup.DATA2])
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):
"""
Group indirect associations
"""
self.init_app()
# add
# ---
self.add_record(group.ENTITY, [group.DATA, group.DATA2, group.DATA3,
group.DATA4, group.DATA5])
self.add_record(user.ENTITY, user.DATA)
# prepare indirect member
self.navigate_to_entity(group.ENTITY, 'search')
self.navigate_to_record(group.PKEY2)
self.add_associations([user.PKEY])
self.add_associations([group.PKEY3], 'member_group')
self.navigate_to_entity(group.ENTITY, 'search')
self.navigate_to_record(group.PKEY)
self.add_associations([group.PKEY2], 'member_group')
# prepare indirect memberof
self.navigate_to_entity(group.ENTITY, 'search')
self.navigate_to_record(group.PKEY4)
self.add_associations([group.PKEY], 'member_group')
self.add_associations([group.PKEY5], 'memberof_group')
self.add_record(netgroup.ENTITY, netgroup.DATA)
self.navigate_to_record(netgroup.PKEY)
self.add_table_associations('memberuser_group', [group.PKEY4])
self.add_record(rbac.ROLE_ENTITY, rbac.ROLE_DATA)
self.navigate_to_record(rbac.ROLE_PKEY)
self.add_associations([group.PKEY4], 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.PKEY4])
self.add_record(sudo.RULE_ENTITY, sudo.RULE_DATA)
self.navigate_to_record(sudo.RULE_PKEY)
self.add_table_associations('memberuser_group', [group.PKEY4])
# check indirect associations
# ---------------------------
self.navigate_to_entity(group.ENTITY, 'search')
self.navigate_to_record(group.PKEY)
self.assert_indirect_record(user.PKEY, group.ENTITY, 'member_user')
self.assert_indirect_record(group.PKEY3, group.ENTITY, 'member_group')
self.assert_indirect_record(group.PKEY5, group.ENTITY,
'memberof_group')
self.assert_indirect_record(netgroup.PKEY, group.ENTITY,
'memberof_netgroup')
self.assert_indirect_record(rbac.ROLE_PKEY, group.ENTITY,
'memberof_role')
self.assert_indirect_record(hbac.RULE_PKEY, group.ENTITY,
'memberof_hbacrule')
self.assert_indirect_record(sudo.RULE_PKEY, group.ENTITY,
'memberof_sudorule')
# cleanup
# -------
self.delete(group.ENTITY, [group.DATA, group.DATA2, group.DATA3,
group.DATA4, group.DATA5])
self.delete(user.ENTITY, [user.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_member_manager_user(self):
"""
Test member manager user has permissions to add and remove group
members
"""
self.init_app()
self.add_record(user.ENTITY, [user.DATA_MEMBER_MANAGER, user.DATA])
self.add_record(group.ENTITY, group.DATA2)
self.navigate_to_record(group.PKEY2)
self.add_associations([user.PKEY_MEMBER_MANAGER],
facet='membermanager_user')
# try to add user to group with member manager permissions
self.logout()
self.login(user.PKEY_MEMBER_MANAGER, user.PASSWD_MEMBER_MANAGER)
self.navigate_to_record(group.PKEY2, entity=group.ENTITY)
self.add_associations([user.PKEY], delete=True)
# re-login as admin and clean up data
self.logout()
self.init_app()
self.delete(user.ENTITY, [user.DATA_MEMBER_MANAGER, user.DATA])
self.delete(group.ENTITY, [group.DATA2])
@screenshot
def test_member_manager_group(self):
"""
Test member managers group has permissions to add and remove group
members
"""
self.init_app()
self.add_record(user.ENTITY, [user.DATA_MEMBER_MANAGER, user.DATA])
self.add_record(group.ENTITY, [group.DATA2, group.DATA3])
self.navigate_to_record(group.PKEY2)
self.add_associations([user.PKEY_MEMBER_MANAGER], facet='member_user')
self.navigate_to_record(group.PKEY3, entity=group.ENTITY)
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(group.PKEY3, entity=group.ENTITY)
self.add_associations([user.PKEY], delete=True)
# re-login as admin and clean up data
self.logout()
self.init_app()
self.delete(user.ENTITY, [user.DATA_MEMBER_MANAGER, user.DATA])
self.delete(group.ENTITY, [group.DATA2, group.DATA3])
@screenshot
def test_settings_new_columns(self):
'''
Related: https://pagure.io/freeipa/issue/9390
Test that the new columns 'givenname', 'sn' and 'nsaccountlock'
are visible when creating new user groups and inspecting its
'settings' section.
'''
self.init_app()
# Create new user (disabled)
self.add_record(user.ENTITY, user.DATA)
self.navigate_to_record(user.PKEY)
self.disable_action()
# Create a new user (enabled)
self.add_record(user.ENTITY, user.DATA2)
# Create an empty group
self.add_record(group.ENTITY, [group.DATA2])
# Add created users to the group
self.navigate_to_record(group.PKEY2)
self.add_associations([user.PKEY, user.PKEY2], facet='member_user')
# Check if new columns are in the group 'settings' section
self.find('givenname', by=By.NAME, strict=True)
self.find('sn', by=By.NAME, strict=True)
self.find('nsaccountlock', by=By.NAME, strict=True)
# Assert that 'Status' value correspond with the already-created users
# - Disabled user
assert "Disabled" == self.get_record_value(user.PKEY, 'nsaccountlock')
# - Enabled user
assert "Enabled" == self.get_record_value(user.PKEY2, 'nsaccountlock')
| 16,830
|
Python
|
.py
| 382
| 34.497382
| 79
| 0.625771
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,428
|
test_constants.py
|
freeipa_freeipa/ipatests/test_ipaplatform/test_constants.py
|
#
# Copyright (C) 2020 FreeIPA Contributors see COPYING for license
#
import pytest
from ipaplatform.base.constants import User, Group
def test_user_root():
user = User("root")
assert user == "root"
assert str(user) == "root"
assert type(str(user)) is str
assert repr(user) == '<User "root">'
assert user.uid == 0
assert user.pgid == 0
assert user.entity.pw_uid == 0
assert User(user) is user
assert User(str(user)) is not user
def test_user_invalid():
invalid = User("invalid")
with pytest.raises(ValueError) as e:
assert invalid.uid
assert str(e.value) == "user 'invalid' not found"
def test_group():
group = Group("root")
assert group == "root"
assert str(group) == "root"
assert type(str(group)) is str
assert repr(group) == '<Group "root">'
assert group.gid == 0
assert group.entity.gr_gid == 0
assert Group(group) is group
assert Group(str(group)) is not group
def test_group_invalid():
invalid = Group("invalid")
with pytest.raises(ValueError) as e:
assert invalid.gid
assert str(e.value) == "group 'invalid' not found"
@pytest.mark.skip_if_platform("debian", reason="test is Fedora specific")
@pytest.mark.skip_if_platform("suse", reason="test is Fedora specific")
def test_user_group_daemon():
# daemon user / group are always defined
user = User("daemon")
assert user == "daemon"
assert user.uid == 2
assert user.pgid == 2
group = Group("daemon")
assert group == "daemon"
assert group.gid == 2
assert Group(user) is not user
| 1,603
|
Python
|
.py
| 48
| 28.916667
| 73
| 0.668831
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,429
|
test_platforms.py
|
freeipa_freeipa/ipatests/test_ipaplatform/test_platforms.py
|
#
# Copyright (C) 2020 FreeIPA Contributors see COPYING for license
#
"""Test import and basic properties of platforms
"""
from importlib import import_module
import pytest
from ipaplatform.base.constants import BaseConstantsNamespace, User, Group
from ipaplatform.base.paths import BasePathNamespace
from ipaplatform.base.services import KnownServices
from ipaplatform.base.tasks import BaseTaskNamespace
PLATFORMS = [
"debian",
"fedora",
"fedora_container",
"rhel",
"rhel_container",
"suse",
]
@pytest.mark.parametrize("name", PLATFORMS)
def test_import_platform(name):
constants = import_module(f"ipaplatform.{name}.constants")
assert isinstance(constants.constants, BaseConstantsNamespace)
assert issubclass(constants.User, User)
assert issubclass(constants.Group, Group)
paths = import_module(f"ipaplatform.{name}.paths")
assert isinstance(paths.paths, BasePathNamespace)
services = import_module(f"ipaplatform.{name}.services")
assert isinstance(services.knownservices, KnownServices)
assert isinstance(services.timedate_services, list)
assert callable(services.service)
tasks = import_module(f"ipaplatform.{name}.tasks")
assert isinstance(tasks.tasks, BaseTaskNamespace)
| 1,259
|
Python
|
.py
| 33
| 34.727273
| 74
| 0.784072
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,430
|
test_tasks.py
|
freeipa_freeipa/ipatests/test_ipaplatform/test_tasks.py
|
#
# Copyright (C) 2017 FreeIPA Contributors see COPYING for license
#
from __future__ import absolute_import
import os
import pytest
from ipaplatform.tasks import tasks
@pytest.mark.skip_if_platform(
"debian", reason="Test is specific to platforms using RPM"
)
def test_ipa_version():
v3 = tasks.parse_ipa_version('3.0')
assert v3.version == u'3.0'
if hasattr(v3, '_rpmvercmp'):
assert v3._rpmvercmp_func is None
v3._rpmvercmp(b'1', b'2')
assert v3._rpmvercmp_func is not None
v4 = tasks.parse_ipa_version('4.0')
assert v4.version == u'4.0'
if hasattr(v4, '_rpmvercmp'):
assert v4._rpmvercmp_func is not None
# pylint: disable=comparison-with-itself
assert v3 < v4
assert v3 <= v4
assert v3 <= v3
assert v3 != v4
assert v3 == v3
assert not v3 == v4
assert v4 > v3
assert v4 >= v3
def test_detect_container():
container = None
# naive detection, may fail for OpenVZ and other container runtimes
if os.path.isfile('/run/systemd/container'):
with open('/run/systemd/container') as f:
container = f.read().strip()
elif os.geteuid() == 0:
with open('/proc/1/environ') as f:
environ = f.read()
for item in environ.split('\x00'):
if not item:
continue
k, v = item.split('=', 1)
if k == 'container':
container = v
elif os.path.isfile("/run/.containerenv"):
container = "podman"
elif os.path.isfile("/.dockerenv"):
container = "docker"
detected = tasks.detect_container()
assert detected == container
| 1,662
|
Python
|
.py
| 51
| 26.313725
| 71
| 0.621099
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,431
|
test_importhook.py
|
freeipa_freeipa/ipatests/test_ipaplatform/test_importhook.py
|
#
# Copyright (C) 2017 FreeIPA Contributors see COPYING for license
#
from __future__ import absolute_import
import os
import sys
import pytest
import ipaplatform.constants
import ipaplatform.paths
import ipaplatform.services
import ipaplatform.tasks
from ipaplatform._importhook import metaimporter
from ipaplatform.osinfo import osinfo, _parse_osrelease
try:
from ipaplatform.override import OVERRIDE
except ImportError:
OVERRIDE = None
HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, 'data')
@pytest.mark.skipif(OVERRIDE is None,
reason='test requires override')
def test_override():
assert OVERRIDE == osinfo.platform_ids[0]
assert OVERRIDE == osinfo.platform
@pytest.mark.parametrize('mod, name', [
(ipaplatform.constants, 'ipaplatform.constants'),
(ipaplatform.paths, 'ipaplatform.paths'),
(ipaplatform.services, 'ipaplatform.services'),
(ipaplatform.tasks, 'ipaplatform.tasks'),
])
def test_importhook(mod, name):
assert name in metaimporter.modules
prefix, suffix = name.split('.')
assert prefix == 'ipaplatform'
override = '.'.join((prefix, metaimporter.platform, suffix))
assert mod.__name__ == override
# dicts are equal, modules may not be identical
assert mod.__dict__ == sys.modules[override].__dict__
@pytest.mark.parametrize('filename, id_, id_like', [
(os.path.join(DATA, 'os-release-centos'), 'centos', ('rhel', 'fedora')),
(os.path.join(DATA, 'os-release-fedora'), 'fedora', ()),
(os.path.join(DATA, 'os-release-ubuntu'), 'ubuntu', ('debian',)),
])
def test_parse_os_release(filename, id_, id_like):
parsed = _parse_osrelease(filename)
assert parsed['ID'] == id_
assert parsed['ID_LIKE'] == id_like
| 1,762
|
Python
|
.py
| 47
| 34.042553
| 76
| 0.717136
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,432
|
test_passwd_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_passwd_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
#
# Copyright (C) 2009 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/plugins/passwd.py` module.
"""
import pytest
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, assert_attr_equal
from ipalib import api
from ipalib import errors
@pytest.mark.tier1
class test_passwd(XMLRPC_test):
"""
Test the `passwd` plugin.
"""
uid = u'pwexample'
givenname = u'Jim'
sn = u'Example'
home = u'/home/%s' % uid
principalname = u'%s@%s' % (uid, api.env.realm)
kw = {'givenname': givenname, 'sn': sn, 'uid': uid, 'homedirectory': home}
def test_1_user_add(self):
"""
Create a test user
"""
entry = api.Command['user_add'](**self.kw)['result']
assert_attr_equal(entry, 'givenname', self.givenname)
assert_attr_equal(entry, 'sn', self.sn)
assert_attr_equal(entry, 'uid', self.uid)
assert_attr_equal(entry, 'homedirectory', self.home)
assert_attr_equal(entry, 'objectclass', 'ipaobject')
def test_2_set_passwd(self):
"""
Test the `xmlrpc.passwd` method.
"""
out = api.Command['passwd'](self.uid, password=u'password1')
assert out['result'] is True
def test_3_user_del(self):
"""
Remove the test user
"""
api.Command['user_del'](self.uid)
# Verify that it is gone
with pytest.raises(errors.NotFound):
api.Command['user_show'](self.uid)
| 2,178
|
Python
|
.py
| 60
| 31.516667
| 78
| 0.670772
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,433
|
test_range_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_range_plugin.py
|
# Authors:
# Alexander Bokovoy <abokovoy@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 `ipaserver/plugins/idrange.py` module, and XML-RPC in general.
"""
import six
from ipalib import api, errors, messages
from ipalib import constants
from ipaplatform import services
from ipatests.test_xmlrpc.xmlrpc_test import (
Declarative, fuzzy_uuid, Fuzzy, fuzzy_sequence_of)
from ipatests.test_xmlrpc import objectclasses
from ipatests.util import MockLDAP
from ipapython.dn import DN
from ipatests.test_xmlrpc.test_user_plugin import get_user_result
from ipatests.test_xmlrpc.mock_trust import (
get_range_dn, get_trusted_dom_dict, get_trusted_dom_range_dict,
get_trust_dn)
import pytest
if six.PY3:
unicode = str
# Determine the test shift used
id_shift = 0
rid_shift = 0
for idrange in api.Command['idrange_find']()['result']:
size = int(idrange['ipaidrangesize'][0])
base_id = int(idrange['ipabaseid'][0])
rtype = idrange['iparangetype'][0]
if rtype == 'ipa-local-subid' or base_id == constants.SUBID_RANGE_START:
# ignore subordinate id range. It would push values beyond uint32_t.
# There is plenty of space below SUBUID_RANGE_START.
continue
id_end = base_id + size
rid_end = 0
if 'ipabaserid' in idrange:
base_rid = int(idrange['ipabaserid'][0])
rid_end = base_rid + size
if 'ipasecondarybaserid' in idrange:
secondary_base_rid = int(idrange['ipasecondarybaserid'][0])
rid_end = max(base_rid, secondary_base_rid) + size
if id_shift < id_end:
id_shift = id_end + 1000000
if rid_shift < rid_end:
rid_shift = rid_end + 1000000
# Local ranges definitions
testrange1 = u'testrange1'
testrange1_base_id = id_shift + 900000
testrange1_size = 99999
testrange1_base_rid = rid_shift + 10000
testrange1_secondary_base_rid = rid_shift + 200000
testrange2 = u'testrange2'
testrange2_base_id = id_shift + 100
testrange2_size = 50
testrange2_base_rid = rid_shift + 100
testrange2_secondary_base_rid = rid_shift + 1000
testrange3 = u'testrange3'
testrange3_base_id = id_shift + 200
testrange3_size = 50
testrange3_base_rid = rid_shift + 70
testrange3_secondary_base_rid = rid_shift + 1100
testrange4 = u'testrange4'
testrange4_base_id = id_shift + 300
testrange4_size = 50
testrange4_base_rid = rid_shift + 200
testrange4_secondary_base_rid = rid_shift + 1030
testrange5 = u'testrange5'
testrange5_base_id = id_shift + 400
testrange5_size = 50
testrange5_base_rid = rid_shift + 1020
testrange5_secondary_base_rid = rid_shift + 1200
testrange6 = u'testrange6'
testrange6_base_id = id_shift + 130
testrange6_size = 50
testrange6_base_rid = rid_shift + 500
testrange6_secondary_base_rid = rid_shift + 1300
testrange7 = u'testrange7'
testrange7_base_id = id_shift + 600
testrange7_size = 50
testrange7_base_rid = rid_shift + 600
testrange7_secondary_base_rid = rid_shift + 649
testrange8 = u'testrange8'
testrange8_base_id = id_shift + 700
testrange8_size = 50
testrange8_base_rid = rid_shift + 700
testrange8_secondary_base_rid = rid_shift + 800
testrange9 = u'testrange9'
testrange9_base_id = id_shift + 800
testrange9_size = 50
testrange9_base_rid = rid_shift + 800
testrange9_secondary_base_rid = rid_shift + 1800
# Domain ranges definitions
# Domain1 - AD domain nonactive (not present in LDAP)
domain1_sid = u'S-1-5-21-259319770-2312917334-591429603'
domain1range1 = u'domain1range1'
domain1range1_base_id = id_shift + 10000
domain1range1_size = 50
domain1range1_base_rid = rid_shift + 10000
domain1range1_type = u'ipa-ad-trust'
domain1range1_dn = get_range_dn(name=domain1range1)
domain1range1_add = get_trusted_dom_range_dict(
name=domain1range1,
base_id=domain1range1_base_id,
size=domain1range1_size,
rangetype=domain1range1_type,
base_rid=domain1range1_base_rid,
sid=domain1_sid
)
# Domain2 - AD domain active (present in LDAP)
domain2 = u'domain2'
domain2_dn = get_trust_dn(domain2)
domain2_sid = u'S-1-5-21-2997650941-1802118864-3094776726'
domain2_add = get_trusted_dom_dict(domain2, domain2_sid)
domain2range1 = u'domain2range1'
domain2range1_base_id = id_shift + 10100
domain2range1_size = 50
domain2range1_base_rid = rid_shift + 10100
domain2range1_type = u'ipa-ad-trust'
domain2range1_dn = get_range_dn(name=domain2range1)
domain2range1_add = get_trusted_dom_range_dict(
name=domain2range1,
base_id=domain2range1_base_id,
size=domain2range1_size,
rangetype=domain2range1_type,
base_rid=domain2range1_base_rid,
sid=domain2_sid
)
domain2range2 = u'domain2range2'
domain2range2_base_id = id_shift + 10200
domain2range2_size = 50
domain2range2_base_rid = rid_shift + 10200
domain2range2_type = u'ipa-ad-trust'
domain2range2_dn = get_range_dn(name=domain2range2)
domain2range2_add = get_trusted_dom_range_dict(
name=domain2range2,
base_id=domain2range2_base_id,
size=domain2range2_size,
rangetype=domain2range2_type,
base_rid=domain2range2_base_rid,
sid=domain2_sid
)
# Domain3 - Posix active AD domain, two posix ranges
domain3 = u'domain3'
domain3_dn = get_trust_dn(domain3)
domain3_sid = u'S-1-5-21-1980929950-1830687243-1002863068'
domain3_add = get_trusted_dom_dict(domain3, domain3_sid)
domain3range1 = u'domain3range1'
domain3range1_base_id = id_shift + 10300
domain3range1_size = 50
domain3range1_base_rid = 0
domain3range1_type = u'ipa-ad-trust-posix'
domain3range1_dn = get_range_dn(name=domain3range1)
domain3range1_add = get_trusted_dom_range_dict(
name=domain3range1,
base_id=domain3range1_base_id,
size=domain3range1_size,
rangetype=domain3range1_type,
base_rid=domain3range1_base_rid,
sid=domain3_sid
)
domain3range2 = u'domain3range2'
domain3range2_base_id = id_shift + 10400
domain3range2_size = 50
domain3range2_base_rid = 0
domain3range2_type = u'ipa-ad-trust-posix'
domain3range2_dn = get_range_dn(name=domain3range2)
domain3range2_add = get_trusted_dom_range_dict(
name=domain3range2,
base_id=domain3range2_base_id,
size=domain3range2_size,
rangetype=domain3range2_type,
base_rid=domain3range2_base_rid,
sid=domain3_sid
)
# Domain4 - Posix active AD domain, one posix range
domain4 = u'domain4'
domain4_dn = get_trust_dn(domain4)
domain4_sid = u'S-1-5-21-2630044516-2228086573-3500008130'
domain4_add = get_trusted_dom_dict(domain4, domain4_sid)
domain4range1 = u'domain4range1'
domain4range1_base_id = id_shift + 10500
domain4range1_size = 50
domain4range1_base_rid = 0
domain4range1_type = u'ipa-ad-trust-posix'
domain4range1_dn = get_range_dn(name=domain4range1)
domain4range1_add = get_trusted_dom_range_dict(
name=domain4range1,
base_id=domain4range1_base_id,
size=domain4range1_size,
rangetype=domain4range1_type,
base_rid=domain4range1_base_rid,
sid=domain4_sid
)
# Domain5 - NonPosix active AD domain, two nonposix ranges
domain5 = u'domain5'
domain5_dn = get_trust_dn(domain5)
domain5_sid = u'S-1-5-21-2936727573-1940715531-2353349748'
domain5_add = get_trusted_dom_dict(domain5, domain5_sid)
domain5range1 = u'domain5range1'
domain5range1_base_id = id_shift + 10600
domain5range1_size = 50
domain5range1_base_rid = rid_shift + 10600
domain5range1_type = u'ipa-ad-trust'
domain5range1_dn = get_range_dn(name=domain5range1)
domain5range1_add = get_trusted_dom_range_dict(
name=domain5range1,
base_id=domain5range1_base_id,
size=domain5range1_size,
rangetype=domain5range1_type,
base_rid=domain5range1_base_rid,
sid=domain5_sid
)
domain5range2 = u'domain5range2'
domain5range2_base_id = id_shift + 10700
domain5range2_size = 50
domain5range2_base_rid = rid_shift + 10700
domain5range2_type = u'ipa-ad-trust'
domain5range2_dn = get_range_dn(name=domain5range2)
domain5range2_add = get_trusted_dom_range_dict(
name=domain5range2,
base_id=domain5range2_base_id,
size=domain5range2_size,
rangetype=domain5range2_type,
base_rid=domain5range2_base_rid,
sid=domain5_sid
)
# Domain6 - NonPosix active AD domain, one nonposix ranges
domain6 = u'domain6'
domain6_dn = get_trust_dn(domain6)
domain6_sid = u'S-1-5-21-2824814446-180299986-1494994477'
domain6_add = get_trusted_dom_dict(domain6, domain6_sid)
domain6range1 = u'domain6range1'
domain6range1_base_id = id_shift + 10800
domain6range1_size = 50
domain6range1_base_rid = rid_shift + 10800
domain6range1_type = u'ipa-ad-trust'
domain6range1_dn = get_range_dn(name=domain6range1)
domain6range1_add = get_trusted_dom_range_dict(
name=domain6range1,
base_id=domain6range1_base_id,
size=domain6range1_size,
rangetype=domain6range1_type,
base_rid=domain6range1_base_rid,
sid=domain6_sid
)
# Domain7 - Posix active AD domain, invalid(defined) RID
domain7 = u'domain7'
domain7_dn = get_trust_dn(domain7)
domain7_sid = u'S-1-5-21-2714542333-175454564-1645457223'
domain7_add = get_trusted_dom_dict(domain7, domain7_sid)
domain7range1 = u'domain7range1'
domain7range1_base_id = id_shift + 10900
domain7range1_size = 50
domain7range1_base_rid = rid_shift + 10900
domain7range1_type = u'ipa-ad-trust-posix'
domain7range1_dn = get_range_dn(name=domain7range1)
# Container for all trusted objects
trust_container_dn = "cn=ad,cn=trusts,{basedn}".format(basedn=api.env.basedn)
trust_container_add = dict(
objectClass=[b"nsContainer", b"top"]
)
# Convince Domain Validator that adtrust-install was run in order to test
# adding of ipa-trust-posix range
smb_cont_dn = "{cifsdomains},{basedn}".format(
cifsdomains=api.env.container_cifsdomains,
basedn=api.env.basedn)
smb_cont_add = dict(
objectClass=[b"nsContainer", b"top"]
)
trust_local_dn = "cn={domain},{smbcont}".format(
domain=api.env.domain,
smbcont=smb_cont_dn)
trust_local_add = dict(
objectClass=[b"ipaNTDomainAttrs", b"nsContainer", b"top"],
ipaNTFlatName=[b"UNITTESTS"],
ipaNTDomainGUID=[b"4ed70def-bff4-464c-889f-6cd2cfa4dbb7"],
ipaNTSecurityIdentifier=[b"S-1-5-21-2568409255-1212639194-836868319"]
)
user1 = u'tuser1'
user1_uid = id_shift + 900000
group1 = u'group1'
group1_gid = id_shift + 900100
IPA_LOCAL_RANGE_MOD_ERR = (
u"This command can not be used to change ID allocation for local IPA "
"domain. Run `ipa help idrange` for more information"
)
dirsrv_instance = services.knownservices.dirsrv.service_instance("")
fuzzy_restart_messages = fuzzy_sequence_of(Fuzzy(type=dict))
@pytest.mark.tier1
class test_range(Declarative):
mockldap = None
@pytest.fixture(autouse=True, scope="class")
def range_setup(self, request, declarative_setup):
cls = request.cls
def fin():
cls.mockldap = MockLDAP()
cls.mockldap.del_entry(domain2_dn)
cls.mockldap.del_entry(domain3_dn)
cls.mockldap.del_entry(domain4_dn)
cls.mockldap.del_entry(domain5_dn)
cls.mockldap.del_entry(domain6_dn)
cls.mockldap.del_entry(domain7_dn)
cls.mockldap.del_entry(domain1range1_dn)
cls.mockldap.del_entry(domain2range1_dn)
cls.mockldap.del_entry(domain2range2_dn)
cls.mockldap.del_entry(domain3range1_dn)
cls.mockldap.del_entry(domain3range2_dn)
cls.mockldap.del_entry(domain4range1_dn)
cls.mockldap.del_entry(domain5range1_dn)
cls.mockldap.del_entry(domain5range2_dn)
cls.mockldap.del_entry(domain6range1_dn)
cls.mockldap.del_entry(domain7range1_dn)
cls.mockldap.del_entry(trust_container_dn)
cls.mockldap.del_entry(trust_local_dn)
cls.mockldap.del_entry(smb_cont_dn)
cls.mockldap.unbind()
fin()
cls.mockldap = MockLDAP()
cls.mockldap.add_entry(trust_container_dn, trust_container_add)
cls.mockldap.add_entry(smb_cont_dn, smb_cont_add)
cls.mockldap.add_entry(trust_local_dn, trust_local_add)
cls.mockldap.add_entry(domain2_dn, domain2_add)
cls.mockldap.add_entry(domain3_dn, domain3_add)
cls.mockldap.add_entry(domain4_dn, domain4_add)
cls.mockldap.add_entry(domain5_dn, domain5_add)
cls.mockldap.add_entry(domain6_dn, domain6_add)
cls.mockldap.add_entry(domain7_dn, domain7_add)
cls.mockldap.add_entry(domain1range1_dn, domain1range1_add)
cls.mockldap.add_entry(domain2range1_dn, domain2range1_add)
cls.mockldap.add_entry(domain2range2_dn, domain2range2_add)
cls.mockldap.add_entry(domain3range1_dn, domain3range1_add)
cls.mockldap.add_entry(domain3range2_dn, domain3range2_add)
cls.mockldap.add_entry(domain4range1_dn, domain4range1_add)
cls.mockldap.add_entry(domain5range1_dn, domain5range1_add)
cls.mockldap.add_entry(domain5range2_dn, domain5range2_add)
cls.mockldap.add_entry(domain6range1_dn, domain6range1_add)
cls.mockldap.unbind()
request.addfinalizer(fin)
cleanup_commands = [
('idrange_del', [testrange1, testrange2, testrange3, testrange4,
testrange5, testrange6, testrange7, testrange8,
testrange9],
{'continue': True}),
('user_del', [user1], {}),
('group_del', [group1], {}),
]
# Basic tests.
tests = [
dict(
desc='Create ID range %r' % (testrange1),
command=('idrange_add', [testrange1],
dict(ipabaseid=testrange1_base_id, ipaidrangesize=testrange1_size,
ipabaserid=testrange1_base_rid, ipasecondarybaserid=testrange1_secondary_base_rid)),
expected=dict(
result=dict(
dn=DN(('cn',testrange1),('cn','ranges'),('cn','etc'),
api.env.basedn),
cn=[testrange1],
objectclass=[u'ipaIDrange', u'ipadomainidrange'],
ipabaseid=[unicode(testrange1_base_id)],
ipabaserid=[unicode(testrange1_base_rid)],
ipasecondarybaserid=[unicode(testrange1_secondary_base_rid)],
ipaidrangesize=[unicode(testrange1_size)],
iparangetyperaw=[u'ipa-local'],
iparangetype=[u'local domain range'],
),
value=testrange1,
summary=u'Added ID range "%s"' % (testrange1),
messages=(
messages.ServiceRestartRequired(
service=dirsrv_instance,
server='<all IPA servers>').to_dict(),
),
),
),
dict(
desc='Retrieve ID range %r' % (testrange1),
command=('idrange_show', [testrange1], dict()),
expected=dict(
result=dict(
dn=DN(('cn',testrange1),('cn','ranges'),('cn','etc'),
api.env.basedn),
cn=[testrange1],
ipabaseid=[unicode(testrange1_base_id)],
ipabaserid=[unicode(testrange1_base_rid)],
ipasecondarybaserid=[unicode(testrange1_secondary_base_rid)],
ipaidrangesize=[unicode(testrange1_size)],
iparangetyperaw=[u'ipa-local'],
iparangetype=[u'local domain range'],
),
value=testrange1,
summary=None,
),
),
# Checks for modifications leaving objects outside of the range.
dict(
desc='Create user %r in ID range %r' % (user1, testrange1),
command=(
'user_add', [user1], dict(givenname=u'Test', sn=u'User1',
uidnumber=user1_uid)
),
expected=dict(
value=user1,
summary=u'Added user "%s"' % user1,
result=get_user_result(
user1, u'Test', u'User1', 'add',
uidnumber=[unicode(user1_uid)],
gidnumber=[unicode(user1_uid)],
objectclass=objectclasses.user_base + [u'mepOriginEntry'],
),
),
),
dict(
desc='Create group %r in ID range %r' % (group1, testrange1),
command=(
'group_add', [group1], dict(description=u'Test desc 1',
gidnumber=group1_gid)
),
expected=dict(
value=group1,
summary=u'Added group "%s"' % group1,
result=dict(
cn=[group1],
description=[u'Test desc 1'],
gidnumber=[unicode(group1_gid)],
objectclass=objectclasses.group + [u'posixgroup'],
ipauniqueid=[fuzzy_uuid],
dn=DN(('cn',group1),('cn','groups'),('cn','accounts'), api.env.basedn),
),
),
),
dict(
desc='Try to modify ID range %r to get out bounds object #1' % (testrange1),
command=(
'idrange_mod', [testrange1], dict(ipabaseid=user1_uid + 1)
),
expected=errors.ExecutionError(message=IPA_LOCAL_RANGE_MOD_ERR),
),
dict(
desc='Try to modify ID range %r to get out bounds object #2' % (testrange1),
command=('idrange_mod', [testrange1], dict(ipaidrangesize=100)),
expected=errors.ExecutionError(message=IPA_LOCAL_RANGE_MOD_ERR),
),
dict(
desc='Try to modify ID range %r to get out bounds object #3' % (testrange1),
command=('idrange_mod', [testrange1], dict(ipabaseid=100, ipaidrangesize=100)),
expected=errors.ExecutionError(message=IPA_LOCAL_RANGE_MOD_ERR),
),
dict(
desc='Modify ID range %r' % (testrange1),
command=('idrange_mod', [testrange1], dict(ipaidrangesize=90000)),
expected=errors.ExecutionError(message=IPA_LOCAL_RANGE_MOD_ERR)
),
dict(
desc='Try to delete ID range %r with active IDs inside it' % testrange1,
command=('idrange_del', [testrange1], {}),
expected=errors.ValidationError(name='ipabaseid,ipaidrangesize',
error=u'range modification leaving objects with ID out of the'
u' defined range is not allowed'),
),
dict(
desc='Delete user %r' % user1,
command=('user_del', [user1], {}),
expected=dict(
result=dict(failed=[]),
value=[user1],
summary=u'Deleted user "%s"' % user1,
),
),
dict(
desc='Delete group %r' % group1,
command=('group_del', [group1], {}),
expected=dict(
result=dict(failed=[]),
value=[group1],
summary=u'Deleted group "%s"' % group1,
),
),
# Framework validation: mod local idrange with auto-private-groups
# is prohibited
dict(
desc=('Try to modify local range %r with --auto-private-groups'
% (testrange1)),
command=('idrange_mod', [testrange1],
dict(ipaautoprivategroups='true')),
expected=errors.ExecutionError(message=IPA_LOCAL_RANGE_MOD_ERR)
),
dict(
desc='Delete ID range %r' % testrange1,
command=('idrange_del', [testrange1], {}),
expected=dict(
result=dict(failed=[]),
messages=fuzzy_restart_messages,
value=[testrange1],
summary=u'Deleted ID range "%s"' % testrange1,
),
),
# Tests for overlapping local ranges.
dict(
desc='Create ID range %r' % (testrange2),
command=('idrange_add', [testrange2],
dict(ipabaseid=testrange2_base_id,
ipaidrangesize=testrange2_size,
ipabaserid=testrange2_base_rid,
ipasecondarybaserid=testrange2_secondary_base_rid)),
expected=dict(
result=dict(
dn=DN(('cn',testrange2),('cn','ranges'),('cn','etc'),
api.env.basedn),
cn=[testrange2],
objectclass=[u'ipaIDrange', u'ipadomainidrange'],
ipabaseid=[unicode(testrange2_base_id)],
ipabaserid=[unicode(testrange2_base_rid)],
ipasecondarybaserid=[unicode(testrange2_secondary_base_rid)],
ipaidrangesize=[unicode(testrange2_size)],
iparangetyperaw=[u'ipa-local'],
iparangetype=[u'local domain range'],
),
value=testrange2,
summary=u'Added ID range "%s"' % (testrange2),
messages=(
messages.ServiceRestartRequired(
service=dirsrv_instance,
server='<all IPA servers>').to_dict(),
),
),
),
dict(
desc='Try to modify ID range %r so that its rid ranges are overlapping themselves' % (testrange2),
command=('idrange_mod', [testrange2],
dict(ipabaserid=(testrange2_secondary_base_rid))),
expected=errors.ExecutionError(message=IPA_LOCAL_RANGE_MOD_ERR),
),
dict(
desc='Try to create ID range %r with overlapping rid range' % (testrange3),
command=('idrange_add', [testrange3],
dict(ipabaseid=testrange3_base_id,
ipaidrangesize=testrange3_size,
ipabaserid=testrange3_base_rid,
ipasecondarybaserid=testrange3_secondary_base_rid)),
expected=errors.DatabaseError(
desc='Constraint violation', info='New primary rid range overlaps with existing primary rid range.'),
),
dict(
desc='Try to create ID range %r with overlapping secondary rid range' % (testrange4),
command=('idrange_add', [testrange4],
dict(ipabaseid=testrange4_base_id,
ipaidrangesize=testrange4_size,
ipabaserid=testrange4_base_rid,
ipasecondarybaserid=testrange4_secondary_base_rid)),
expected=errors.DatabaseError(
desc='Constraint violation', info='New secondary rid range overlaps with existing secondary rid range.'),
),
dict(
desc='Try to create ID range %r with primary range overlapping secondary rid range' % (testrange5),
command=('idrange_add', [testrange5],
dict(ipabaseid=testrange5_base_id,
ipaidrangesize=testrange5_size,
ipabaserid=testrange5_base_rid,
ipasecondarybaserid=testrange5_secondary_base_rid)),
expected=errors.DatabaseError(
desc='Constraint violation', info='New primary rid range overlaps with existing secondary rid range.'),
),
dict(
desc='Try to create ID range %r with overlapping id range' % (testrange6),
command=('idrange_add', [testrange6],
dict(ipabaseid=testrange6_base_id,
ipaidrangesize=testrange6_size,
ipabaserid=testrange6_base_rid,
ipasecondarybaserid=testrange6_secondary_base_rid)),
expected=errors.DatabaseError(
desc='Constraint violation', info='New base range overlaps with existing base range.'),
),
dict(
desc='Try to create ID range %r with rid ranges overlapping themselves' % (testrange7),
command=('idrange_add', [testrange7],
dict(ipabaseid=testrange7_base_id,
ipaidrangesize=testrange7_size,
ipabaserid=testrange7_base_rid,
ipasecondarybaserid=testrange7_secondary_base_rid)),
expected=errors.ValidationError(
name='ID Range setup', error='Primary RID range and secondary RID range cannot overlap'),
),
dict(
desc='Delete ID range %r' % testrange2,
command=('idrange_del', [testrange2], {}),
expected=dict(
result=dict(failed=[]),
messages=fuzzy_restart_messages,
value=[testrange2],
summary=u'Deleted ID range "%s"' % testrange2,
),
),
# Testing framework validation: --dom-sid/--dom-name and secondary RID
# base cannot be used together
dict(
desc='Create ID range %r' % (testrange8),
command=('idrange_add', [testrange8],
dict(ipabaseid=testrange8_base_id,
ipaidrangesize=testrange8_size,
ipabaserid=testrange8_base_rid,
ipasecondarybaserid=testrange8_secondary_base_rid,
ipanttrusteddomainsid=domain1_sid)),
expected=errors.ValidationError(
name='ID Range setup', error='Options dom-sid/dom-name and '
'secondary-rid-base cannot be used together'),
),
# Testing framework validation: --auto-private-groups is prohibited
# with ipa-local range
dict(
desc='Local ID range %r with auto-private-groups' % (testrange8),
command=('idrange_add', [testrange8],
dict(ipabaseid=testrange8_base_id,
ipaidrangesize=testrange8_size,
ipaautoprivategroups='true')),
expected=errors.ValidationError(
name='ID Range setup',
error='IPA Range type must be one of ipa-ad-trust '
'or ipa-ad-trust-posix when '
'auto-private-groups is specified'),
),
# Testing framework validation: --rid-base is prohibited with ipa-ad-posix
dict(
desc='Try to create ipa-ad-trust-posix ID range %r with base RID' % (domain7range1),
command=('idrange_add', [domain7range1],
dict(ipabaseid=domain7range1_base_id,
ipaidrangesize=domain7range1_size,
ipabaserid=domain7range1_base_rid,
iparangetype=domain7range1_type,
ipanttrusteddomainsid=domain7_sid)),
expected=errors.ValidationError(
name='ID Range setup',
error='Option rid-base must not be used when IPA range '
'type is ipa-ad-trust-posix'),
),
# Testing framework validation: --auto-private-groups can only be
# one of true, false, hybrid
dict(
desc=('Create ID range %r with bogus --auto-private-groups'
% (domain7range1)),
command=('idrange_add', [domain7range1],
dict(ipabaseid=domain7range1_base_id,
ipaidrangesize=domain7range1_size,
iparangetype=domain7range1_type,
ipanttrusteddomainsid=domain7_sid,
ipaautoprivategroups='bogus')),
expected=errors.ValidationError(
name='auto_private_groups',
error="must be one of 'true', 'false', 'hybrid'"),
),
dict(
desc='Create ID range %r' % (domain7range1),
command=('idrange_add', [domain7range1],
dict(ipabaseid=domain7range1_base_id,
ipaidrangesize=domain7range1_size,
iparangetype=domain7range1_type,
ipanttrusteddomainsid=domain7_sid)),
expected=dict(
result=dict(
dn=unicode(domain7range1_dn),
cn=[domain7range1],
objectclass=[u'ipaIDrange', u'ipatrustedaddomainrange'],
ipabaseid=[unicode(domain7range1_base_id)],
ipaidrangesize=[unicode(domain7range1_size)],
ipanttrusteddomainsid=[unicode(domain7_sid)],
iparangetyperaw=[u'ipa-ad-trust-posix'],
iparangetype=[u'Active Directory trust range with POSIX attributes'],
),
value=unicode(domain7range1),
summary=u'Added ID range "%s"' % (domain7range1),
),
),
dict(
desc='Try to modify ipa-ad-trust-posix ID range %r with base RID' % (domain7range1),
command=('idrange_mod', [domain7range1], dict(ipabaserid=domain7range1_base_rid)),
expected=errors.ValidationError(
name='ID Range setup',
error='Option rid-base must not be used when IPA range '
'type is ipa-ad-trust-posix'),
),
# Testing prohibition of deletion of ranges belonging to active
# trusted domains.
dict(
desc='Delete non-active AD trusted range %r' % domain1range1,
command=('idrange_del', [domain1range1], {}),
expected=dict(
result=dict(failed=[]),
value=[domain1range1],
summary=u'Deleted ID range "%s"' % domain1range1,
messages=fuzzy_restart_messages,
),
),
dict(
desc='Try to delete active AD trusted range %r' % domain2range1,
command=('idrange_del', [domain2range1], {}),
expected=errors.DependentEntry(
label='Active Trust domain',
key=domain2range1,
dependent=domain2),
),
# Testing base range overlaps for ranges of different types and
# different domains
# - Base range overlaps
# 1. ipa-ad-trust-posix type ranges from the same forest can overlap
# on base ranges, use domain3range1 and domain3range2
dict(
desc=('Modify ipa-ad-trust-posix range %r to overlap on base range'
' with posix range from the same domain' % (domain3range2)),
command=('idrange_mod', [domain3range2],
dict(ipabaseid=domain3range1_base_id)),
expected=dict(
messages=fuzzy_restart_messages,
result=dict(
cn=[domain3range2],
ipabaseid=[unicode(domain3range1_base_id)],
ipaidrangesize=[unicode(domain3range2_size)],
ipanttrusteddomainsid=[unicode(domain3_sid)],
iparangetyperaw=[u'ipa-ad-trust-posix'],
iparangetype=[u'Active Directory trust range with POSIX '
'attributes'],
),
value=domain3range2,
summary=u'Modified ID range "%s"' % (domain3range2),
),
),
# 2. ipa-ad-trust-posix type ranges from different forests cannot
# overlap on base ranges, use domain3range1 and domain4range1
dict(
desc=('Modify ipa-ad-trust-posix range %r to overlap on base range'
' with posix range from different domain' % (domain3range1)),
command=('idrange_mod', [domain3range1],
dict(ipabaseid=domain4range1_base_id)),
expected=errors.DatabaseError(
desc='Constraint violation',
info='New base range overlaps with existing base range.'),
),
# 3. ipa-ad-trust ranges from same forest cannot overlap on base ranges,
# use domain5range1 and domain5range2
dict(
desc=('Modify ipa-ad-trust range %r to overlap on base range'
' with posix range from the same domain' % (domain5range1)),
command=('idrange_mod', [domain5range1],
dict(ipabaseid=domain5range2_base_id)),
expected=errors.DatabaseError(
desc='Constraint violation',
info='New base range overlaps with existing base range.'),
),
# 4. ipa-ad-trust ranges from different forests cannot overlap on base
# ranges, use domain5range1 and domain6range1
dict(
desc=('Modify ipa-ad-trust range %r to overlap on base range'
' with posix range from different domain' % (domain5range1)),
command=('idrange_mod', [domain5range1],
dict(ipabaseid=domain6range1_base_id)),
expected=errors.DatabaseError(
desc='Constraint violation',
info='New base range overlaps with existing base range.'),
),
# - RID range overlaps
# 1. Overlaps on base RID ranges are allowed for ranges from different
# domains, use domain2range1 and domain5range1
dict(
desc=('Modify ipa-ad-trust range %r to overlap on base RID'
' range with nonposix range from different domain'
% (domain2range1)),
command=('idrange_mod', [domain2range1],
dict(ipabaserid=domain5range1_base_rid)),
expected=dict(
messages=fuzzy_restart_messages,
result=dict(
cn=[domain2range1],
ipabaseid=[unicode(domain2range1_base_id)],
ipabaserid=[unicode(domain5range1_base_rid)],
ipaidrangesize=[unicode(domain2range1_size)],
ipanttrusteddomainsid=[unicode(domain2_sid)],
iparangetyperaw=[u'ipa-ad-trust'],
iparangetype=[u'Active Directory domain range'],
),
value=domain2range1,
summary=u'Modified ID range "%s"' % (domain2range1),
),
),
# 2. ipa-ad-trust ranges from the same forest cannot overlap on base
# RID ranges, use domain5range1 and domain5range2
dict(
desc=('Modify ipa-ad-trust range %r to overlap on base RID range'
' with range from the same domain' % (domain2range1)),
command=('idrange_mod', [domain2range1],
dict(ipabaserid=domain2range2_base_rid)),
expected=errors.DatabaseError(
desc='Constraint violation',
info='New primary rid range overlaps with existing primary rid '
'range.'),
),
dict(
desc=('Modify ipa-ad-trust range %r with --auto-private-groups='
'true' % (domain2range1)),
command=('idrange_mod', [domain2range1],
dict(ipaautoprivategroups='true')),
expected=dict(
messages=fuzzy_restart_messages,
result=dict(
cn=[domain2range1],
ipabaseid=[unicode(domain2range1_base_id)],
ipabaserid=[unicode(domain5range1_base_rid)],
ipaidrangesize=[unicode(domain2range1_size)],
ipanttrusteddomainsid=[unicode(domain2_sid)],
iparangetyperaw=[u'ipa-ad-trust'],
ipaautoprivategroups=[u'true'],
iparangetype=[u'Active Directory domain range'],
),
value=domain2range1,
summary=u'Modified ID range "%s"' % (domain2range1),
),
),
dict(
desc=('Modify ipa-ad-trust range %r with --auto-private-groups='
'false' % (domain2range1)),
command=('idrange_mod', [domain2range1],
dict(ipaautoprivategroups='false')),
expected=dict(
messages=fuzzy_restart_messages,
result=dict(
cn=[domain2range1],
ipabaseid=[unicode(domain2range1_base_id)],
ipabaserid=[unicode(domain5range1_base_rid)],
ipaidrangesize=[unicode(domain2range1_size)],
ipanttrusteddomainsid=[unicode(domain2_sid)],
iparangetyperaw=[u'ipa-ad-trust'],
ipaautoprivategroups=[u'false'],
iparangetype=[u'Active Directory domain range'],
),
value=domain2range1,
summary=u'Modified ID range "%s"' % (domain2range1),
),
),
dict(
desc=('Modify ipa-ad-trust range %r with --auto-private-groups='
'hybrid' % (domain2range1)),
command=('idrange_mod', [domain2range1],
dict(ipaautoprivategroups='hybrid')),
expected=dict(
messages=fuzzy_restart_messages,
result=dict(
cn=[domain2range1],
ipabaseid=[unicode(domain2range1_base_id)],
ipabaserid=[unicode(domain5range1_base_rid)],
ipaidrangesize=[unicode(domain2range1_size)],
ipanttrusteddomainsid=[unicode(domain2_sid)],
iparangetyperaw=[u'ipa-ad-trust'],
ipaautoprivategroups=[u'hybrid'],
iparangetype=[u'Active Directory domain range'],
),
value=domain2range1,
summary=u'Modified ID range "%s"' % (domain2range1),
),
),
dict(
desc=('Modify ipa-ad-trust range %r with --auto-private-groups='
'<empty>' % (domain2range1)),
command=('idrange_mod', [domain2range1],
dict(ipaautoprivategroups='')),
expected=dict(
messages=fuzzy_restart_messages,
result=dict(
cn=[domain2range1],
ipabaseid=[unicode(domain2range1_base_id)],
ipabaserid=[unicode(domain5range1_base_rid)],
ipaidrangesize=[unicode(domain2range1_size)],
ipanttrusteddomainsid=[unicode(domain2_sid)],
iparangetyperaw=[u'ipa-ad-trust'],
iparangetype=[u'Active Directory domain range'],
),
value=domain2range1,
summary=u'Modified ID range "%s"' % (domain2range1),
),
),
# Test for bug 6404
# if dom-name is empty, add should not fail
dict(
desc='Create ID range %r' % (testrange9),
command=('idrange_add', [testrange9],
dict(ipanttrusteddomainname=None,
ipabaseid=testrange9_base_id,
ipaidrangesize=testrange9_size,
ipabaserid=testrange9_base_rid,
ipasecondarybaserid=testrange9_secondary_base_rid)),
expected=dict(
result=dict(
dn=DN(('cn', testrange9), ('cn', 'ranges'), ('cn', 'etc'),
api.env.basedn),
cn=[testrange9],
objectclass=[u'ipaIDrange', u'ipadomainidrange'],
ipabaseid=[unicode(testrange9_base_id)],
ipabaserid=[unicode(testrange9_base_rid)],
ipasecondarybaserid=[
unicode(testrange9_secondary_base_rid)],
ipaidrangesize=[unicode(testrange9_size)],
iparangetyperaw=[u'ipa-local'],
iparangetype=[u'local domain range'],
),
value=testrange9,
summary=u'Added ID range "%s"' % (testrange9),
messages=(
messages.ServiceRestartRequired(
service=dirsrv_instance,
server='<all IPA servers>').to_dict(),
),
),
),
dict(
desc='Delete ID range %r' % testrange9,
command=('idrange_del', [testrange9], {}),
expected=dict(
result=dict(failed=[]),
value=[testrange9],
summary=u'Deleted ID range "%s"' % testrange9,
messages=fuzzy_restart_messages,
),
),
]
| 41,528
|
Python
|
.py
| 936
| 32.705128
| 121
| 0.59549
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,434
|
test_realmdomains_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_realmdomains_plugin.py
|
# Authors:
# Ana Krivokapic <akrivoka@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/>.
"""
Test the `ipaserver/plugins/realmdomains.py` module.
"""
from ipalib import api, errors
from ipapython.dn import DN
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import Declarative
import pytest
cn = u'Realm Domains'
dn = DN(('cn', cn), ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn)
our_domain = api.env.domain
new_domain_1 = u'example1.com'
new_domain_2 = u'example2.com'
bad_domain = u'doesnotexist.test'
sl_domain = u'singlelabeldomain'
@pytest.mark.tier1
class test_realmdomains(Declarative):
# Make sure your environment has sound DNS configuration where
# the IPA domain has either NS or SOA record. Check your resolver
# if getting errors with the realmdomains_mod cleanup command.
cleanup_commands = [
('realmdomains_mod', [], {'associateddomain': [our_domain]}),
]
tests = [
dict(
desc='Retrieve realm domains',
command=('realmdomains_show', [], {}),
expected=dict(
value=None,
summary=None,
result=dict(
dn=dn,
associateddomain=[our_domain],
),
),
),
dict(
desc='Retrieve realm domains - print all attributes',
command=('realmdomains_show', [], {'all': True}),
expected=dict(
value=None,
summary=None,
result=dict(
dn=dn,
associateddomain=[our_domain],
cn=[cn],
objectclass=objectclasses.realmdomains,
aci=[
u'(targetattr = "associateddomain || cn || '
u'createtimestamp || entryusn || '
u'modifytimestamp || objectclass")'
u'(targetfilter = "(objectclass=domainrelatedobject)")'
u'(version 3.0;acl '
u'"permission:System: Read Realm Domains";'
u'allow (compare,read,search) '
u'userdn = "ldap:///all";)',
u'(targetattr = "associateddomain")'
u'(targetfilter = "(objectclass=domainrelatedobject)")'
u'(version 3.0;acl '
u'"permission:System: Modify Realm Domains";'
u'allow (write) groupdn = "ldap:///%s";)' %
DN('cn=System: Modify Realm Domains',
api.env.container_permission,
api.env.basedn),
],
),
),
),
dict(
desc='Replace list of realm domains with "%s"' % [our_domain, new_domain_1],
command=('realmdomains_mod', [], {'associateddomain': [our_domain, new_domain_1], 'force':True}),
expected=dict(
value=None,
summary=None,
messages=({u'message': u"The _kerberos TXT record from domain "
"example1.com could not be created (%s.: "
"DNS zone not found).\nThis can happen if the zone "
"is not managed by IPA. Please create the record "
"manually, containing the following value: "
"'%s'" % (new_domain_1, api.env.realm),
u'code': 13011,
u'type': u'warning',
u'name': u'KerberosTXTRecordCreationFailure',
u'data': {
u'domain': new_domain_1,
u'realm': api.env.realm,
u'error': (u"%s.: DNS zone not found" %
new_domain_1),
}},
),
result=dict(
associateddomain=[our_domain, new_domain_1],
),
),
),
dict(
desc='Add domain "%s" to list' % new_domain_2,
command=('realmdomains_mod', [], {'add_domain': new_domain_2, 'force': True}),
expected=dict(
value=None,
summary=None,
result=dict(
associateddomain=[our_domain, new_domain_1, new_domain_2],
),
messages=({u'message': u"The _kerberos TXT record from domain "
"%(domain)s could not be created (%(domain)s.: "
"DNS zone not found).\nThis can happen if the zone "
"is not managed by IPA. Please create the record "
"manually, containing the following value: "
"'%(realm)s'" % dict(domain=new_domain_2,
realm=api.env.realm),
u'code': 13011,
u'type': u'warning',
u'name': u'KerberosTXTRecordCreationFailure',
u'data': {
u'domain': new_domain_2,
u'realm': api.env.realm,
u'error': (u"%s.: DNS zone not found" %
new_domain_2),
}},
),
),
),
dict(
desc='Delete domain "%s" from list' % new_domain_2,
command=('realmdomains_mod', [], {'del_domain': new_domain_2}),
expected=dict(
value=None,
summary=None,
result=dict(
associateddomain=[our_domain, new_domain_1],
),
messages=({u'message': u"The _kerberos TXT record from domain "
"%(domain)s could not be removed (%(domain)s.: "
"DNS zone not found).\nThis can happen if the zone "
"is not managed by IPA. Please remove the record "
"manually." % dict(domain=new_domain_2),
u'code': 13012,
u'type': u'warning',
u'name': u'KerberosTXTRecordDeletionFailure',
u'data': {
u'domain': new_domain_2,
u'error': (u"%s.: DNS zone not found" %
new_domain_2),
}},
),
),
),
dict(
desc='Add domain "%s" and delete domain "%s"' % (new_domain_2, new_domain_1),
command=('realmdomains_mod', [], {'add_domain': new_domain_2, 'del_domain': new_domain_1, 'force': True}),
expected=dict(
value=None,
summary=None,
result=dict(
associateddomain=[our_domain, new_domain_2],
),
messages=({u'message': u"The _kerberos TXT record from domain "
"%(domain)s could not be created (%(domain)s.: "
"DNS zone not found).\nThis can happen if the zone "
"is not managed by IPA. Please create the record "
"manually, containing the following value: "
"'%(realm)s'" % dict(domain=new_domain_2,
realm=api.env.realm),
u'code': 13011,
u'type': u'warning',
u'name': u'KerberosTXTRecordCreationFailure',
u'data': {
u'domain': new_domain_2,
u'realm': api.env.realm,
u'error': (u"%s.: DNS zone not found" %
new_domain_2),
}},
{u'message': u"The _kerberos TXT record from domain "
"%(domain)s could not be removed (%(domain)s.: "
"DNS zone not found).\nThis can happen if the zone "
"is not managed by IPA. Please remove the record "
"manually." % dict(domain=new_domain_1),
u'code': 13012,
u'type': u'warning',
u'name': u'KerberosTXTRecordDeletionFailure',
u'data': {
u'domain': new_domain_1,
u'error': (u"%s.: DNS zone not found" %
new_domain_1),
}},
),
),
),
dict(
desc='Try to specify --domain and --add-domain options together',
command=('realmdomains_mod', [], {
'associateddomain': [our_domain, new_domain_1],
'add_domain': new_domain_1,
}),
expected=errors.MutuallyExclusiveError(
reason='The --domain option cannot be used together with --add-domain or --del-domain. Use --domain to specify the whole realm domain list explicitly, to add/remove individual domains, use --add-domain/del-domain.'),
),
dict(
desc='Try to replace list of realm domains with a list without our domain',
command=('realmdomains_mod', [], {'associateddomain': [new_domain_1]}),
expected=errors.ValidationError(
name='realmdomain list', error='IPA server domain cannot be omitted'),
),
dict(
desc='Try to replace list of realm domains with a list with an invalid domain "%s"' % bad_domain,
command=('realmdomains_mod', [], {'associateddomain': [our_domain, bad_domain]}),
expected=errors.ValidationError(
name='domain', error='DNS zone for each realmdomain must contain SOA or NS records. No records found for: %s' % bad_domain),
),
dict(
desc='Try to add an invalid domain "%s"' % bad_domain,
command=('realmdomains_mod', [], {'add_domain': bad_domain}),
expected=errors.ValidationError(
name='domain', error='DNS zone for each realmdomain must contain SOA or NS records. No records found for: %s' % bad_domain),
),
dict(
desc='Try to delete our domain',
command=('realmdomains_mod', [], {'del_domain': our_domain}),
expected=errors.ValidationError(
name='del_domain', error='IPA server domain cannot be deleted'),
),
dict(
desc='Try to delete domain which is not in list',
command=('realmdomains_mod', [], {'del_domain': new_domain_1}),
expected=errors.AttrValueNotFound(
attr='associateddomain', value=new_domain_1),
),
dict(
desc='Add an invalid domain "%s" with --force option' % bad_domain,
command=('realmdomains_mod', [], {'add_domain': bad_domain, 'force': True}),
expected=dict(
value=None,
summary=None,
result=dict(
associateddomain=[our_domain, new_domain_2, bad_domain],
),
messages=({u'message': u"The _kerberos TXT record from domain "
"%(domain)s could not be created (%(domain)s.: "
"DNS zone not found).\nThis can happen if the zone "
"is not managed by IPA. Please create the record "
"manually, containing the following value: "
"'%(realm)s'" % dict(domain=bad_domain,
realm=api.env.realm),
u'code': 13011,
u'type': u'warning',
u'name': u'KerberosTXTRecordCreationFailure',
u'data': {
u'domain': bad_domain,
u'realm': api.env.realm,
u'error': (u"%s.: DNS zone not found" %
bad_domain),
}},
),
),
),
dict(
desc='Add a single label domain {}'.format(sl_domain),
command=('realmdomains_mod', [], {'add_domain': sl_domain}),
expected=errors.ValidationError(
name='add_domain',
error='single label domains are not supported'
),
)
]
| 13,841
|
Python
|
.py
| 283
| 30.473498
| 232
| 0.464389
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,435
|
test_sudocmd_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_sudocmd_plugin.py
|
# Authors:
# Jr Aquino <jr.aquino@citrixonline.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 the `ipaserver/plugins/sudocmd.py` module.
"""
from ipalib import api, errors
from ipatests.util import assert_deepequal
from ipatests.test_xmlrpc.xmlrpc_test import (XMLRPC_test, raises_exact)
from ipatests.test_xmlrpc.tracker.sudocmd_plugin import SudoCmdTracker
import pytest
@pytest.fixture(scope='class')
def sudocmd1(request, xmlrpc_setup):
tracker = SudoCmdTracker(command=u'/usr/bin/sudotestcmd1',
description=u'Test sudo command 1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def sudocmd2(request, xmlrpc_setup):
tracker = SudoCmdTracker(command=u'/usr/bin/sudoTestCmd1',
description=u'Test sudo command 2')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def sudorule1(request, xmlrpc_setup):
name = u'test_sudorule1'
def fin():
api.Command['sudorule_del'](name)
request.addfinalizer(fin)
return name
@pytest.mark.tier1
class TestNonexistentSudoCmd(XMLRPC_test):
def test_retrieve_nonexistent(self, sudocmd1):
""" Try to retrieve non-existent sudocmd """
command = sudocmd1.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: sudo command not found' % sudocmd1.cmd)):
command()
def test_update_nonexistent(self, sudocmd1):
""" Try to update non-existent sudocmd """
command = sudocmd1.make_update_command(dict(description=u'Nope'))
with raises_exact(errors.NotFound(
reason=u'%s: sudo command not found' % sudocmd1.cmd)):
command()
def test_delete_nonexistent(self, sudocmd1):
""" Try to delete non-existent sudocmd """
command = sudocmd1.make_delete_command()
with raises_exact(errors.NotFound(
reason=u'%s: sudo command not found' % sudocmd1.cmd)):
command()
@pytest.mark.tier1
class TestSudoCmd(XMLRPC_test):
def test_create(self, sudocmd1, sudocmd2):
""" Create sudocmd and sudocmd with camelcase'd command """
sudocmd1.ensure_exists()
sudocmd2.ensure_exists()
def test_create_duplicates(self, sudocmd1, sudocmd2):
""" Try to create duplicate sudocmds """
sudocmd1.ensure_exists()
sudocmd2.ensure_exists()
command1 = sudocmd1.make_create_command()
command2 = sudocmd2.make_create_command()
with raises_exact(errors.DuplicateEntry(
message=u'sudo command with name "%s" already exists' %
sudocmd1.cmd)):
command1()
with raises_exact(errors.DuplicateEntry(
message=u'sudo command with name "%s" already exists' %
sudocmd2.cmd)):
command2()
def test_retrieve(self, sudocmd1):
""" Retrieve sudocmd """
sudocmd1.ensure_exists()
sudocmd1.retrieve()
def test_search(self, sudocmd1, sudocmd2):
""" Search for sudocmd """
sudocmd1.find()
sudocmd2.find()
def test_update_and_verify(self, sudocmd1):
""" Update sudocmd description and verify by retrieve """
sudocmd1_desc_new = u'Updated sudo command 1'
sudocmd1.update(dict(description=sudocmd1_desc_new),
dict(description=[sudocmd1_desc_new]))
sudocmd1.retrieve()
@pytest.mark.tier1
class TestSudoCmdInSudoRuleLists(XMLRPC_test):
def test_add_sudocmd_to_sudorule_allow_list(self, sudocmd1, sudorule1):
""" Add sudocmd to sudorule allow list """
sudocmd1.ensure_exists()
api.Command['sudorule_add'](sudorule1)
result = api.Command['sudorule_add_allow_command'](
sudorule1, sudocmd=sudocmd1.cmd
)
assert_deepequal(dict(
completed=1,
failed=dict(
memberallowcmd=dict(sudocmdgroup=(), sudocmd=())),
result=lambda result: True,
), result)
def test_del_dependent_sudocmd_sudorule_allow(self, sudocmd1, sudorule1):
""" Try to delete sudocmd that is in sudorule allow list """
sudocmd1.ensure_exists()
command = sudocmd1.make_delete_command()
with raises_exact(errors.DependentEntry(
key=sudocmd1.cmd,
label='sudorule',
dependent=sudorule1)):
command()
def test_remove_sudocmd_from_sudorule_allow(self, sudocmd1, sudorule1):
""" Remove sudocmd from sudorule allow list """
sudocmd1.ensure_exists()
result = api.Command['sudorule_remove_allow_command'](
sudorule1, sudocmd=sudocmd1.cmd
)
assert_deepequal(dict(
completed=1,
failed=dict(
memberallowcmd=dict(sudocmdgroup=(), sudocmd=())),
result=lambda result: True),
result)
def test_add_sudocmd_to_sudorule_deny_list(self, sudocmd1, sudorule1):
""" Add sudocmd to sudorule deny list """
sudocmd1.ensure_exists()
result = api.Command['sudorule_add_deny_command'](
sudorule1, sudocmd=sudocmd1.cmd
)
assert_deepequal(dict(
completed=1,
failed=dict(
memberdenycmd=dict(sudocmdgroup=(), sudocmd=())),
result=lambda result: True),
result)
def test_del_dependent_sudocmd_sudorule_deny(self, sudocmd1, sudorule1):
""" Try to delete sudocmd that is in sudorule deny list """
sudocmd1.ensure_exists()
command = sudocmd1.make_delete_command()
with raises_exact(errors.DependentEntry(
key=sudocmd1.cmd,
label='sudorule',
dependent=sudorule1)):
command()
def test_remove_sudocmd_from_sudorule_deny(self, sudocmd1, sudorule1):
""" Remove sudocmd from sudorule deny list """
sudocmd1.ensure_exists()
result = api.Command['sudorule_remove_deny_command'](
sudorule1, sudocmd=sudocmd1.cmd
)
assert_deepequal(dict(
completed=1,
failed=dict(
memberdenycmd=dict(sudocmdgroup=(), sudocmd=())),
result=lambda result: True),
result)
| 7,017
|
Python
|
.py
| 166
| 33.674699
| 77
| 0.647714
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,436
|
test_old_permission_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_old_permission_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Pavel Zuna <pzuna@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 the `ipaserver/plugins/permission.py` module with old API.
This ensures basic backwards compatibility for code before
http://www.freeipa.org/page/V3/Permissions_V2
"""
from ipalib import api, errors
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import Declarative
from ipapython.dn import DN
import pytest
permission1 = u'testperm'
permission1_dn = DN(('cn',permission1),
api.env.container_permission,api.env.basedn)
permission1_renamed = u'testperm1_rn'
permission1_renamed_dn = DN(('cn',permission1_renamed),
api.env.container_permission,api.env.basedn)
permission1_renamed_ucase = u'Testperm_RN'
permission1_renamed_ucase_dn = DN(('cn',permission1_renamed_ucase),
api.env.container_permission,api.env.basedn)
permission2 = u'testperm2'
permission2_dn = DN(('cn',permission2),
api.env.container_permission,api.env.basedn)
permission3 = u'testperm3'
permission3_dn = DN(('cn',permission3),
api.env.container_permission,api.env.basedn)
permission3_attributelevelrights = {
'member': u'rscwo',
'seealso': u'rscwo',
'ipapermissiontype': u'rscwo',
'cn': u'rscwo',
'businesscategory': u'rscwo',
'objectclass': u'rscwo',
'memberof': u'rscwo',
'aci': u'rscwo',
'o': u'rscwo',
'owner': u'rscwo',
'ou': u'rscwo',
'targetgroup': u'rscwo',
'type': u'rscwo',
'nsaccountlock': u'rscwo',
'description': u'rscwo',
'attrs': u'rscwo',
'ipapermincludedattr': u'rscwo',
'ipapermbindruletype': u'rscwo',
'ipapermdefaultattr': u'rscwo',
'ipapermexcludedattr': u'rscwo',
'subtree': u'rscwo', # old
'permissions': u'rscwo', # old
'ipapermtarget': u'rscwo',
'ipapermtargetfilter': u'rscwo',
'ipapermtargetto': u'rscwo',
'ipapermtargetfrom': u'rscwo',
}
privilege1 = u'testpriv1'
privilege1_dn = DN(('cn',privilege1),
api.env.container_privilege,api.env.basedn)
invalid_permission1 = u'bad;perm'
users_dn = DN(api.env.container_user, api.env.basedn)
groups_dn = DN(api.env.container_group, api.env.basedn)
hbac_dn = DN(api.env.container_hbac, api.env.basedn)
@pytest.mark.tier1
class test_old_permission(Declarative):
default_version = u'2.65'
cleanup_commands = [
('permission_del', [permission1], {}),
('permission_del', [permission2], {}),
('permission_del', [permission3], {}),
('privilege_del', [privilege1], {}),
]
tests = [
dict(
desc='Try to retrieve non-existent %r' % permission1,
command=('permission_show', [permission1], {}),
expected=errors.NotFound(
reason=u'%s: permission not found' % permission1),
),
dict(
desc='Try to update non-existent %r' % permission1,
command=('permission_mod', [permission1], dict(permissions=u'all')),
expected=errors.NotFound(
reason=u'%s: permission not found' % permission1),
),
dict(
desc='Try to delete non-existent %r' % permission1,
command=('permission_del', [permission1], {}),
expected=errors.NotFound(
reason=u'%s: permission not found' % permission1),
),
dict(
desc='Search for non-existent %r' % permission1,
command=('permission_find', [permission1], {}),
expected=dict(
count=0,
truncated=False,
summary=u'0 permissions matched',
result=[],
),
),
dict(
desc='Create %r' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
permissions=u'write',
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=u'user',
permissions=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'V2', u'SYSTEM'],
subtree=u'ldap:///%s' % users_dn,
),
),
),
dict(
desc='Try to create duplicate %r' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
permissions=u'write',
),
),
expected=errors.DuplicateEntry(
message='permission with name "%s" already exists' % permission1),
),
dict(
desc='Create %r' % privilege1,
command=('privilege_add', [privilege1],
dict(description=u'privilege desc. 1')
),
expected=dict(
value=privilege1,
summary=u'Added privilege "%s"' % privilege1,
result=dict(
dn=privilege1_dn,
cn=[privilege1],
description=[u'privilege desc. 1'],
objectclass=objectclasses.privilege,
),
),
),
dict(
desc='Add permission %r to privilege %r' % (permission1, privilege1),
command=('privilege_add_permission', [privilege1],
dict(permission=permission1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
permission=[],
),
),
result={
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
'memberof_permission': [permission1],
}
),
),
dict(
desc='Retrieve %r' % permission1,
command=('permission_show', [permission1], {}),
expected=dict(
value=permission1,
summary=None,
result={
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
),
),
dict(
desc='Retrieve %r with --raw' % permission1,
command=('permission_show', [permission1], {'raw' : True}),
expected=dict(
value=permission1,
summary=None,
result={
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member': [privilege1_dn],
'aci': [u'(targetfilter = "(objectclass=posixaccount)")'+
u'(version 3.0;acl "permission:testperm";' +
u'allow (write) ' +
u'groupdn = "ldap:///%s";)' % DN(
('cn', 'testperm'), ('cn', 'permissions'),
('cn', 'pbac'), api.env.basedn)],
'ipapermright': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'ipapermtargetfilter': [u'(objectclass=posixaccount)'],
'ipapermlocation': [users_dn],
},
),
),
dict(
desc='Search for %r with members' % permission1,
command=('permission_find', [permission1], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
],
),
),
dict(
desc='Search for %r' % permission1,
command=('permission_find', [permission1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
],
),
),
dict(
desc='Search for %r using --name with members' % permission1,
command=('permission_find', [], {
'cn': permission1, 'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
],
),
),
dict(
desc='Search for %r using --name' % permission1,
command=('permission_find', [], {'cn': permission1}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
],
),
),
dict(
desc='Search for non-existence permission using --name',
command=('permission_find', [], {'cn': u'notfound'}),
expected=dict(
count=0,
truncated=False,
summary=u'0 permissions matched',
result=[],
),
),
dict(
desc='Search for %r with members' % privilege1,
command=('permission_find', [privilege1], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
],
),
),
dict(
desc='Search for %r' % privilege1,
command=('permission_find', [privilege1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
],
),
),
dict(
desc='Search for %r with --raw with members' % permission1,
command=('permission_find', [permission1], {
'raw': True, 'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member': [privilege1_dn],
'aci': [u'(targetfilter = "(objectclass=posixaccount)")(version 3.0;acl "permission:testperm";allow (write) groupdn = "ldap:///%s";)' % \
DN(('cn', 'testperm'), ('cn', 'permissions'), ('cn', 'pbac'), api.env.basedn)],
'ipapermright': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'ipapermtargetfilter': [u'(objectclass=posixaccount)'],
'ipapermlocation': [users_dn],
},
],
),
),
dict(
desc='Search for %r with --raw' % permission1,
command=('permission_find', [permission1], {'raw': True}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'aci': [
u'(targetfilter = "(objectclass=posixaccount)")'
u'(version 3.0;acl "permission:testperm";'
u'allow (write) groupdn = "ldap:///%s";)' %
DN(
('cn', 'testperm'), ('cn', 'permissions'),
('cn', 'pbac'), api.env.basedn
)
],
'ipapermright': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'ipapermtargetfilter': [u'(objectclass=posixaccount)'],
'ipapermlocation': [users_dn],
},
],
),
),
dict(
desc='Create %r' % permission2,
command=(
'permission_add', [permission2], dict(
type=u'user',
permissions=u'write',
setattr=u'owner=cn=test',
addattr=u'owner=cn=test2',
)
),
expected=dict(
value=permission2,
summary=u'Added permission "%s"' % permission2,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission2_dn,
cn=[permission2],
objectclass=objectclasses.permission,
type=u'user',
permissions=[u'write'],
owner=[u'cn=test', u'cn=test2'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'V2', u'SYSTEM'],
subtree=u'ldap:///%s' % users_dn,
),
),
),
dict(
desc='Search for %r with members' % permission1,
command=('permission_find', [permission1], {'no_members': False}),
expected=dict(
count=2,
truncated=False,
summary=u'2 permissions matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
{
'dn': permission2_dn,
'cn': [permission2],
'objectclass': objectclasses.permission,
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
],
),
),
dict(
desc='Search for %r' % permission1,
command=('permission_find', [permission1], {}),
expected=dict(
count=2,
truncated=False,
summary=u'2 permissions matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
{
'dn': permission2_dn,
'cn': [permission2],
'objectclass': objectclasses.permission,
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
],
),
),
dict(
desc='Search for %r with --pkey-only' % permission1,
command=('permission_find', [permission1], {'pkey_only' : True}),
expected=dict(
count=2,
truncated=False,
summary=u'2 permissions matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
},
{
'dn': permission2_dn,
'cn': [permission2],
},
],
),
),
dict(
desc='Search by ACI attribute with --pkey-only',
command=('permission_find', [], {'pkey_only': True,
'attrs': [u'krbminpwdlife']}),
expected=dict(
count=2,
truncated=False,
summary=u'2 permissions matched',
result=[
{
'dn': DN(('cn', 'System: Modify Group Password Policy'),
api.env.container_permission, api.env.basedn),
'cn': [u'System: Modify Group Password Policy'],
},
{
'dn': DN(('cn', 'System: Read Group Password Policy'),
api.env.container_permission, api.env.basedn),
'cn': [u'System: Read Group Password Policy'],
},
],
),
),
dict(
desc='Search for %r with members' % privilege1,
command=('privilege_find', [privilege1], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 privilege matched',
result=[
{
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
'memberof_permission': [permission1],
},
],
),
),
dict(
desc='Search for %r' % privilege1,
command=('privilege_find', [privilege1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 privilege matched',
result=[
{
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
},
],
),
),
dict(
desc=('Search for %r with a limit of 1 (truncated) with members' %
permission1),
command=('permission_find', [permission1], dict(
sizelimit=1, no_members=False)),
expected=dict(
count=1,
truncated=True,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
],
messages=({
'message': (u'Search result has been truncated: '
u'Configured size limit exceeded'),
'code': 13017,
'type': u'warning',
'name': u'SearchResultTruncated',
'data': {
'reason': u"Configured size limit exceeded"
}
},),
),
),
dict(
desc='Search for %r with a limit of 1 (truncated)' % permission1,
command=('permission_find', [permission1], dict(sizelimit=1)),
expected=dict(
count=1,
truncated=True,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
],
messages=({
'message': (u'Search result has been truncated: '
u'Configured size limit exceeded'),
'code': 13017,
'type': u'warning',
'name': u'SearchResultTruncated',
'data': {
'reason': u"Configured size limit exceeded"
}
},),
),
),
dict(
desc='Search for %r with a limit of 2' % permission1,
command=('permission_find', [permission1], dict(sizelimit=2)),
expected=dict(
count=2,
truncated=False,
summary=u'2 permissions matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
{
'dn': permission2_dn,
'cn': [permission2],
'objectclass': objectclasses.permission,
'type': u'user',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
],
),
),
# This tests setting truncated to True in the post_callback of
# permission_find(). The return order in LDAP is not guaranteed
# so do not check the actual entry.
dict(
desc='Search for permissions by attr with a limit of 1 (truncated)',
command=('permission_find', [u'Modify'],
dict(attrs=u'ipaenabledflag', sizelimit=1)),
expected=dict(
count=1,
truncated=True,
summary=u'1 permission matched',
result=[lambda res:
DN(res['dn']).endswith(DN(api.env.container_permission,
api.env.basedn)) and
'ipapermission' in res['objectclass']],
messages=({
'message': (u'Search result has been truncated: '
u'Configured size limit exceeded'),
'code': 13017,
'type': u'warning',
'name': u'SearchResultTruncated',
'data': {
'reason': u"Configured size limit exceeded"
}
},),
),
),
dict(
desc='Update %r' % permission1,
command=(
'permission_mod', [permission1], dict(
permissions=u'read',
memberof=u'ipausers',
setattr=u'owner=cn=other-test',
addattr=u'owner=cn=other-test2',
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
messages=(
{
'message': ('The permission has read rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'read',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
member_privilege=[privilege1],
type=u'user',
permissions=[u'read'],
memberof=u'ipausers',
owner=[u'cn=other-test', u'cn=other-test2'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'V2', u'SYSTEM'],
subtree=u'ldap:///%s' % users_dn,
),
),
),
dict(
desc='Retrieve %r to verify update' % permission1,
command=('permission_show', [permission1], {}),
expected=dict(
value=permission1,
summary=None,
result={
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': u'user',
'permissions': [u'read'],
'memberof': u'ipausers',
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
),
),
dict(
desc='Try to rename %r to existing permission %r' % (permission1,
permission2),
command=(
'permission_mod', [permission1], dict(rename=permission2,
permissions=u'all',)
),
expected=errors.DuplicateEntry(),
),
dict(
desc='Try to rename %r to empty name' % (permission1),
command=(
'permission_mod', [permission1], dict(rename=u'',
permissions=u'all',)
),
expected=errors.ValidationError(name='rename',
error=u'New name can not be empty'),
),
dict(
desc='Check integrity of original permission %r' % permission1,
command=('permission_show', [permission1], {}),
expected=dict(
value=permission1,
summary=None,
result={
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': u'user',
'permissions': [u'read'],
'memberof': u'ipausers',
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
),
),
dict(
desc='Rename %r to permission %r' % (permission1,
permission1_renamed),
command=(
'permission_mod', [permission1], dict(rename=permission1_renamed,
permissions= u'all',)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result={
'dn': permission1_renamed_dn,
'cn': [permission1_renamed],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': u'user',
'permissions': [u'all'],
'memberof': u'ipausers',
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
),
),
dict(
desc='Rename %r to permission %r' % (permission1_renamed,
permission1_renamed_ucase),
command=(
'permission_mod', [permission1_renamed], dict(rename=permission1_renamed_ucase,
permissions= u'write',)
),
expected=dict(
value=permission1_renamed,
summary=u'Modified permission "%s"' % permission1_renamed,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result={
'dn': permission1_renamed_ucase_dn,
'cn': [permission1_renamed_ucase],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': u'user',
'permissions': [u'write'],
'memberof': u'ipausers',
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
'subtree': u'ldap:///%s' % users_dn,
},
),
),
dict(
desc='Change %r to a subtree type' % permission1_renamed_ucase,
command=(
'permission_mod', [permission1_renamed_ucase],
dict(subtree=u'ldap:///%s' % DN(('cn', 'accounts'), api.env.basedn),
type=None)
),
expected=dict(
value=permission1_renamed_ucase,
summary=u'Modified permission "%s"' % permission1_renamed_ucase,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_renamed_ucase_dn,
cn=[permission1_renamed_ucase],
objectclass=objectclasses.permission,
member_privilege=[privilege1],
subtree=u'ldap:///%s' % DN(('cn', 'accounts'), api.env.basedn),
permissions=[u'write'],
memberof=u'ipausers',
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'V2', u'SYSTEM'],
),
),
),
dict(
desc='Search for %r using --subtree with members' % permission1,
command=('permission_find', [], {
'subtree': u'ldap:///%s' % DN(
('cn', 'accounts'), api.env.basedn),
'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn':permission1_renamed_ucase_dn,
'cn':[permission1_renamed_ucase],
'objectclass': objectclasses.permission,
'member_privilege':[privilege1],
'subtree':u'ldap:///%s' % DN(('cn', 'accounts'), api.env.basedn),
'permissions':[u'write'],
'memberof':u'ipausers',
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
},
],
),
),
dict(
desc='Search for %r using --subtree' % permission1,
command=('permission_find', [], {
'subtree': u'ldap:///%s' % DN(
('cn', 'accounts'), api.env.basedn)}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn':permission1_renamed_ucase_dn,
'cn':[permission1_renamed_ucase],
'objectclass': objectclasses.permission,
'subtree':u'ldap:///%s' % DN(
('cn', 'accounts'), api.env.basedn),
'permissions':[u'write'],
'memberof':u'ipausers',
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'V2', u'SYSTEM'],
},
],
),
),
dict(
desc='Search using nonexistent --subtree',
command=('permission_find', [], {'subtree': u'ldap:///foo=bar'}),
expected=dict(
count=0,
truncated=False,
summary=u'0 permissions matched',
result=[],
),
),
dict(
desc='Search using --targetgroup with members',
command=('permission_find', [], {
'targetgroup': u'ipausers', 'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': DN(('cn', 'System: Add User to default group'),
api.env.container_permission, api.env.basedn),
'cn': [u'System: Add User to default group'],
'objectclass': objectclasses.permission,
'member_privilege': [u'User Administrators'],
'attrs': [u'member'],
'targetgroup': u'ipausers',
'memberindirect_role': [u'User Administrator'],
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermtarget': [DN('cn=ipausers', groups_dn)],
'subtree': u'ldap:///%s' % groups_dn,
'ipapermdefaultattr': [u'member'],
'ipapermissiontype': [u'V2', u'MANAGED', u'SYSTEM'],
}
],
),
),
dict(
desc='Search using --targetgroup',
command=('permission_find', [], {'targetgroup': u'ipausers'}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': DN(('cn', 'System: Add User to default group'),
api.env.container_permission, api.env.basedn),
'cn': [u'System: Add User to default group'],
'objectclass': objectclasses.permission,
'attrs': [u'member'],
'targetgroup': u'ipausers',
'permissions': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermtarget': [DN('cn=ipausers', groups_dn)],
'subtree': u'ldap:///%s' % groups_dn,
'ipapermdefaultattr': [u'member'],
'ipapermissiontype': [u'V2', u'MANAGED', u'SYSTEM'],
}
],
),
),
dict(
desc='Delete %r' % permission1_renamed_ucase,
command=('permission_del', [permission1_renamed_ucase], {}),
expected=dict(
result=dict(failed=u''),
value=permission1_renamed_ucase,
summary=u'Deleted permission "%s"' % permission1_renamed_ucase,
)
),
dict(
desc='Try to delete non-existent %r' % permission1,
command=('permission_del', [permission1], {}),
expected=errors.NotFound(
reason=u'%s: permission not found' % permission1),
),
dict(
desc='Try to retrieve non-existent %r' % permission1,
command=('permission_show', [permission1], {}),
expected=errors.NotFound(
reason=u'%s: permission not found' % permission1),
),
dict(
desc='Try to update non-existent %r' % permission1,
command=('permission_mod', [permission1], dict(rename=u'Foo')),
expected=errors.NotFound(
reason=u'%s: permission not found' % permission1),
),
dict(
desc='Delete %r' % permission2,
command=('permission_del', [permission2], {}),
expected=dict(
result=dict(failed=u''),
value=permission2,
summary=u'Deleted permission "%s"' % permission2,
)
),
dict(
desc='Search for %r' % permission1,
command=('permission_find', [permission1], {}),
expected=dict(
count=0,
truncated=False,
summary=u'0 permissions matched',
result=[],
),
),
dict(
desc='Delete %r' % privilege1,
command=('privilege_del', [privilege1], {}),
expected=dict(
result=dict(failed=u''),
value=privilege1,
summary=u'Deleted privilege "%s"' % privilege1,
)
),
dict(
desc='Try to create permission %r with non-existing memberof' % permission1,
command=(
'permission_add', [permission1], dict(
memberof=u'nonexisting',
permissions=u'write',
)
),
expected=errors.NotFound(reason=u'nonexisting: group not found'),
),
dict(
desc='Create memberof permission %r' % permission1,
command=(
'permission_add', [permission1], dict(
memberof=u'editors',
permissions=u'write',
type=u'user',
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
memberof=u'editors',
permissions=[u'write'],
type=u'user',
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'V2', u'SYSTEM'],
subtree=u'ldap:///%s' % users_dn,
),
),
),
dict(
desc='Try to update non-existent memberof of %r' % permission1,
command=('permission_mod', [permission1], dict(
memberof=u'nonexisting')),
expected=errors.NotFound(reason=u'nonexisting: group not found'),
),
dict(
desc='Update memberof permission %r' % permission1,
command=(
'permission_mod', [permission1], dict(
memberof=u'admins',
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
memberof=u'admins',
permissions=[u'write'],
type=u'user',
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'V2', u'SYSTEM'],
subtree=u'ldap:///%s' % users_dn,
),
),
),
dict(
desc='Unset memberof of permission %r' % permission1,
command=(
'permission_mod', [permission1], dict(
memberof=None,
)
),
expected=dict(
summary=u'Modified permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
value=permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
permissions=[u'write'],
type=u'user',
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'V2', u'SYSTEM'],
subtree=u'ldap:///%s' % users_dn,
),
),
),
dict(
desc='Delete %r' % permission1,
command=('permission_del', [permission1], {}),
expected=dict(
result=dict(failed=u''),
value=permission1,
summary=u'Deleted permission "%s"' % permission1,
)
),
dict(
desc='Create targetgroup permission %r' % permission1,
command=(
'permission_add', [permission1], dict(
targetgroup=u'editors',
permissions=u'write',
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
targetgroup=u'editors',
permissions=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'V2', u'SYSTEM'],
ipapermtarget=[DN('cn=editors', groups_dn)],
subtree=u'ldap:///%s' % api.env.basedn,
),
),
),
dict(
desc='Try to create invalid %r' % invalid_permission1,
command=('permission_add', [invalid_permission1], dict(
type=u'user',
permissions=u'write',
)),
expected=errors.ValidationError(name='name',
error='May only contain letters, numbers, -, _, ., and space'),
),
dict(
desc='Create %r' % permission3,
command=(
'permission_add', [permission3], dict(
type=u'user',
permissions=u'write',
attrs=[u'cn']
)
),
expected=dict(
value=permission3,
summary=u'Added permission "%s"' % permission3,
result=dict(
dn=permission3_dn,
cn=[permission3],
objectclass=objectclasses.permission,
type=u'user',
permissions=[u'write'],
attrs=(u'cn',),
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'V2', u'SYSTEM'],
subtree=u'ldap:///%s' % users_dn,
),
),
),
dict(
desc='Retrieve %r with --all --rights' % permission3,
command=('permission_show', [permission3], {'all' : True, 'rights' : True}),
expected=dict(
value=permission3,
summary=None,
result=dict(
dn=permission3_dn,
cn=[permission3],
objectclass=objectclasses.permission,
type=u'user',
attrs=(u'cn',),
ipapermincludedattr=[u'cn'],
permissions=[u'write'],
attributelevelrights=permission3_attributelevelrights,
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'V2', u'SYSTEM'],
ipapermtargetfilter=[u'(objectclass=posixaccount)'],
subtree=u'ldap:///%s' % users_dn,
),
),
),
dict(
desc='Modify %r with --all -rights' % permission3,
command=('permission_mod', [permission3], {'all' : True, 'rights': True, 'attrs':[u'cn',u'uid']}),
expected=dict(
value=permission3,
summary=u'Modified permission "%s"' % permission3,
result=dict(
dn=permission3_dn,
cn=[permission3],
objectclass=objectclasses.permission,
type=u'user',
attrs=(u'cn',u'uid'),
ipapermincludedattr=[u'cn', u'uid'],
permissions=[u'write'],
attributelevelrights=permission3_attributelevelrights,
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'V2', u'SYSTEM'],
ipapermtargetfilter=[u'(objectclass=posixaccount)'],
subtree=u'ldap:///%s' % users_dn,
),
),
),
]
| 55,595
|
Python
|
.py
| 1,342
| 22.921013
| 161
| 0.413872
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,437
|
test_host_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_host_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Pavel Zuna <pzuna@redhat.com>
# Petr Viktorin <pviktori@redhat.com>
#
# Copyright (C) 2008, 2009 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 `ipalib.plugins.host` module.
"""
from __future__ import print_function, absolute_import
import base64
import os
import tempfile
import pytest
from ipalib import api, errors, messages
from ipalib.constants import MAXHOSTNAMELEN
from ipaplatform.paths import paths
from ipapython import ipautil
from ipapython.dn import DN
from ipapython.dnsutil import DNSName
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.test_user_plugin import get_group_dn
from ipatests.test_xmlrpc.testcert import get_testcert, subject_base
from ipatests.test_xmlrpc.tracker.host_plugin import HostTracker
from ipatests.test_xmlrpc.xmlrpc_test import (XMLRPC_test,
fuzzy_uuid, fuzzy_digits,
fuzzy_hash, fuzzy_date,
fuzzy_issuer,
fuzzy_hex, raises_exact)
from ipatests.util import assert_deepequal
# Constants DNS integration tests
# TODO: Use tracker fixtures for zones/records/users/groups
dnszone = u'test-zone.test'
dnszone_absolute = dnszone + '.'
dnszone_dn = DN(('idnsname', dnszone_absolute), api.env.container_dns, api.env.basedn)
dnszone_rname = u'root.%s' % dnszone_absolute
dnszone_rname_dnsname = DNSName(dnszone_rname)
revzone = u'29.16.172.in-addr.arpa.'
revzone_dn = DN(('idnsname', revzone), api.env.container_dns, api.env.basedn)
revipv6zone = u'0.0.0.0.1.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa.'
revipv6zone_dn = DN(('idnsname', revipv6zone), api.env.container_dns, api.env.basedn)
arec = u'172.16.29.22'
aaaarec = u'2001:db8:1::beef'
arec2 = u'172.16.29.33'
aaaarec2 = u'2001:db8:1::dead'
ipv4_fromip = u'testipv4fromip'
ipv4_fromip_ip = u'172.16.29.40'
ipv4_fromip_arec = ipv4_fromip_ip
ipv4_fromip_dnsname = DNSName(ipv4_fromip)
ipv4_fromip_dn = DN(('idnsname', ipv4_fromip), dnszone_dn)
ipv4_fromip_host_fqdn = u'%s.%s' % (ipv4_fromip, dnszone)
ipv4_fromip_ptr = u'40'
ipv4_fromip_ptr_dnsname = DNSName(ipv4_fromip_ptr)
ipv4_fromip_ptr_dn = DN(('idnsname', ipv4_fromip_ptr), revzone_dn)
ipv6_fromip = u'testipv6fromip'
ipv6_fromip_ipv6 = u'2001:db8:1::9'
ipv6_fromip_aaaarec = ipv6_fromip_ipv6
ipv6_fromip_dnsname = DNSName(ipv6_fromip)
ipv6_fromip_dn = DN(('idnsname', ipv6_fromip), dnszone_dn)
ipv6_fromip_ptr = u'9.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0'
ipv6_fromip_ptr_dnsname = DNSName(ipv6_fromip_ptr)
ipv6_fromip_ptr_dn = DN(('idnsname', ipv6_fromip_ptr), revipv6zone_dn)
sshpubkey = u'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDGAX3xAeLeaJggwTqMjxNwa6XHBUAikXPGMzEpVrlLDCZtv00djsFTBi38PkgxBJVkgRWMrcBsr/35lq7P6w8KGIwA8GI48Z0qBS2NBMJ2u9WQ2hjLN6GdMlo77O0uJY3251p12pCVIS/bHRSq8kHO2No8g7KA9fGGcagPfQH+ee3t7HUkpbQkFTmbPPN++r3V8oVUk5LxbryB3UIIVzNmcSIn3JrXynlvui4MixvrtX6zx+O/bBo68o8/eZD26QrahVbA09fivrn/4h3TM019Eu/c2jOdckfU3cHUV/3Tno5d6JicibyaoDDK7S/yjdn5jhaz8MSEayQvFkZkiF0L public key test'
sshpubkeyfp = u'SHA256:cStA9o5TRSARbeketEOooMUMSWRSsArIAXloBZ4vNsE public key test (ssh-rsa)'
user1 = u'tuser1'
user2 = u'tuser2'
group1 = u'group1'
group1_dn = get_group_dn(group1)
group2 = u'group2'
group2_dn = get_group_dn(group2)
hostgroup1 = u'testhostgroup1'
hostgroup1_dn = DN(('cn',hostgroup1),('cn','hostgroups'),('cn','accounts'),
api.env.basedn)
host_cert = get_testcert(DN(('CN', api.env.host), subject_base()),
'host/%s@%s' % (api.env.host, api.env.realm))
missingrevzone = u'22.30.16.172.in-addr.arpa.'
ipv4_in_missingrevzone_ip = u'172.16.30.22'
@pytest.fixture(scope='class')
def host(request, xmlrpc_setup):
tracker = HostTracker(name=u'testhost1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def host2(request, xmlrpc_setup):
tracker = HostTracker(name=u'testhost2')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def host3(request, xmlrpc_setup):
tracker = HostTracker(name=u'testhost3')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def host4(request, xmlrpc_setup):
tracker = HostTracker(name=u'testhost4')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def host5(request, xmlrpc_setup):
tracker = HostTracker(name=u'testhost5')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def lab_host(request, xmlrpc_setup):
name = u'testhost1'
tracker = HostTracker(name=name,
fqdn=u'%s.lab.%s' % (name, api.env.domain))
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def this_host(request, xmlrpc_setup):
"""Fixture for the current master"""
tracker = HostTracker(name=api.env.host.partition('.')[0],
fqdn=api.env.host)
tracker.exists = True
# Finalizer ensures that any certificates added to this_host are removed
tracker.add_finalizer_certcleanup(request)
# This host is not created/deleted, so don't call make_fixture
return tracker
@pytest.fixture(scope='class')
def invalid_host(request, xmlrpc_setup):
tracker = HostTracker(name='foo_bar',)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def ipv6only_host(request, xmlrpc_setup):
name = u'testipv6onlyhost'
tracker = HostTracker(name=name, fqdn=u'%s.%s' % (name, dnszone))
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def ipv4only_host(request, xmlrpc_setup):
name = u'testipv4onlyhost'
tracker = HostTracker(name=name, fqdn=u'%s.%s' % (name, dnszone))
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def ipv46both_host(request, xmlrpc_setup):
name = u'testipv4and6host'
tracker = HostTracker(name=name, fqdn=u'%s.%s' % (name, dnszone))
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def ipv4_fromip_host(request, xmlrpc_setup):
name = u'testipv4fromip'
tracker = HostTracker(name=name, fqdn=u'%s.%s' % (name, dnszone))
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def ipv6_fromip_host(request, xmlrpc_setup):
name = u'testipv6fromip'
tracker = HostTracker(name=name, fqdn=u'%s.%s' % (name, dnszone))
return tracker.make_fixture(request)
@pytest.mark.tier1
class TestNonexistentHost(XMLRPC_test):
def test_retrieve_nonexistent(self, host):
host.ensure_missing()
command = host.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: host not found' % host.fqdn)):
command()
def test_update_nonexistent(self, host):
host.ensure_missing()
command = host.make_update_command(updates=dict(description=u'Nope'))
with raises_exact(errors.NotFound(
reason=u'%s: host not found' % host.fqdn)):
command()
def test_delete_nonexistent(self, host):
host.ensure_missing()
command = host.make_delete_command()
with raises_exact(errors.NotFound(
reason=u'%s: host not found' % host.fqdn)):
command()
@pytest.mark.tier1
class TestCRUD(XMLRPC_test):
def test_create_duplicate(self, host):
host.ensure_exists()
command = host.make_create_command(force=True)
with raises_exact(errors.DuplicateEntry(
message=u'host with name "%s" already exists' % host.fqdn)):
command()
def test_retrieve_simple(self, host):
host.retrieve()
def test_retrieve_all(self, host):
host.retrieve(all=True)
def test_search_simple(self, host):
host.find()
def test_search_all(self, host):
host.find(all=True)
def test_update_simple(self, host):
host.update(dict(
description=u'Updated host 1',
usercertificate=host_cert),
expected_updates=dict(
description=[u'Updated host 1'],
usercertificate=[base64.b64decode(host_cert)],
issuer=fuzzy_issuer,
serial_number=fuzzy_digits,
serial_number_hex=fuzzy_hex,
sha1_fingerprint=fuzzy_hash,
sha256_fingerprint=fuzzy_hash,
subject=DN(('CN', api.env.host), subject_base()),
valid_not_before=fuzzy_date,
valid_not_after=fuzzy_date,
)
)
host.retrieve()
# test host-find with --certificate
command = host.make_find_command(
fqdn=host.fqdn, usercertificate=host_cert)
res = command()['result']
assert len(res) == 1
def test_host_find_pkey_only(self, host5):
# test host-find with --pkey-only
host5.ensure_exists()
command = host5.make_create_command(force=True)
host5.update(dict(ipasshpubkey=sshpubkey),
expected_updates=dict(
description=['Test host <testhost5>'],
fqdn=[host5.fqdn],
ipasshpubkey=[sshpubkey],
has_keytab=False,
has_password=False,
krbprincipalname=['host/%s@%s' %
(host5.fqdn, api.env.realm)],
krbcanonicalname=['host/%s@%s' %
(host5.fqdn, api.env.realm)],
managedby_host=[host5.fqdn],
sshpubkeyfp=[sshpubkeyfp], ))
command = host5.make_find_command(
fqdn=host5.fqdn, pkey_only=True)
result = command()['result']
for item in result:
assert 'ipasshpubkey' not in item.keys()
def test_try_rename(self, host):
host.ensure_exists()
command = host.make_update_command(
updates=dict(setattr=u'fqdn=changed.example.com'))
with raises_exact(errors.NotAllowedOnRDN()):
command()
def test_add_mac_address(self, host):
host.update(dict(macaddress=u'00:50:56:30:F6:5F'),
expected_updates=dict(macaddress=[u'00:50:56:30:F6:5F']))
host.retrieve()
def test_add_mac_addresses(self, host):
host.update(dict(macaddress=[u'00:50:56:30:F6:5F',
u'00:50:56:2C:8D:82']))
host.retrieve()
def test_try_illegal_mac(self, host):
command = host.make_update_command(
updates=dict(macaddress=[u'xx']))
with raises_exact(errors.ValidationError(
name='macaddress',
error=u'Must be of the form HH:HH:HH:HH:HH:HH, where ' +
u'each H is a hexadecimal character.')):
command()
def test_add_ssh_pubkey(self, host):
host.update(dict(ipasshpubkey=[sshpubkey]),
expected_updates=dict(
ipasshpubkey=[sshpubkey],
sshpubkeyfp=[sshpubkeyfp],
))
host.retrieve()
def test_try_illegal_ssh_pubkey(self, host):
host.ensure_exists()
command = host.make_update_command(
updates=dict(ipasshpubkey=[u'no-pty %s' % sshpubkey]))
with raises_exact(errors.ValidationError(
name='sshpubkey', error=u'options are not allowed')):
command()
def test_update_shortname(self, host):
host.ensure_exists()
host.run_command('host_mod', host.shortname,
updatedns=True,
setattr='nshardwareplatform=linux')
def test_delete_host(self, host):
host.delete()
def test_retrieve_nonexistent(self, host):
host.ensure_missing()
command = host.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: host not found' % host.fqdn)):
command()
def test_update_nonexistent(self, host):
host.ensure_missing()
command = host.make_update_command(
updates=dict(description=u'Nope'))
with raises_exact(errors.NotFound(
reason=u'%s: host not found' % host.fqdn)):
command()
def test_delete_nonexistent(self, host):
host.ensure_missing()
command = host.make_delete_command()
with raises_exact(errors.NotFound(
reason=u'%s: host not found' % host.fqdn)):
command()
def test_try_add_not_in_dns(self, host):
host.ensure_missing()
command = host.make_create_command(force=False)
with raises_exact(errors.DNSNotARecordError(hostname=host.fqdn)):
command()
def test_add_host_with_null_password(self, host):
host.ensure_missing()
command = host.make_create_command()
result = command(userpassword=None)
host.track_create()
host.check_create(result)
@staticmethod
def modify_config_maxhostname(host_tracker, value):
try:
command = host_tracker.make_command(
'config_mod',
**dict(
setattr=u'ipamaxhostnamelength={}'.format(value)))
command()
except errors.EmptyModlist:
pass
@staticmethod
def generate_hostname(total_length, label_len=5):
"""Helper function to generate hostname given total length and
optional DNS label length
:param total_length: total length of fqdn
:param label_len: label length
:return: fqdn like string
"""
if total_length < 9:
raise ArithmeticError("Total DNS length in theses tests"
"must be at least 9")
no_of_labels = total_length // (label_len + 1)
remainder = total_length % (label_len + 1)
return '{}{}{}'.format(
(no_of_labels - 1) * '{}.'.format(label_len * 'a'),
label_len * 'b' if remainder != 0 else (label_len + 1) * 'b',
".{}".format(remainder * 'c') if remainder != 0 else "")
def test_config_maxhostname_invalid(self, host):
"""Change config maxhostname to an invalid value
(lower than MAXHOSTNAMELEN). Should fail"""
with raises_exact(errors.ValidationError(
name='ipamaxhostnamelength',
error='must be at least {}'.format(MAXHOSTNAMELEN))):
self.modify_config_maxhostname(host, MAXHOSTNAMELEN // 2)
def test_raise_hostname_limit_above_maxhostnamelen(self, host):
"""Raise config maxhostname to a value above the default
(MAXHOSTNAMELEN). Should pass"""
self.modify_config_maxhostname(host, MAXHOSTNAMELEN * 2)
def test_try_hostname_length_above_maxhostnamelimit(self):
"""Try to create host with hostname length above
hostnamelength limit. Should fail"""
testhost = HostTracker(name=u'testhost',
fqdn=u'{}'.format(
self.generate_hostname(MAXHOSTNAMELEN + 1)))
self.modify_config_maxhostname(testhost, MAXHOSTNAMELEN)
with raises_exact(errors.ValidationError(
name=u'hostname',
error=u'can be at most {} characters'.format(
MAXHOSTNAMELEN))):
testhost.create()
testhost.ensure_missing()
def test_try_hostname_length_below_maximum(self):
"""Try to create host with valid hostname. Should pass"""
valid_length = MAXHOSTNAMELEN // 2
testhost = HostTracker(name=u'testhost',
fqdn=u'{}'.format(
self.generate_hostname(valid_length)))
self.modify_config_maxhostname(testhost, MAXHOSTNAMELEN)
testhost.create()
testhost.ensure_missing()
def test_raise_limit_above_and_try_hostname_len_above_limit(self):
"""Raise limit above default and try to create host with hostname
length above the new-set limit. Should fail"""
testhost = HostTracker(name=u'testhost',
fqdn=u'{}'.format(
self.generate_hostname(MAXHOSTNAMELEN * 3)))
self.modify_config_maxhostname(testhost, MAXHOSTNAMELEN * 2)
with raises_exact(errors.ValidationError(
name='hostname',
error=u'can be at most {} characters'.format(
MAXHOSTNAMELEN * 2))):
testhost.create()
testhost.ensure_missing()
def test_raise_limit_and_try_valid_len_hostname(self):
"""Raise limit above default and test hostname with length
in between default 64 and the new value. Should pass"""
testhost = HostTracker(name=u'testhost',
fqdn=u'{}'.format(
self.generate_hostname(MAXHOSTNAMELEN + 1)))
self.modify_config_maxhostname(testhost, MAXHOSTNAMELEN * 2)
testhost.create()
testhost.ensure_missing()
@pytest.mark.tier1
class TestMultipleMatches(XMLRPC_test):
def test_try_show_multiple_matches_with_shortname(self, host, lab_host):
host.ensure_exists()
lab_host.ensure_exists()
assert host.shortname == lab_host.shortname
command = host.make_command('host_show', host.shortname)
with pytest.raises(errors.SingleMatchExpected):
command()
@pytest.mark.tier1
class TestHostWithService(XMLRPC_test):
"""Test deletion using a non-fully-qualified hostname.
Services associated with this host should also be removed.
"""
# TODO: Use a service tracker, when available
def test_host_with_service(self, host):
host.ensure_exists()
service1 = u'dns/%s@%s' % (host.fqdn, host.api.env.realm)
service1dn = DN(('krbprincipalname', service1.lower()),
('cn','services'), ('cn','accounts'),
host.api.env.basedn)
try:
result = host.run_command('service_add', service1, force=True)
assert_deepequal(dict(
value=service1,
summary=u'Added service "%s"' % service1,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
objectclass=objectclasses.service,
managedby_host=[host.fqdn],
ipauniqueid=[fuzzy_uuid],
),
), result)
host.delete()
result = host.run_command('service_find', host.fqdn)
assert_deepequal(dict(
count=0,
truncated=False,
summary=u'0 services matched',
result=[],
), result)
finally:
try:
host.run_command('service_del', service1)
except errors.NotFound:
pass
@pytest.mark.tier1
class TestManagedHosts(XMLRPC_test):
def test_managed_hosts(self, host, host2, host3):
host.ensure_exists()
host2.ensure_exists()
host3.ensure_exists()
self.add_managed_host(host, host2)
host2.retrieve()
self.search_man_noman_hosts(host2, host)
self.search_man_hosts(host2, host3)
self.remove_man_hosts(host, host2)
host.retrieve()
host2.retrieve()
def add_managed_host(self, manager, underling):
command = manager.make_command('host_add_managedby',
underling.fqdn, host=manager.fqdn)
result = command()
underling.attrs['managedby_host'] = [manager.fqdn, underling.fqdn]
assert_deepequal(dict(
completed=1,
failed={'managedby': {'host': ()}},
result=underling.filter_attrs(underling.managedby_keys),
), result)
def search_man_noman_hosts(self, host, noman_host):
command = host.make_find_command(host.fqdn,
man_host=host.fqdn,
not_man_host=noman_host.fqdn)
result = command()
assert_deepequal(dict(
count=1,
truncated=False,
summary=u'1 host matched',
result=[host.filter_attrs(host.find_keys)],
), result)
def search_man_hosts(self, host1, host2):
command = host1.make_find_command(man_host=[host1.fqdn, host2.fqdn])
result = command()
assert_deepequal(dict(
count=0,
truncated=False,
summary=u'0 hosts matched',
result=[],
), result)
def remove_man_hosts(self, manager, underling):
command = manager.make_command('host_remove_managedby',
underling.fqdn, host=manager.fqdn)
result = command()
underling.attrs['managedby_host'] = [underling.fqdn]
assert_deepequal(dict(
completed=1,
failed={'managedby': {'host': ()}},
result=underling.filter_attrs(underling.managedby_keys),
), result)
@pytest.mark.tier1
class TestProtectedMaster(XMLRPC_test):
def test_try_delete_master(self, this_host):
command = this_host.make_delete_command()
with raises_exact(errors.ValidationError(
name='hostname',
error=u'An IPA master host cannot be deleted or disabled')):
command()
def test_try_disable_master(self, this_host):
command = this_host.make_command('host_disable', this_host.fqdn)
with raises_exact(errors.ValidationError(
name='hostname',
error=u'An IPA master host cannot be deleted or disabled')):
command()
def test_try_add_auth_ind_master(self, this_host):
command = this_host.make_update_command({
u'krbprincipalauthind': u'radius'})
with raises_exact(errors.ValidationError(
name='krbprincipalauthind',
error=u'authentication indicators not allowed '
'in service "host"'
)):
command()
def test_add_non_master_with_auth_ind(self, host5):
host5.ensure_missing()
command = host5.make_command(
'host_add', host5.fqdn, krbprincipalauthind=['radius', 'passkey'],
force=True
)
result = command()
# The fact that the command succeeds exercises the change but
# let's check the indicator as well.
assert result['result']['krbprincipalauthind'] == ('radius', 'passkey')
@pytest.mark.tier1
class TestValidation(XMLRPC_test):
def test_try_validate_create(self, invalid_host):
command = invalid_host.make_create_command()
with raises_exact(errors.ValidationError(
name='hostname',
error=u"invalid domain-name: only letters, numbers, '-' are " +
u"allowed. DNS label may not start or end with '-'")):
command()
# The assumption on these next 4 tests is that if we don't get a
# validation error then the request was processed normally.
def test_try_validate_update(self, invalid_host):
command = invalid_host.make_update_command({})
with raises_exact(errors.NotFound(
reason=u'%s: host not found' % invalid_host.fqdn)):
command()
def test_try_validate_delete(self, invalid_host):
command = invalid_host.make_delete_command()
with raises_exact(errors.NotFound(
reason=u'%s: host not found' % invalid_host.fqdn)):
command()
def test_try_validate_retrieve(self, invalid_host):
command = invalid_host.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: host not found' % invalid_host.fqdn)):
command()
def test_try_validate_find(self, invalid_host):
command = invalid_host.make_find_command(invalid_host.fqdn)
result = command()
assert_deepequal(dict(
count=0,
truncated=False,
summary=u'0 hosts matched',
result=[],
), result)
@pytest.fixture
def keytabname(request):
keytabfd, keytabname = tempfile.mkstemp()
try:
os.close(keytabfd)
yield keytabname
finally:
os.unlink(keytabname)
@pytest.mark.tier1
class TestHostFalsePwdChange(XMLRPC_test):
def test_join_host(self, host, keytabname):
"""
Create a test host and join it into IPA.
This test must not run remotely.
"""
if not os.path.isfile(paths.SBIN_IPA_JOIN):
pytest.skip("Command '%s' not found. "
"The test must not run remotely."
% paths.SBIN_IPA_JOIN)
# create a test host with bulk enrollment password
host.track_create()
# manipulate host.attrs to correspond with real attributes of host
# after creating it with random password
del host.attrs['krbprincipalname']
del host.attrs['krbcanonicalname']
host.attrs['has_password'] = True
objclass = list(set(
host.attrs['objectclass']) - {u'krbprincipal', u'krbprincipalaux'})
host.attrs['objectclass'] = objclass
command = host.make_create_command(force=True)
result = command(random=True)
random_pass = result['result']['randompassword']
host.attrs['randompassword'] = random_pass
host.check_create(result)
del host.attrs['randompassword']
# joint the host with the bulk password
new_args = [
paths.SBIN_IPA_JOIN,
"-s", host.api.env.host,
"-h", host.fqdn,
"-k", keytabname,
"-w", random_pass,
"-q",
]
try:
ipautil.run(new_args)
except ipautil.CalledProcessError as e:
# join operation may fail on 'adding key into keytab', but
# the keytab is not necessary for further tests
print(e)
# fix host.attrs again to correspond with current state
host.attrs['has_keytab'] = True
host.attrs['has_password'] = False
host.attrs['krbprincipalname'] = [u'host/%s@%s' % (host.fqdn,
host.api.env.realm)]
host.attrs['krbcanonicalname'] = [u'host/%s@%s' % (host.fqdn,
host.api.env.realm)]
host.retrieve()
# Try to change the password of enrolled host with specified password
command = host.make_update_command(
updates=dict(userpassword=u'pass_123'))
with pytest.raises(errors.ValidationError):
command()
# Try to change the password of enrolled host with random password
command = host.make_update_command(updates=dict(random=True))
with pytest.raises(errors.ValidationError):
command()
@pytest.fixture(scope='class')
def dns_setup_nonameserver(host4):
# Make sure that the server does not handle the reverse zone used
# for the test
try:
host4.run_command('dnszone_del', missingrevzone, **{'continue': True})
except (errors.NotFound, errors.EmptyModlist):
pass
# Save the current forward policy
result = host4.run_command('dnsserver_show', api.env.host)
current_fwd_pol = result['result']['idnsforwardpolicy'][0]
# Configure the forward policy to none to make sure that no DNS
# server will answer for the reverse zone either
try:
host4.run_command('dnsserver_mod', api.env.host,
idnsforwardpolicy=u'none')
except errors.EmptyModlist:
pass
try:
yield
finally:
# Restore the previous forward-policy
try:
host4.run_command('dnsserver_mod', api.env.host,
idnsforwardpolicy=current_fwd_pol)
except errors.EmptyModlist:
pass
@pytest.mark.tier1
class TestHostNoNameserversForRevZone(XMLRPC_test):
def test_create_host_with_ip(self, dns_setup_nonameserver, host4):
"""
Regression test for ticket 7397
Configure the master with forward-policy = none to make sure
that no DNS server will answer for the reverse zone
Try to add a new host with an IP address in the missing reverse
zone.
With issue 7397, a NoNameserver exception generates a Traceback in
httpd error_log, and the command returns an InternalError.
"""
try:
command = host4.make_create_command()
result = command(ip_address=ipv4_in_missingrevzone_ip)
msg = result['messages'][0]
assert msg['code'] == messages.FailedToAddHostDNSRecords.errno
expected = "The host was added but the DNS update failed"
# Either one of:
# All nameservers failed to answer the query for DNS reverse zone
# DNS reverse zone ... is not managed by this server
assert expected in msg['message']
# Make sure the host is added
host4.run_command('host_show', host4.fqdn)
finally:
# Delete the host entry
command = host4.make_delete_command()
try:
command(updatedns=True)
except errors.NotFound:
pass
def test_create_host_with_otp(self, dns_setup_nonameserver, host4):
"""
Create a test host specifying an IP address for which
IPA does not handle the reverse zone, and requesting
the creation of a random password.
Non-reg test for ticket 7374.
"""
command = host4.make_create_command()
try:
result = command(random=True, ip_address=ipv4_in_missingrevzone_ip)
# Make sure a random password is returned
assert result['result']['randompassword']
# Make sure the warning about missing DNS record is added
msg = result['messages'][0]
assert msg['code'] == messages.FailedToAddHostDNSRecords.errno
assert msg['message'].startswith(
u'The host was added but the DNS update failed with:')
finally:
# Cleanup
try:
command = host4.make_delete_command()
command(updatedns=True)
except errors.NotFound:
pass
@pytest.fixture(scope='class')
def dns_setup(host):
try:
host.run_command('dnszone_del', dnszone, revzone, revipv6zone,
**{'continue': True})
except (errors.NotFound, errors.EmptyModlist):
pass
try:
host.run_command('dnszone_add', dnszone, idnssoarname=dnszone_rname)
host.run_command('dnszone_add', revzone, idnssoarname=dnszone_rname)
host.run_command('dnszone_add', revipv6zone,
idnssoarname=dnszone_rname)
yield
finally:
try:
host.run_command('dnszone_del', dnszone, revzone, revipv6zone,
**{'continue': True})
except (errors.NotFound, errors.EmptyModlist):
pass
@pytest.mark.tier1
class TestHostDNS(XMLRPC_test):
def test_add_ipv6only_host(self, dns_setup, ipv6only_host):
ipv6only_host.run_command('dnsrecord_add', dnszone,
ipv6only_host.shortname, aaaarecord=aaaarec)
try:
ipv6only_host.create(force=False)
finally:
ipv6only_host.run_command(
'dnsrecord_del', dnszone, ipv6only_host.shortname,
aaaarecord=aaaarec)
def test_add_ipv4only_host(self, dns_setup, ipv4only_host):
ipv4only_host.run_command('dnsrecord_add', dnszone,
ipv4only_host.shortname, arecord=arec)
try:
ipv4only_host.create(force=False)
finally:
ipv4only_host.run_command(
'dnsrecord_del', dnszone, ipv4only_host.shortname,
arecord=arec)
def test_add_ipv46both_host(self, dns_setup, ipv46both_host):
ipv46both_host.run_command('dnsrecord_add', dnszone,
ipv46both_host.shortname,
arecord=arec2, aaaarecord=aaaarec2)
try:
ipv46both_host.create(force=False)
finally:
ipv46both_host.run_command(
'dnsrecord_del', dnszone, ipv46both_host.shortname,
arecord=arec2, aaaarecord=aaaarec2)
def test_add_ipv4_host_from_ip(self, dns_setup, ipv4_fromip_host):
ipv4_fromip_host.ensure_missing()
ipv4_fromip_host.track_create()
command = ipv4_fromip_host.make_create_command(force=False)
result = command(ip_address=ipv4_fromip_ip)
ipv4_fromip_host.check_create(result)
result = ipv4_fromip_host.run_command('dnsrecord_show', dnszone,
ipv4_fromip_host.shortname)
assert_deepequal(dict(
value=ipv4_fromip_dnsname,
summary=None,
result=dict(
dn=ipv4_fromip_dn,
idnsname=[ipv4_fromip_dnsname],
arecord=[ipv4_fromip_arec],
),
), result)
result = ipv4_fromip_host.run_command('dnsrecord_show', revzone,
ipv4_fromip_ptr)
assert_deepequal(dict(
value=ipv4_fromip_ptr_dnsname,
summary=None,
result=dict(
dn=ipv4_fromip_ptr_dn,
idnsname=[ipv4_fromip_ptr_dnsname],
ptrrecord=[ipv4_fromip_host.fqdn + '.'],
),
), result)
def test_add_ipv6_host_from_ip(self, dns_setup, ipv6_fromip_host):
ipv6_fromip_host.ensure_missing()
ipv6_fromip_host.track_create()
command = ipv6_fromip_host.make_create_command(force=False)
result = command(ip_address=ipv6_fromip_ipv6)
ipv6_fromip_host.check_create(result)
result = ipv6_fromip_host.run_command('dnsrecord_show', dnszone,
ipv6_fromip_host.shortname)
assert_deepequal(dict(
value=ipv6_fromip_dnsname,
summary=None,
result=dict(
dn=ipv6_fromip_dn,
idnsname=[ipv6_fromip_dnsname],
aaaarecord=[ipv6_fromip_aaaarec],
),
), result)
result = ipv6_fromip_host.run_command('dnsrecord_show', revipv6zone,
ipv6_fromip_ptr)
assert_deepequal(dict(
value=ipv6_fromip_ptr_dnsname,
summary=None,
result=dict(
dn=ipv6_fromip_ptr_dn,
idnsname=[ipv6_fromip_ptr_dnsname],
ptrrecord=[ipv6_fromip_host.fqdn + '.'],
),
), result)
@pytest.fixture(scope='class')
def allowedto_context(request, host3):
def cleanup():
try:
host3.run_command('user_del', user1, user2, **{'continue': True})
except errors.NotFound:
pass
try:
host3.run_command('group_del', group1, group2,
**{'continue': True})
except errors.NotFound:
pass
try:
host3.run_command('hostgroup_del', hostgroup1)
except errors.NotFound:
pass
cleanup()
request.addfinalizer(cleanup)
host3.ensure_exists()
host3.run_command('user_add', givenname=u'Test', sn=u'User1')
host3.run_command('user_add', givenname=u'Test', sn=u'User2')
host3.run_command('group_add', group1)
host3.run_command('group_add', group2)
host3.run_command('hostgroup_add', hostgroup1,
description=u'Test hostgroup 1')
@pytest.mark.tier1
class TestHostAllowedTo(XMLRPC_test):
def test_user_allow_retrieve_keytab(self, allowedto_context, host):
host.ensure_exists()
result = host.run_command('host_allow_retrieve_keytab', host.fqdn,
user=user1)
host.attrs['ipaallowedtoperform_read_keys_user'] = [user1]
assert_deepequal(dict(
failed=dict(
ipaallowedtoperform_read_keys=dict(
group=[], host=[], hostgroup=[], user=[]),
),
completed=1,
result=host.filter_attrs(host.allowedto_keys),
), result)
# Duplicates should not be accepted
result = host.run_command('host_allow_retrieve_keytab', host.fqdn,
user=user1)
assert_deepequal(dict(
failed=dict(
ipaallowedtoperform_read_keys=dict(
group=[], host=[], hostgroup=[],
user=[[user1, u'This entry is already a member']],
),
),
completed=0,
result=host.filter_attrs(host.allowedto_keys),
), result)
def test_group_allow_retrieve_keytab(self, allowedto_context, host, host3):
host.ensure_exists()
host3.ensure_exists()
result = host.run_command('host_allow_retrieve_keytab', host.fqdn,
group=[group1, group2], host=[host3.fqdn],
hostgroup=[hostgroup1])
host.attrs['ipaallowedtoperform_read_keys_group'] = [group1, group2]
host.attrs['ipaallowedtoperform_read_keys_host'] = [host3.fqdn]
host.attrs['ipaallowedtoperform_read_keys_hostgroup'] = [hostgroup1]
assert_deepequal(dict(
failed=dict(
ipaallowedtoperform_read_keys=dict(
group=[], host=[], hostgroup=[], user=[]),
),
completed=4,
result=host.filter_attrs(host.allowedto_keys),
), result)
# Non-members cannot be removed
result = host.run_command('host_disallow_retrieve_keytab', host.fqdn,
user=[user2])
assert_deepequal(dict(
failed=dict(
ipaallowedtoperform_read_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[[user2, u'This entry is not a member']],
),
),
completed=0,
result=host.filter_attrs(host.allowedto_keys),
), result)
# Disallow one of the existing allowed groups
result = host.run_command('host_disallow_retrieve_keytab', host.fqdn,
group=[group2])
host.attrs['ipaallowedtoperform_read_keys_group'] = [group1]
assert_deepequal(dict(
failed=dict(
ipaallowedtoperform_read_keys=dict(
group=[], host=[], hostgroup=[], user=[]),
),
completed=1,
result=host.filter_attrs(host.allowedto_keys),
), result)
host.retrieve()
def test_allow_create(self, allowedto_context, host, host3):
host.ensure_exists()
host3.ensure_exists()
result = host.run_command('host_allow_create_keytab', host.fqdn,
group=[group1, group2], user=[user1],
host=[host3.fqdn],
hostgroup=[hostgroup1])
host.attrs['ipaallowedtoperform_write_keys_user'] = [user1]
host.attrs['ipaallowedtoperform_write_keys_group'] = [group1, group2]
host.attrs['ipaallowedtoperform_write_keys_host'] = [host3.fqdn]
host.attrs['ipaallowedtoperform_write_keys_hostgroup'] = [hostgroup1]
assert_deepequal(dict(
failed=dict(
ipaallowedtoperform_write_keys=dict(
group=[], host=[], hostgroup=[], user=[]),
),
completed=5,
result=host.filter_attrs(host.allowedto_keys),
), result)
# Duplicates should not be accepted
result = host.run_command('host_allow_create_keytab', host.fqdn,
group=[group1], user=[user1],
host=[host3.fqdn], hostgroup=[hostgroup1])
assert_deepequal(dict(
failed=dict(
ipaallowedtoperform_write_keys=dict(
group=[[group1, u'This entry is already a member']],
host=[[host3.fqdn, u'This entry is already a member']],
user=[[user1, u'This entry is already a member']],
hostgroup=[[hostgroup1,
u'This entry is already a member']],
),
),
completed=0,
result=host.filter_attrs(host.allowedto_keys),
), result)
# Non-mambers cannot be removed
result = host.run_command('host_disallow_create_keytab', host.fqdn,
user=[user2])
assert_deepequal(dict(
failed=dict(
ipaallowedtoperform_write_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[[user2, u'This entry is not a member']],
),
),
completed=0,
result=host.filter_attrs(host.allowedto_keys),
), result)
# Disallow one of the existing allowed groups
result = host.run_command('host_disallow_create_keytab', host.fqdn,
group=[group2])
host.attrs['ipaallowedtoperform_write_keys_group'] = [group1]
assert_deepequal(dict(
failed=dict(
ipaallowedtoperform_write_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[],
),
),
completed=1,
result=host.filter_attrs(host.allowedto_keys),
), result)
host.retrieve()
def test_host_mod(self, host):
# Done (usually) at the end to ensure the tracking works well
host.update(updates=dict(description=u'desc'),
expected_updates=dict(description=[u'desc']))
| 43,265
|
Python
|
.py
| 985
| 32.705584
| 411
| 0.59896
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,438
|
test_vault_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_vault_plugin.py
|
# Authors:
# Endi S. Dewata <edewata@redhat.com>
#
# Copyright (C) 2015 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/plugins/vault.py` module.
"""
import pytest
import six
from ipalib import api
from ipatests.test_xmlrpc.xmlrpc_test import Declarative, fuzzy_bytes
vault_name = u'test_vault'
service_name = u'HTTP/server.example.com'
user_name = u'testuser'
standard_vault_name = u'standard_test_vault'
symmetric_vault_name = u'symmetric_test_vault'
asymmetric_vault_name = u'asymmetric_test_vault'
# binary data from \x00 to \xff
if six.PY2:
secret = b''.join(chr(c) for c in range(0, 256))
else:
secret = bytes(range(0, 256))
password = u'password'
other_password = u'other_password'
public_key = b"""
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnT61EFxUOQgCJdM0tmw/
pRRPDPGchTClnU1eBtiQD3ItKYf1+weMGwGOSJXPtkto7NlE7Qs8WHAr0UjyeBDe
k/zeB6nSVdk47OdaW1AHrJL+44r238Jbm/+7VO5lTu6Z4N5p0VqoWNLi0Uh/CkqB
tsxXaaAgjMp0AGq2U/aO/akeEYWQOYIdqUKVgAEKX5MmIA8tmbmoYIQ+B4Q3vX7N
otG4eR6c2o9Fyjd+M4Gai5Ce0fSrigRvxAYi8xpRkQ5yQn5gf4WVrn+UKTfOIjLO
pVThop+Xivcre3SpI0kt6oZPhBw9i8gbMnqifVmGFpVdhq+QVBqp+MVJvTbhRPG6
3wIDAQAB
-----END PUBLIC KEY-----
"""
private_key = b"""
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAnT61EFxUOQgCJdM0tmw/pRRPDPGchTClnU1eBtiQD3ItKYf1
+weMGwGOSJXPtkto7NlE7Qs8WHAr0UjyeBDek/zeB6nSVdk47OdaW1AHrJL+44r2
38Jbm/+7VO5lTu6Z4N5p0VqoWNLi0Uh/CkqBtsxXaaAgjMp0AGq2U/aO/akeEYWQ
OYIdqUKVgAEKX5MmIA8tmbmoYIQ+B4Q3vX7NotG4eR6c2o9Fyjd+M4Gai5Ce0fSr
igRvxAYi8xpRkQ5yQn5gf4WVrn+UKTfOIjLOpVThop+Xivcre3SpI0kt6oZPhBw9
i8gbMnqifVmGFpVdhq+QVBqp+MVJvTbhRPG63wIDAQABAoIBAQCD2bXnfxPcMnvi
jaPwpvoDCPF0EBBHmk/0g5ApO2Qon3uBDJFUqbJwXrCY6o2d9MOJfnGONlKmcYA8
X+d4h+SqwGjIkjxdYeSauS+Jy6Rzr1ptH/P8EjPQrfG9uJxYQDflV3nxYwwwVrx7
8kccMPdteRB+8Bb7FzOHufMimmayCNFETnVT5CKH2PrYoPB+fr0itCipWOenDp33
e73OV+K9U3rclmtHaoRxGohqByKfQRUkipjw4m+T3qfZZc5eN77RGW8J+oL1GVom
fwtiH7N1HVte0Dmd13nhiASg355kjqRPcIMPsRHvXkOpgg5HRUTKG5elqAyvvm27
Fzj1YdeRAoGBAMnE61+FYh8qCyEGe8r6RGjO8iuoyk1t+0gBWbmILLBiRnj4K8Tc
k7HBG/pg3XCNbCuRwiLg8tk3VAAXzn6o+IJr3QnKbNCGa1lKfYU4mt11sBEyuL5V
NpZcZ8IiPhMlGyDA9cFbTMKOE08RqbOIdxOmTizFt0R5sYZAwOjEvBIZAoGBAMeC
N/P0bdrScFZGeS51wEdiWme/CO0IyGoqU6saI8L0dbmMJquiaAeIEjIKLqxH1RON
axhsyk97e0PCcc5QK62Utf50UUAbL/v7CpIG+qdSRYDO4bVHSCkwF32N3pYh/iVU
EsEBEkZiJi0dWa/0asDbsACutxcHda3RI5pi7oO3AoGAcbGNs/CUHt1xEfX2UaT+
YVSjb2iYPlNH8gYYygvqqqVl8opdF3v3mYUoP8jPXrnCBzcF/uNk1HNx2O+RQxvx
lIQ1NGwlLsdfvBvWaPhBg6LqSHadVVrs/IMrUGA9PEp/Y9B3arIIqeSnCrn4Nxsh
higDCwWKRIKSPwVD7qXVGBkCgYEAu5/CASIRIeYgEXMLSd8hKcDcJo8o1MoauIT/
1Hyrvw9pm0qrn2QHk3WrLvYWeJzBTTcEzZ6aEG+fN9UodA8/VGnzUc6QDsrCsKWh
hj0cArlDdeSZrYLQ4TNCFCiUePqU6QQM8weP6TMqlejxTKF+t8qi1bF5rCWuzP1P
D0UU7DcCgYAUvmEGckugS+FTatop8S/rmkcQ4Bf5M/YCZfsySavucDiHcBt0QtXt
Swh0XdDsYS3W1yj2XqqsQ7R58KNaffCHjjulWFzb5IiuSvvdxzWtiXHisOpO36MJ
kUlCMj24a8XsShzYTWBIyW2ngvGe3pQ9PfjkUdm0LGZjYITCBvgOKw==
-----END RSA PRIVATE KEY-----
"""
other_public_key = b"""
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAv7E/QLVyKjrgDctZ50U7
rmtL7Ks1QLoccp9WvZJ6WI1rYd0fX5FySS4dI6QTNZc6qww8NeNuZtkoxT9m1wkk
Rl/3wK7fWNLenH/+VHOaTQc20exg7ztfsO7JIsmKmigtticdR5C4jLfjcOp+WjLH
w3zrmrO5SIZ8njxMoDcQJa2vu/t281U/I7ti8ue09FSitIECU05vgmPS+MnXR8HK
PxXqrNkjl29mXNbPiByWwlse3Prwved9I7fwgpiHJqUBFudD/0tZ4DWyLG7t9wM1
O8gRaRg1r+ENVpmMSvXo4+8+bR3rEYddD5zU7nKXafeuthXlXplae/8uZmCiSI63
TwIDAQAB
-----END PUBLIC KEY-----
"""
other_private_key = b"""
-----BEGIN RSA PRIVATE KEY-----
MIIEpgIBAAKCAQEAv7E/QLVyKjrgDctZ50U7rmtL7Ks1QLoccp9WvZJ6WI1rYd0f
X5FySS4dI6QTNZc6qww8NeNuZtkoxT9m1wkkRl/3wK7fWNLenH/+VHOaTQc20exg
7ztfsO7JIsmKmigtticdR5C4jLfjcOp+WjLHw3zrmrO5SIZ8njxMoDcQJa2vu/t2
81U/I7ti8ue09FSitIECU05vgmPS+MnXR8HKPxXqrNkjl29mXNbPiByWwlse3Prw
ved9I7fwgpiHJqUBFudD/0tZ4DWyLG7t9wM1O8gRaRg1r+ENVpmMSvXo4+8+bR3r
EYddD5zU7nKXafeuthXlXplae/8uZmCiSI63TwIDAQABAoIBAQCA+0GFR9F+isjx
Xy+qBpKmxLl8kKKvX8r+cSpLOkEqTlW/rqqKgnI0vVuL/L2UJKKsLvpghBxoBZyC
RCvtatBGrhIlS0UrHg/9m73Ek1hylfUUAQokTn4PrkwWJSgmm/xOATmZSs5ymNTn
yFCmXl69sdNR77YvD5bQXeBtOT+bKXy7yQ1TmYPwwSjL+WSlMV6ZfE3HNVmxPTpk
CTFS638cJblWk9MUIy8HIlhu6If2P4RnHr7ZGGivhREayvs0zXcAfqhIyFHruxSE
yYnmqH9paWjv5mP3YyLoKr+NUvvxnBr/9wCTt0TKgG8G6rpkHuPDLQni9wUGnew8
QdMgFEohAoGBAPH4vaVB5gDVfvIqwJBsBLHpPq72GvxjrM/exD0jIIpXZxz9gCql
CmC5b1RS1uy8PMoc/RO4CE7UTLaTesciP6LjTD1RhH3rLLJO8/iVC1RXgMrCLHLm
ZQnDhIQGGNQxpvBjQy5ZOWat2dFxYhHN630IFPOtrWsOmJ5HsL1JrjzxAoGBAMrO
R1zNwQ42VbJS6AFshZVjmUV2h3REGh4zG/9IqL0Hz493hyCTGoDPLLXIbtkqNqzQ
XibSZ9RMVPKKTiNQTx91DTgh4Anz8xUr84tA2iAf3ayNWKi3Y3GhmP2EWp1qYeom
kV8Uq0lt4dHZuEo3LuqvbtbzlF9qUXqKS5qy6Tg/AoGBAKCp02o2HjzxhS/QeTmr
r1ZeE7PiTzrECAuh01TwzPtuW1XhcEdgfEqK9cPcmT5pIkflBZkhOcr1pdYYiI5O
TEigeY/BX6KoE251hALLG9GtpCN82DyWhAH+oy9ySOwj5793eTT+I2HtD1LE4SQH
QVQsmJTP/fS2pVl7KnwUvy9RAoGBAKzo2qchNewsHzx+uxgbsnkABfnXaP2T4sDE
yqYJCPTB6BFl02vOf9Y6zN/gF8JH333P2bY3xhaXTgXMLXqmSg+D+NVW7HEP8Lyo
UGj1zgN9p74qdODEGqETKiFb6vYzcW/1mhP6x18/tDz658k+611kXZge7O288+MK
bhNjXrx5AoGBAMox25PcxVgOjCd9+LdUcIOG6LQ971eCH1NKL9YAekICnwMrStbK
veCYju6ok4ZWnMiH8MR1jgC39RWtjJZwynCuPXUP2/vZkoVf1tCZyz7dSm8TdS/2
5NdOHVy7+NQcEPSm7/FmXdpcR9ZSGAuxMBfnEUibdyz5LdJGnFUN/+HS
-----END RSA PRIVATE KEY-----
"""
@pytest.mark.tier1
class test_vault_plugin(Declarative):
@pytest.fixture(autouse=True, scope="class")
def vault_plugin_setup(self, declarative_setup):
if not api.Backend.rpcclient.isconnected():
api.Backend.rpcclient.connect()
if not api.Command.kra_is_enabled()['result']:
pytest.skip('KRA service is not enabled')
cleanup_commands = [
('vault_del', [vault_name], {'continue': True}),
('vault_del', [vault_name], {
'service': service_name,
'continue': True
}),
('vault_del', [vault_name], {'shared': True, 'continue': True}),
('vault_del', [vault_name], {'username': user_name, 'continue': True}),
('vault_del', [standard_vault_name], {'continue': True}),
('vault_del', [symmetric_vault_name], {'continue': True}),
('vault_del', [asymmetric_vault_name], {'continue': True}),
]
tests = [
{
'desc': 'Create private vault',
'command': (
'vault_add',
[vault_name],
{
'ipavaulttype': u'standard',
},
),
'expected': {
'value': vault_name,
'summary': 'Added vault "%s"' % vault_name,
'result': {
'dn': u'cn=%s,cn=admin,cn=users,cn=vaults,cn=kra,%s'
% (vault_name, api.env.basedn),
'objectclass': [u'top', u'ipaVault'],
'cn': [vault_name],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'username': u'admin',
},
},
},
{
'desc': 'Find private vaults',
'command': (
'vault_find',
[],
{},
),
'expected': {
'count': 1,
'truncated': False,
'summary': u'1 vault matched',
'result': [
{
'dn': u'cn=%s,cn=admin,cn=users,cn=vaults,cn=kra,%s'
% (vault_name, api.env.basedn),
'cn': [vault_name],
'ipavaulttype': [u'standard'],
'username': u'admin',
},
],
},
},
{
'desc': 'Show private vault',
'command': (
'vault_show',
[vault_name],
{},
),
'expected': {
'value': vault_name,
'summary': None,
'result': {
'dn': u'cn=%s,cn=admin,cn=users,cn=vaults,cn=kra,%s'
% (vault_name, api.env.basedn),
'cn': [vault_name],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'username': u'admin',
},
},
},
{
'desc': 'Modify private vault',
'command': (
'vault_mod',
[vault_name],
{
'description': u'Test vault',
},
),
'expected': {
'value': vault_name,
'summary': u'Modified vault "%s"' % vault_name,
'result': {
'cn': [vault_name],
'description': [u'Test vault'],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'username': u'admin',
},
},
},
{
'desc': 'Delete private vault',
'command': (
'vault_del',
[vault_name],
{},
),
'expected': {
'value': [vault_name],
'summary': u'Deleted vault "%s"' % vault_name,
'result': {
'failed': (),
},
},
},
{
'desc': 'Create service vault',
'command': (
'vault_add',
[vault_name],
{
'ipavaulttype': u'standard',
'service': service_name,
},
),
'expected': {
'value': vault_name,
'summary': u'Added vault "%s"' % vault_name,
'result': {
'dn': u'cn=%s,cn=%s@%s,cn=services,cn=vaults,cn=kra,%s'
% (vault_name, service_name, api.env.realm,
api.env.basedn),
'objectclass': [u'top', u'ipaVault'],
'cn': [vault_name],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'service': "%s@%s" % (service_name, api.env.realm),
},
},
},
{
'desc': 'Find service vaults',
'command': (
'vault_find',
[],
{
'service': service_name,
},
),
'expected': {
'count': 1,
'truncated': False,
'summary': u'1 vault matched',
'result': [
{
'dn': u'cn=%s,cn=%s@%s,cn=services,cn=vaults,cn=kra,%s'
% (vault_name, service_name, api.env.realm,
api.env.basedn),
'cn': [vault_name],
'ipavaulttype': [u'standard'],
'service': '%s@%s' % (service_name, api.env.realm),
},
],
},
},
{
'desc': 'Show service vault',
'command': (
'vault_show',
[vault_name],
{
'service': service_name,
},
),
'expected': {
'value': vault_name,
'summary': None,
'result': {
'dn': u'cn=%s,cn=%s@%s,cn=services,cn=vaults,cn=kra,%s'
% (vault_name, service_name, api.env.realm,
api.env.basedn),
'cn': [vault_name],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'service': "%s@%s" % (service_name, api.env.realm),
},
},
},
{
'desc': 'Modify service vault',
'command': (
'vault_mod',
[vault_name],
{
'service': service_name,
'description': u'Test vault',
},
),
'expected': {
'value': vault_name,
'summary': u'Modified vault "%s"' % vault_name,
'result': {
'cn': [vault_name],
'description': [u'Test vault'],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'service': "%s@%s" % (service_name, api.env.realm),
},
},
},
{
'desc': 'Delete service vault',
'command': (
'vault_del',
[vault_name],
{
'service': service_name,
},
),
'expected': {
'value': [vault_name],
'summary': u'Deleted vault "%s"' % vault_name,
'result': {
'failed': (),
},
},
},
{
'desc': 'Create shared vault',
'command': (
'vault_add',
[vault_name],
{
'ipavaulttype': u'standard',
'shared': True
},
),
'expected': {
'value': vault_name,
'summary': u'Added vault "%s"' % vault_name,
'result': {
'dn': u'cn=%s,cn=shared,cn=vaults,cn=kra,%s'
% (vault_name, api.env.basedn),
'objectclass': [u'top', u'ipaVault'],
'cn': [vault_name],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'shared': True,
},
},
},
{
'desc': 'Find shared vaults',
'command': (
'vault_find',
[],
{
'shared': True
},
),
'expected': {
'count': 1,
'truncated': False,
'summary': u'1 vault matched',
'result': [
{
'dn': u'cn=%s,cn=shared,cn=vaults,cn=kra,%s'
% (vault_name, api.env.basedn),
'cn': [vault_name],
'ipavaulttype': [u'standard'],
'shared': True,
},
],
},
},
{
'desc': 'Show shared vault',
'command': (
'vault_show',
[vault_name],
{
'shared': True
},
),
'expected': {
'value': vault_name,
'summary': None,
'result': {
'dn': u'cn=%s,cn=shared,cn=vaults,cn=kra,%s'
% (vault_name, api.env.basedn),
'cn': [vault_name],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'shared': True,
},
},
},
{
'desc': 'Modify shared vault',
'command': (
'vault_mod',
[vault_name],
{
'shared': True,
'description': u'Test vault',
},
),
'expected': {
'value': vault_name,
'summary': u'Modified vault "%s"' % vault_name,
'result': {
'cn': [vault_name],
'description': [u'Test vault'],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'shared': True,
},
},
},
{
'desc': 'Delete shared vault',
'command': (
'vault_del',
[vault_name],
{
'shared': True
},
),
'expected': {
'value': [vault_name],
'summary': u'Deleted vault "%s"' % vault_name,
'result': {
'failed': (),
},
},
},
{
'desc': 'Create user vault',
'command': (
'vault_add',
[vault_name],
{
'ipavaulttype': u'standard',
'username': user_name,
},
),
'expected': {
'value': vault_name,
'summary': u'Added vault "%s"' % vault_name,
'result': {
'dn': u'cn=%s,cn=%s,cn=users,cn=vaults,cn=kra,%s'
% (vault_name, user_name, api.env.basedn),
'objectclass': [u'top', u'ipaVault'],
'cn': [vault_name],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'username': user_name,
},
},
},
{
'desc': 'Find user vaults',
'command': (
'vault_find',
[],
{
'username': user_name,
},
),
'expected': {
'count': 1,
'truncated': False,
'summary': u'1 vault matched',
'result': [
{
'dn': u'cn=%s,cn=%s,cn=users,cn=vaults,cn=kra,%s'
% (vault_name, user_name, api.env.basedn),
'cn': [vault_name],
'ipavaulttype': [u'standard'],
'username': user_name,
},
],
},
},
{
'desc': 'Show user vault',
'command': (
'vault_show',
[vault_name],
{
'username': user_name,
},
),
'expected': {
'value': vault_name,
'summary': None,
'result': {
'dn': u'cn=%s,cn=%s,cn=users,cn=vaults,cn=kra,%s'
% (vault_name, user_name, api.env.basedn),
'cn': [vault_name],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'username': user_name,
},
},
},
{
'desc': 'Modify user vault',
'command': (
'vault_mod',
[vault_name],
{
'username': user_name,
'description': u'Test vault',
},
),
'expected': {
'value': vault_name,
'summary': u'Modified vault "%s"' % vault_name,
'result': {
'cn': [vault_name],
'description': [u'Test vault'],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'username': user_name,
},
},
},
{
'desc': 'Delete user vault',
'command': (
'vault_del',
[vault_name],
{
'username': user_name,
},
),
'expected': {
'value': [vault_name],
'summary': u'Deleted vault "%s"' % vault_name,
'result': {
'failed': (),
},
},
},
{
'desc': 'Create standard vault',
'command': (
'vault_add',
[standard_vault_name],
{
'ipavaulttype': u'standard',
},
),
'expected': {
'value': standard_vault_name,
'summary': 'Added vault "%s"' % standard_vault_name,
'result': {
'dn': u'cn=%s,cn=admin,cn=users,cn=vaults,cn=kra,%s'
% (standard_vault_name, api.env.basedn),
'objectclass': [u'top', u'ipaVault'],
'cn': [standard_vault_name],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'username': u'admin',
},
},
},
{
'desc': 'Archive secret into standard vault',
'command': (
'vault_archive',
[standard_vault_name],
{
'data': secret,
},
),
'expected': {
'value': standard_vault_name,
'summary': 'Archived data into vault "%s"'
% standard_vault_name,
'result': {},
},
},
{
'desc': 'Retrieve secret from standard vault',
'command': (
'vault_retrieve',
[standard_vault_name],
{},
),
'expected': {
'value': standard_vault_name,
'summary': 'Retrieved data from vault "%s"'
% standard_vault_name,
'result': {
'data': secret,
},
},
},
{
'desc': 'Change standard vault to symmetric vault',
'command': (
'vault_mod',
[standard_vault_name],
{
'ipavaulttype': u'symmetric',
'new_password': password,
},
),
'expected': {
'value': standard_vault_name,
'summary': u'Modified vault "%s"' % standard_vault_name,
'result': {
'cn': [standard_vault_name],
'ipavaulttype': [u'symmetric'],
'ipavaultsalt': [fuzzy_bytes],
'owner_user': [u'admin'],
'username': u'admin',
},
},
},
{
'desc': 'Retrieve secret from standard vault converted to '
'symmetric vault',
'command': (
'vault_retrieve',
[standard_vault_name],
{
'password': password,
},
),
'expected': {
'value': standard_vault_name,
'summary': 'Retrieved data from vault "%s"'
% standard_vault_name,
'result': {
'data': secret,
},
},
},
{
'desc': 'Create symmetric vault',
'command': (
'vault_add',
[symmetric_vault_name],
{
'ipavaulttype': u'symmetric',
'password': password,
},
),
'expected': {
'value': symmetric_vault_name,
'summary': 'Added vault "%s"' % symmetric_vault_name,
'result': {
'dn': u'cn=%s,cn=admin,cn=users,cn=vaults,cn=kra,%s'
% (symmetric_vault_name, api.env.basedn),
'objectclass': [u'top', u'ipaVault'],
'cn': [symmetric_vault_name],
'ipavaulttype': [u'symmetric'],
'ipavaultsalt': [fuzzy_bytes],
'owner_user': [u'admin'],
'username': u'admin',
},
},
},
{
'desc': 'Archive secret into symmetric vault',
'command': (
'vault_archive',
[symmetric_vault_name],
{
'password': password,
'data': secret,
},
),
'expected': {
'value': symmetric_vault_name,
'summary': 'Archived data into vault "%s"'
% symmetric_vault_name,
'result': {},
},
},
{
'desc': 'Retrieve secret from symmetric vault',
'command': (
'vault_retrieve',
[symmetric_vault_name],
{
'password': password,
},
),
'expected': {
'value': symmetric_vault_name,
'summary': 'Retrieved data from vault "%s"'
% symmetric_vault_name,
'result': {
'data': secret,
},
},
},
{
'desc': 'Change symmetric vault password',
'command': (
'vault_mod',
[symmetric_vault_name],
{
'old_password': password,
'new_password': other_password,
},
),
'expected': {
'value': symmetric_vault_name,
'summary': u'Modified vault "%s"' % symmetric_vault_name,
'result': {
'cn': [symmetric_vault_name],
'ipavaulttype': [u'symmetric'],
'ipavaultsalt': [fuzzy_bytes],
'owner_user': [u'admin'],
'username': u'admin',
},
},
},
{
'desc': 'Retrieve secret from symmetric vault with new password',
'command': (
'vault_retrieve',
[symmetric_vault_name],
{
'password': other_password,
},
),
'expected': {
'value': symmetric_vault_name,
'summary': 'Retrieved data from vault "%s"'
% symmetric_vault_name,
'result': {
'data': secret,
},
},
},
{
'desc': 'Change symmetric vault to asymmetric vault',
'command': (
'vault_mod',
[symmetric_vault_name],
{
'ipavaulttype': u'asymmetric',
'old_password': other_password,
'ipavaultpublickey': public_key,
},
),
'expected': {
'value': symmetric_vault_name,
'summary': u'Modified vault "%s"' % symmetric_vault_name,
'result': {
'cn': [symmetric_vault_name],
'ipavaulttype': [u'asymmetric'],
'ipavaultpublickey': [public_key],
'owner_user': [u'admin'],
'username': u'admin',
},
},
},
{
'desc': 'Retrieve secret from symmetric vault converted to '
'asymmetric vault',
'command': (
'vault_retrieve',
[symmetric_vault_name],
{
'private_key': private_key,
},
),
'expected': {
'value': symmetric_vault_name,
'summary': 'Retrieved data from vault "%s"'
% symmetric_vault_name,
'result': {
'data': secret,
},
},
},
{
'desc': 'Create asymmetric vault',
'command': (
'vault_add',
[asymmetric_vault_name],
{
'ipavaulttype': u'asymmetric',
'ipavaultpublickey': public_key,
},
),
'expected': {
'value': asymmetric_vault_name,
'summary': 'Added vault "%s"' % asymmetric_vault_name,
'result': {
'dn': u'cn=%s,cn=admin,cn=users,cn=vaults,cn=kra,%s'
% (asymmetric_vault_name, api.env.basedn),
'objectclass': [u'top', u'ipaVault'],
'cn': [asymmetric_vault_name],
'ipavaulttype': [u'asymmetric'],
'ipavaultpublickey': [public_key],
'owner_user': [u'admin'],
'username': u'admin',
},
},
},
{
'desc': 'Archive secret into asymmetric vault',
'command': (
'vault_archive',
[asymmetric_vault_name],
{
'data': secret,
},
),
'expected': {
'value': asymmetric_vault_name,
'summary': 'Archived data into vault "%s"'
% asymmetric_vault_name,
'result': {},
},
},
{
'desc': 'Retrieve secret from asymmetric vault',
'command': (
'vault_retrieve',
[asymmetric_vault_name],
{
'private_key': private_key,
},
),
'expected': {
'value': asymmetric_vault_name,
'summary': 'Retrieved data from vault "%s"'
% asymmetric_vault_name,
'result': {
'data': secret,
},
},
},
{
'desc': 'Change asymmetric vault keys',
'command': (
'vault_mod',
[asymmetric_vault_name],
{
'private_key': private_key,
'ipavaultpublickey': other_public_key,
},
),
'expected': {
'value': asymmetric_vault_name,
'summary': u'Modified vault "%s"' % asymmetric_vault_name,
'result': {
'cn': [asymmetric_vault_name],
'ipavaulttype': [u'asymmetric'],
'ipavaultpublickey': [other_public_key],
'owner_user': [u'admin'],
'username': u'admin',
},
},
},
{
'desc': 'Retrieve secret from asymmetric vault with new keys',
'command': (
'vault_retrieve',
[asymmetric_vault_name],
{
'private_key': other_private_key,
},
),
'expected': {
'value': asymmetric_vault_name,
'summary': 'Retrieved data from vault "%s"'
% asymmetric_vault_name,
'result': {
'data': secret,
},
},
},
{
'desc': 'Change asymmetric vault to standard vault',
'command': (
'vault_mod',
[asymmetric_vault_name],
{
'ipavaulttype': u'standard',
'private_key': other_private_key,
},
),
'expected': {
'value': asymmetric_vault_name,
'summary': u'Modified vault "%s"' % asymmetric_vault_name,
'result': {
'cn': [asymmetric_vault_name],
'ipavaulttype': [u'standard'],
'owner_user': [u'admin'],
'username': u'admin',
},
},
},
{
'desc': 'Retrieve secret from asymmetric vault converted to '
'standard vault',
'command': (
'vault_retrieve',
[asymmetric_vault_name],
{},
),
'expected': {
'value': asymmetric_vault_name,
'summary': 'Retrieved data from vault "%s"'
% asymmetric_vault_name,
'result': {
'data': secret,
},
},
},
]
| 33,477
|
Python
|
.py
| 946
| 20.765328
| 79
| 0.4418
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,439
|
test_idp_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_idp_plugin.py
|
#
# Copyright (C) 2021 FreeIPA Contributors see COPYING for license
#
"""
Test the `ipaserver.plugins.idp` module.
"""
import pytest
from ipalib import errors
from ipatests.test_xmlrpc.xmlrpc_test import (
XMLRPC_test, raises_exact)
from ipatests.test_xmlrpc.tracker.idp_plugin import IdpTracker
google_auth = "https://accounts.google.com/o/oauth2/auth"
google_devauth = "https://oauth2.googleapis.com/device/code"
google_token = "https://oauth2.googleapis.com/token"
google_userinfo = "https://openidconnect.googleapis.com/v1/userinfo"
google_jwks = "https://www.googleapis.com/oauth2/v3/certs"
idp_scope = "openid email"
idp_sub = "email"
@pytest.fixture(scope='class')
def idp(request, xmlrpc_setup):
tracker = IdpTracker('idp1', ipaidpauthendpoint=google_auth,
ipaidpdevauthendpoint=google_devauth,
ipaidptokenendpoint=google_token,
ipaidpuserinfoendpoint=google_userinfo,
ipaidpkeysendpoint=google_jwks,
ipaidpclientid="idp1client",
ipaidpclientsecret="Secret123",
ipaidpscope=idp_scope)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def renamedidp(request, xmlrpc_setup):
tracker = IdpTracker('idp2', ipaidpauthendpoint=google_auth,
ipaidpdevauthendpoint=google_devauth,
ipaidptokenendpoint=google_token,
ipaidpuserinfoendpoint=google_userinfo,
ipaidpkeysendpoint=google_jwks,
ipaidpclientid="idp1client",
ipaidpclientsecret="Secret123",
ipaidpscope=idp_scope)
return tracker.make_fixture(request)
class TestNonexistentIdp(XMLRPC_test):
def test_retrieve_nonexistent(self, idp):
""" Try to retrieve a non-existent idp """
idp.ensure_missing()
command = idp.make_retrieve_command()
with raises_exact(errors.NotFound(
reason='%s: Identity Provider reference not found' % idp.cn)):
command()
def test_update_nonexistent(self, idp):
""" Try to update a non-existent idp """
idp.ensure_missing()
command = idp.make_update_command(
updates=dict(ipaidpclientid='idpclient2'))
with raises_exact(errors.NotFound(
reason='%s: Identity Provider reference not found' % idp.cn)):
command()
def test_delete_nonexistent(self, idp):
""" Try to delete a non-existent idp """
idp.ensure_missing()
command = idp.make_delete_command()
with raises_exact(errors.NotFound(
reason='%s: Identity Provider reference not found' % idp.cn)):
command()
def test_rename_nonexistent(self, idp, renamedidp):
""" Try to rename a non-existent idp """
idp.ensure_missing()
command = idp.make_update_command(
updates=dict(setattr='cn=%s' % renamedidp.cn))
with raises_exact(errors.NotFound(
reason='%s: Identity Provider reference not found' % idp.cn)):
command()
@pytest.mark.tier1
class TestIdP(XMLRPC_test):
def test_retrieve(self, idp):
"""" Create idp and try to retrieve it """
idp.ensure_exists()
idp.retrieve()
def test_delete(self, idp):
""" Delete idp """
idp.ensure_exists()
idp.delete()
@pytest.mark.tier1
class TestFindIdp(XMLRPC_test):
def test_find(self, idp):
""" Basic check of idp-find """
idp.ensure_exists()
idp.find()
def test_find_with_all(self, idp):
""" Basic check of idp-find with --all """
idp.ensure_exists()
idp.find(all=True)
def test_find_with_pkey_only(self, idp):
""" Basic check of idp-find with primary keys only """
idp.ensure_exists()
command = idp.make_find_command(cn=idp.cn, pkey_only=True)
result = command()
idp.check_find(result, pkey_only=True)
@pytest.mark.tier1
class TestUpdateIdp(XMLRPC_test):
def test_update(self, idp):
""" Basic check of idp-mod """
idp.ensure_exists()
idp.update(
updates=dict(ipaidpclientid='NewClientID')
)
def test_rename(self, idp, renamedidp):
""" Rename idp and rename it back """
idp.ensure_exists()
renamedidp.ensure_missing()
oldcn = idp.cn
idp.update(updates=dict(rename=renamedidp.cn))
idp.update(updates=dict(rename=oldcn))
def test_rename_to_same_value(self, idp):
""" Try to rename idp to the same value """
idp.ensure_exists()
command = idp.make_update_command(
updates=dict(setattr=('cn=%s' % idp.cn))
)
with raises_exact(errors.EmptyModlist()):
command()
@pytest.mark.tier1
class TestCreateIdp(XMLRPC_test):
def test_create_idp_with_min_values(self):
""" Creation with only mandatory parameters """
idp_min = IdpTracker('min_idp', ipaidpauthendpoint=google_auth,
ipaidpdevauthendpoint=google_devauth,
ipaidptokenendpoint=google_token,
ipaidpuserinfoendpoint=google_userinfo,
ipaidpkeysendpoint=google_jwks,
ipaidpclientid="idp1client")
idp_min.track_create()
command = idp_min.make_create_command()
result = command()
idp_min.check_create(result)
idp_min.delete()
def test_create_idp_with_provider(self):
""" Creation with --provider parameter """
idp_with_provider = IdpTracker(
'idp_with_provider', ipaidpprovider='google',
ipaidpclientid="idpclient1")
idp_with_provider.track_create()
# the endpoints are automatically added
idp_with_provider.attrs.update(ipaidpauthendpoint=[google_auth])
idp_with_provider.attrs.update(ipaidpdevauthendpoint=[google_devauth])
idp_with_provider.attrs.update(ipaidptokenendpoint=[google_token])
idp_with_provider.attrs.update(ipaidpkeysendpoint=[google_jwks])
idp_with_provider.attrs.update(ipaidpuserinfoendpoint=[google_userinfo])
idp_with_provider.attrs.update(ipaidpscope=[idp_scope])
idp_with_provider.attrs.update(ipaidpsub=[idp_sub])
command = idp_with_provider.make_create_command()
result = command()
idp_with_provider.check_create(result)
idp_with_provider.delete()
def test_create_with_invalid_provider(self):
""" Creation with invalid --provider parameter """
idp_with_provider = IdpTracker(
'idp_with_provider', ipaidpprovider='fake',
ipaidpclientid="idpclient1")
idp_with_provider.track_create()
command = idp_with_provider.make_create_command()
with raises_exact(errors.ValidationError(
name='provider',
error="must be one of 'google', 'github', 'microsoft', "
"'okta', 'keycloak'"
)):
command()
def test_create_with_provider_and_authendpoint(self):
""" Creation with --provider parameter and --auth-uri"""
idp_with_provider = IdpTracker(
'idp_with_provider', ipaidpprovider='google',
ipaidpauthendpoint=google_auth,
ipaidpdevauthendpoint=google_devauth,
ipaidpclientid="idpclient1")
idp_with_provider.track_create()
command = idp_with_provider.make_create_command()
with raises_exact(errors.MutuallyExclusiveError(
reason='cannot specify both individual endpoints and IdP provider'
)):
command()
def test_create_with_provider_and_tokenendpoint(self):
""" Creation with --provider parameter and --token-uri"""
idp_with_provider = IdpTracker(
'idp_with_provider', ipaidpprovider='google',
ipaidptokenendpoint=google_token,
ipaidpdevauthendpoint=google_devauth,
ipaidpclientid="idpclient1")
idp_with_provider.track_create()
command = idp_with_provider.make_create_command()
with raises_exact(errors.MutuallyExclusiveError(
reason='cannot specify both individual endpoints and IdP provider'
)):
command()
def test_create_missing_authendpoint(self):
""" Creation with missing --dev-auth-uri and --auth-uri"""
idp_with_provider = IdpTracker(
'idp_with_provider',
ipaidptokenendpoint=google_token,
ipaidpclientid="idpclient1")
idp_with_provider.track_create()
command = idp_with_provider.make_create_command()
with raises_exact(errors.RequirementError(
name='dev-auth-uri or provider'
)):
command()
def test_create_missing_tokenendpoint(self):
""" Creation with missing --token-uri"""
idp_with_provider = IdpTracker(
'idp_with_provider',
ipaidpauthendpoint=google_auth,
ipaidpdevauthendpoint=google_devauth,
ipaidpclientid="idpclient1")
idp_with_provider.track_create()
command = idp_with_provider.make_create_command()
with raises_exact(errors.RequirementError(
name='token-uri or provider'
)):
command()
def test_create_missing_clientid(self):
""" Creation with missing --client-id"""
idp_with_provider = IdpTracker(
'idp_with_provider',
ipaidptokenendpoint=google_token,
ipaidpdevauthendpoint=google_devauth,
ipaidpauthendpoint=google_auth)
idp_with_provider.track_create()
command = idp_with_provider.make_create_command()
with raises_exact(errors.RequirementError(
name='client_id'
)):
command()
| 10,024
|
Python
|
.py
| 230
| 33.452174
| 80
| 0.628548
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,440
|
test_plugins_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_plugins_plugin.py
|
#
# Copyright (C) 2021 FreeIPA Contributors see COPYING for license
#
"""Test `plugins` plugin
"""
import pytest
from ipalib import api, errors
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
@pytest.mark.tier1
class TestPlugins(XMLRPC_test):
"""Test `plugins` plugin
"""
EXPECTED_KEYS = ("result", "count", "summary")
def run_plugins(self, *args, **options):
cmd = api.Command.plugins
cmd_result = cmd(*args, **options)
return cmd_result
def assert_result(self, cmd_result):
assert tuple(cmd_result.keys()) == self.EXPECTED_KEYS
result = cmd_result["result"]
assert isinstance(result, dict)
actual_count = cmd_result["count"]
assert isinstance(actual_count, int)
assert len(result) == actual_count
expected_summaries = (
f"{actual_count} plugin loaded", f"{actual_count} plugins loaded"
)
assert cmd_result["summary"] in expected_summaries
@pytest.mark.parametrize(
"server", [True, False, None], ids=["server", "local", "local_default"]
)
def test_plugins(self, server):
options = {}
if server is not None:
options = {"server": server}
cmd_result = self.run_plugins(**options)
self.assert_result(cmd_result)
assert cmd_result["count"] >= 1
@pytest.mark.parametrize("server", [True, False], ids=["server", "local"])
def test_plugins_with_nonexistent_argument(self, server):
with pytest.raises(errors.ZeroArgumentError):
self.run_plugins("nonexistentarg", server=server)
@pytest.mark.parametrize("server", [True, False], ids=["server", "local"])
def test_plugins_with_nonexistent_option(self, server):
with pytest.raises(errors.OptionError) as e:
self.run_plugins(
nonexistentoption="nonexistentoption", server=server
)
assert "Unknown option: nonexistentoption" in str(e.value)
| 1,992
|
Python
|
.py
| 49
| 33.469388
| 79
| 0.649586
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,441
|
test_caacl_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_caacl_plugin.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
"""
Test the `ipalib.plugins.caacl` module.
"""
import pytest
from ipalib import errors
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
from ipatests.test_xmlrpc.tracker.certprofile_plugin import CertprofileTracker
from ipatests.test_xmlrpc.tracker.caacl_plugin import CAACLTracker
from ipatests.test_xmlrpc.tracker.stageuser_plugin import StageUserTracker
from ipatests.test_xmlrpc.tracker.ca_plugin import CATracker
@pytest.fixture(scope='class')
def default_profile(request, xmlrpc_setup):
name = 'caIPAserviceCert'
desc = u'Standard profile for network services'
tracker = CertprofileTracker(name, store=True, desc=desc)
tracker.track_create()
return tracker
@pytest.fixture(scope='class')
def default_acl(request, xmlrpc_setup):
name = u'hosts_services_caIPAserviceCert'
tracker = CAACLTracker(name, service_category=u'all', host_category=u'all')
tracker.track_create()
tracker.attrs.update(
{u'ipamembercertprofile_certprofile': [u'caIPAserviceCert']})
return tracker
@pytest.fixture(scope='class')
def crud_acl(request, xmlrpc_setup):
name = u'crud-acl'
tracker = CAACLTracker(name)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def category_acl(request, xmlrpc_setup):
name = u'category_acl'
tracker = CAACLTracker(name, ipacertprofile_category=u'all',
user_category=u'all', service_category=u'all',
host_category=u'all', ipaca_category=u'all')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def caacl_test_ca(request, xmlrpc_setup):
name = u'caacl-test-ca'
subject = u'CN=caacl test subca,O=test industries inc.'
return CATracker(name, subject).make_fixture(request)
@pytest.fixture(scope='class')
def staged_user(request, xmlrpc_setup):
name = u'st-user'
tracker = StageUserTracker(name, u'stage', u'test')
return tracker.make_fixture(request)
@pytest.mark.tier0
class TestDefaultACL(XMLRPC_test):
def test_default_acl_present(self, default_acl):
default_acl.retrieve()
@pytest.mark.tier1
class TestCAACLbasicCRUD(XMLRPC_test):
def test_create(self, crud_acl):
crud_acl.create()
def test_delete(self, crud_acl):
crud_acl.delete()
def test_disable(self, crud_acl):
crud_acl.ensure_exists()
crud_acl.disable()
crud_acl.retrieve()
def test_disable_twice(self, crud_acl):
crud_acl.disable()
crud_acl.retrieve()
def test_enable(self, crud_acl):
crud_acl.enable()
crud_acl.retrieve()
def test_enable_twice(self, crud_acl):
crud_acl.enable()
crud_acl.retrieve()
def test_find(self, crud_acl):
crud_acl.find()
@pytest.mark.tier1
class TestCAACLMembers(XMLRPC_test):
def test_category_member_exclusivity(self, category_acl, default_profile):
category_acl.create()
default_profile.ensure_exists()
with pytest.raises(errors.MutuallyExclusiveError):
category_acl.add_profile(default_profile.name, track=False)
def test_mod_delete_category(self, category_acl):
updates = dict(
hostcategory=None,
servicecategory=None,
ipacertprofilecategory=None,
usercategory=None,
ipacacategory=None)
category_acl.update(updates)
def test_add_profile(self, category_acl, default_profile):
category_acl.add_profile(certprofile=default_profile.name)
category_acl.retrieve()
def test_remove_profile(self, category_acl, default_profile):
category_acl.remove_profile(certprofile=default_profile.name)
category_acl.retrieve()
def test_add_ca(self, category_acl, caacl_test_ca):
caacl_test_ca.ensure_exists()
category_acl.add_ca(ca=caacl_test_ca.name)
category_acl.retrieve()
def test_remove_ca(self, category_acl, caacl_test_ca):
category_acl.remove_ca(ca=caacl_test_ca.name)
category_acl.retrieve()
def test_add_invalid_value_service(self, category_acl, default_profile):
res = category_acl.add_service(service=default_profile.name, track=False)
assert len(res['failed']) == 1
assert(res['failed']['memberservice']['service'][0][0].startswith(default_profile.name))
# the same for other types
def test_add_invalid_value_user(self, category_acl, default_profile):
res = category_acl.add_user(user=default_profile.name, track=False)
assert len(res['failed']) == 1
res = category_acl.add_user(group=default_profile.name, track=False)
assert len(res['failed']) == 1
def test_add_invalid_value_host(self, category_acl, default_profile):
res = category_acl.add_host(host=default_profile.name, track=False)
assert len(res['failed']) == 1
res = category_acl.add_host(hostgroup=default_profile.name, track=False)
assert len(res['failed']) == 1
def test_add_invalid_value_profile(self, category_acl):
res = category_acl.add_profile(certprofile=category_acl.name, track=False)
assert len(res['failed']) == 1
def test_add_invalid_value_ca(self, category_acl):
res = category_acl.add_ca(ca=category_acl.name, track=False)
assert len(res['failed']) == 1
def test_add_staged_user_to_acl(self, category_acl, staged_user):
res = category_acl.add_user(user=staged_user.name, track=False)
assert len(res['failed']) == 1
| 5,604
|
Python
|
.py
| 127
| 37.590551
| 96
| 0.69919
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,442
|
test_add_remove_cert_cmd.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_add_remove_cert_cmd.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
import base64
import pytest
from ipalib import api, errors
from ipapython.dn import DN
from ipatests.util import assert_deepequal, raises
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
from ipatests.test_xmlrpc.testcert import get_testcert
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
from ipatests.test_xmlrpc.tracker.idview_plugin import IdviewTracker
@pytest.fixture(scope='class')
def idview(request, xmlrpc_setup):
tracker = IdviewTracker(cn=u'MyView')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def testuser(request, xmlrpc_setup):
tracker = UserTracker(name=u'testuser', givenname=u'John', sn=u'Donne')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def cert1(request, xmlrpc_setup):
return get_testcert(DN(('CN', u'testuser')), u'testuser')
@pytest.fixture(scope='class')
def cert2(request, xmlrpc_setup):
return get_testcert(DN(('CN', u'testuser')), u'testuser')
@pytest.mark.tier1
class CertManipCmdTestBase(XMLRPC_test):
entity_class = ''
entity_pkey = None
entity_subject = None
entity_principal = None
non_existent_entity = None
profile_store_orig = True
default_profile_id = u'caIPAserviceCert'
default_caacl = u'hosts_services_%s' % default_profile_id
cmd_options = dict(
entity_add=None,
caacl=None,
)
certs = None
certs_remainder = None
certs_subset = None
invalid_b64 = None
malformed_cert = None
mixed_certs = None
nonexistent_certs = None
cert_add_cmd = None
cert_del_cmd = None
cert_add_summary = u''
cert_del_summary = u''
entity_attrs = None
@classmethod
def disable_profile_store(cls):
try:
api.Command.certprofile_mod(cls.default_profile_id,
ipacertprofilestoreissued=False)
except errors.EmptyModlist:
cls.profile_store_orig = False
else:
cls.profile_store_orig = True
@classmethod
def restore_profile_store(cls):
if cls.profile_store_orig:
api.Command.certprofile_mod(
cls.default_profile_id,
ipacertprofilestoreissued=cls.profile_store_orig)
@classmethod
def add_entity(cls):
api.Command['%s_add' % cls.entity_class](
cls.entity_pkey,
**cls.cmd_options['entity_add'])
@classmethod
def delete_entity(cls):
try:
api.Command['%s_del' % cls.entity_class](cls.entity_pkey)
except errors.NotFound:
pass
# optional methods which implement adding CA ACL rule so that we can
# request cert for the entity. Currently used only for users.
@classmethod
def add_caacl(cls):
pass
@classmethod
def remove_caacl(cls):
pass
@pytest.fixture(autouse=True, scope="class")
def certmanipcmd_setup(self, request, xmlrpc_setup):
cls = request.cls
cls.delete_entity()
cls.add_entity()
cls.add_caacl()
cls.disable_profile_store()
# list of certificates to add to entry
cls.certs = [
u"MIICszCCAZugAwIBAgICM24wDQYJKoZIhvcNAQELBQAwIzEUMBIGA1UEChML\r\n"
"RVhBTVBMRS5PUkcxCzAJBgNVBAMTAkNBMB4XDTE3MDExOTEwMjUyOVoXDTE3M\r\n"
"DQxOTEwMjUyOVowFjEUMBIGA1UEAxMLc3RhZ2V1c2VyLTEwggEiMA0GCSqGSI\r\n"
"b3DQEBAQUAA4IBDwAwggEKAoIBAQCq03FRQQBvq4HwYMKP8USLZuOkKzuIs2V\r\n"
"Pt8k/+nO1dADrzMogKDiUDjCwYoG2UM/sj6P+PJUUCNDLh5eRRI+aR5VE5y2a\r\n"
"K95iCsj1ByDWrugAUXgr8GUUr+UbaGc0XxHCMnQBkYhzbXY3u91KYRRh5l3lx\r\n"
"RSICcVeJFJ/tiMS14Vsor1DWykHGz1wm0Zjwg1XDV3oea+uwrSz5Pa6RNPlgC\r\n"
"+GGW6B7+8qC2XdSSEwvY7y1SAGgqyOxN/FLwvqqMDNU0uX7fww587uZ57IfYz\r\n"
"b8Xn5DAprRFNk40FDc46rMlkPBT+Tij1I0jedD8h2e6WEa7JRU6SGToYDbRm4\r\n"
"RL9xAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAHqm1jXzYer9oSjYs9qh1jWpM\r\n"
"vTcN+0/z1uuX++Wezh3lG7IzYtypbZNxlXDECyrkUh+9oxzMJqdlZ562ko2br\r\n"
"uK6X5csbbM9uVsUva8NCsPPfZXDhrYaMKFvQGFY4pO3uhFGhccob037VN5Ifm\r\n"
"aKGM8aJ40cw2PQh38QPDdemizyVCThQ9Pcr+WgWKiG+t2Gd9NldJRLEhky0bW\r\n"
"2fc4zWZVbGq5nFXy1k+d/bgkHbVzf255eFZOKKy0NgZwig+uSlhVWPJjS4Z1w\r\n"
"LbpBKxTZp/xD0yEARs0u1ZcCELO/BkgQM50EDKmahIM4mdCs/7j1B/DdWs2i3\r\n"
"5lnbjxYYiUiyA=",
u"MIICszCCAZugAwIBAgICJGMwDQYJKoZIhvcNAQELBQAwIzEUMBIGA1UEChML\r\n"
"RVhBTVBMRS5PUkcxCzAJBgNVBAMTAkNBMB4XDTE3MDExOTEwMjcyN1oXDTE3M\r\n"
"DQxOTEwMjcyN1owFjEUMBIGA1UEAxMLc3RhZ2V1c2VyLTIwggEiMA0GCSqGSI\r\n"
"b3DQEBAQUAA4IBDwAwggEKAoIBAQDsEuTITzsRiUHXb8LxduokAEHwStCveKV\r\n"
"i8aVFBYQCRbpoXcoTfBISWvdmF3WOkIUfR1O0qrm0s3CPMAyWdTrnCI/45/Cc\r\n"
"FNDpGKPf+izN1t+WSrr6gCoz24y5ALyUEG5FSvHdDcIn+hY9Qvg3cRLxY9M4W\r\n"
"XmtR6p+d48v08nSSJXprgXS6ZiVvN7QGQfNRNDNoQZLmP9tQ/XvgJuiBMPj2N\r\n"
"aUFM8AwDnxGcvzExgaFlX0OKS6hymsUG60PeF0H0aYDgVH/0DKK+mZEA2FNbR\r\n"
"JIQt5Vk+c5aBvPrOfRLKrsQQ/zhtNOxk8Q0G+cwlzANCqbV7EzUFEFEtonnOP\r\n"
"tzY7AgMBAAEwDQYJKoZIhvcNAQELBQADggEBAIPcStKnxv6bdPiL2I7f4B/ME\r\n"
"BEV+kFnzu1msfkh1iouiKmM4ZkXLiqInKxEBwWNmhpRFoxKWaI3DjYtf/PYH/\r\n"
"guHipZvLIrVgfxlf/5ldXeoa7IHZ9hzvrG3WuYG6SHoJw6yaA6Vn8j8Q3r/kG\r\n"
"/1SLZpRpoq0EuhD7V/aHvxr/aiFnU4Fh2VaQd2ICOK2qBFQnoL5QyySVEJ7GA\r\n"
"RmajT3BqAASoixEqfMWYv2AqZnJ84JoI4reP0uZGjz5Cy32xQuenQckr8Faki\r\n"
"p28buFp46C34AWifbRERE396xocc9/Oc7dx9DyjeYqa9CuNo/pYlC4r8QCOkm\r\n"
"0xMWjoGcVUtUw=",
u"MIICszCCAZugAwIBAgICFpYwDQYJKoZIhvcNAQELBQAwIzEUMBIGA1UEChML\r\n"
"RVhBTVBMRS5PUkcxCzAJBgNVBAMTAkNBMB4XDTE3MDExOTEwMjczMVoXDTE3M\r\n"
"DQxOTEwMjczMVowFjEUMBIGA1UEAxMLc3RhZ2V1c2VyLTMwggEiMA0GCSqGSI\r\n"
"b3DQEBAQUAA4IBDwAwggEKAoIBAQDEIMvN8aElxMSyfqIj91nDuuvli/RKNhF\r\n"
"sIU32c7NJVF7kthvltmEwIVKKCE1Yji3GRWXBuZlSz5eSyDaqqpOpdYsVjYaz\r\n"
"XfWA5kjL8vGkoVt97SQ0TEkSOlinnjuo2unjU33RcruRp4rqeQE8EPBlAXYJr\r\n"
"+iK5Y+RF9Mz047ba097wUUX85QeEp1LWwYbLZleNFK1BwsmSL5Js+GcKEBEdi\r\n"
"KS/OfidTz7Hf7KICLo+iZlbG3lNLFQMvWFG8bzTeOgZ5OLDeBRzG6cSZK0Q3A\r\n"
"18uVg0jf0rv/nsOO/JQRK1FufvmOL2Xp7lqLFaAIuQqH1OuAq6MHfuaxwpdiU\r\n"
"yzVfAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAAs0K12ugVJ4t7/iUdddTmS+v\r\n"
"8FEEL92fWgU1bQHR/gMa2by9SIqS1KZVBc5JpJePqVf/S35Gt4o7sE3rbbmZm\r\n"
"mhGDL8D+BmGHjxdhENLyk6rvHOm+TDgM7nQK0FbPekMzkbsFxfw9R7iq8cnZD\r\n"
"7Y1T5e2N+WMzx6Jf/ner32V9CTfFbGP84G0+kqyqo7vp59VIwyHpC0L/0bh8W\r\n"
"YjFKNCPMbnZpO3212dNCaIMp0Kugi9D4kXAeM3unQ2/p5pN7Vgo+Xl9hioN5g\r\n"
"As+3SQR2pArUmr8RtjvfH/PxE8scWtRCCH4aBhfklrCHK+rpUzh4PXqhXGYJC\r\n"
"TmYzsAw/Z7vnY=",
]
# list of certificates for testing of removal of non-existent certs
cls.nonexistent_certs = [
u"MIICszCCAZugAwIBAgICYDAwDQYJKoZIhvcNAQELBQAwIzEUMBIGA1UEChML\r\n"
"RVhBTVBMRS5PUkcxCzAJBgNVBAMTAkNBMB4XDTE3MDExOTEwMjczNVoXDTE3M\r\n"
"DQxOTEwMjczNVowFjEUMBIGA1UEAxMLc3RhZ2V1c2VyLTQwggEiMA0GCSqGSI\r\n"
"b3DQEBAQUAA4IBDwAwggEKAoIBAQDAw12yHMBzQd27/Zv5STUlrkgGaClC4/U\r\n"
"+HxjHSHxFJLStYgK9DrXpRIqnkdwAr7rftlhFiRkqFE4GNGNAlhUlnkn0YTvD\r\n"
"59ucnpSRC7kjkrHAb1fWDNE3VYQOOF93CObOOAciNEl/K0HXqXxxYkhF6cz+m\r\n"
"N1gGd6oOtCu+G1vCoM25X3nlQdgOJtI8X2/MDvZ+nJVRqscsjeNnM0+A1Q1Cf\r\n"
"u2ukiqYgiQVYAa88hpADhXEF+hht3iIiw53GgD1Bb5xFm+OKpwBSegRJOjraj\r\n"
"XeWpr1ZN44JCTuFmAxwaNzynpYjrDbWXoLzbXEhyPbtT1jui6A1rRhEpc9Tyd\r\n"
"Wb4rAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAMe/xoqCmmSV/8x+hawb216sv\r\n"
"5CX6+WKMlLJTsmB586fQoJWJecn3Wg7DB1vfLeffayh9b+7g0w0OZnaUJlPNH\r\n"
"T6x5P29jH9J6fGOu3CIafCpvEXyamJKyQD6tER3l4iRBzoqW74BQh3W6rQnVs\r\n"
"lvM07LlQA0PB9RXYNvEmTCJKOtzA7wcARukvss9VS9oBfxjFgcGDKfMPPNaH9\r\n"
"IGEZi8QwEnOsSpLUobWPhRENbxwTMwlMspk9QG7NvTfisqFRXkAov0R/rHPqr\r\n"
"AXJTZmkPP+MhrsrbnT0CV2f6bxPkvXknuf+7Xi3h900BLQOSY+jqmtmGrYjln\r\n"
"tsqX1gL4y2e98=",
u"MIICszCCAZugAwIBAgICeicwDQYJKoZIhvcNAQELBQAwIzEUMBIGA1UEChML\r\n"
"RVhBTVBMRS5PUkcxCzAJBgNVBAMTAkNBMB4XDTE3MDExOTEwMjczOVoXDTE3M\r\n"
"DQxOTEwMjczOVowFjEUMBIGA1UEAxMLc3RhZ2V1c2VyLTUwggEiMA0GCSqGSI\r\n"
"b3DQEBAQUAA4IBDwAwggEKAoIBAQCd1VDwUwkwieLqngX1q2HoOe/tKnPxnr/\r\n"
"DrjbXAwFxEDcp7lfIUXALy33YZTAUGaNhlKzL+5sL3O5RcebSywBvw9Cpg9O4\r\n"
"lLPeAwdgnCHpNMaBjFL9/ySnwrIH0Hpx7chUXt1zz+z4ia1i7ZfVWHlP3D+pu\r\n"
"dR8MdzKH+1irtLcVL8ESfIqVsLGf0qV3wi2znqFsul6+e1MLE/RVXFoCmEX7J\r\n"
"5mJ77aFm6GgpXR7O3UAGl1NAfbZUz1Itt/NSrx8lHAYur4tUPQPEEa8XSe/B8\r\n"
"hG5J1inw6jm94vvpi2a3GOU6eDz4q0nM0/Rbia212tdbpyKdkm4aCQkoyhrJR\r\n"
"+DhvAgMBAAEwDQYJKoZIhvcNAQELBQADggEBADd5V5BMVY4zBRQiLZ2x+7seD\r\n"
"oT7ewyYW6Kk9oMlk7JWXgNyAG5/561vSkKIBkQG2CTRD3dAX7SbUwkxP7/a9g\r\n"
"ozJN3VOrLBUDhxyesr3cMuIU9XVyPezT3KapQjXkxzmJKiRNPc/fope4Xx5uc\r\n"
"UwYa6lm9QVCD4gnNElf+RexpI3VwkjmAWS3cvsKRFFNbZCS5gpCM/rOX76m4l\r\n"
"YcBSA8B+jb0FkOJt3u9fwtoMbhv5kdjEDGNWmG1kJ86ybqeWj12BpKGh4G6m4\r\n"
"E8ROnyuBt8Bolk4jqR3uCPfD4T+HpkttqrznRaGvroD020pEjtU22sAKkhBZQ\r\n"
"2Wbfkc49wxqpY=",
]
# cert subset to remove from entry
cls.certs_subset = cls.certs[:2]
# remaining subset
cls.certs_remainder = cls.certs[2:]
# mixture of certs which exist and do not exists in the entry
cls.mixed_certs = cls.certs[:2] + cls.nonexistent_certs[:1]
# invalid base64 encoding
cls.invalid_b64 = [u'few4w24gvrae54y6463234f']
# malformed certificate
cls.malformed_cert = [base64.b64encode(b'malformed cert')]
# store entity info for the final test
cls.entity_attrs = api.Command[
'%s_show' % cls.entity_class](cls.entity_pkey)
def fin():
cls.delete_entity()
cls.remove_caacl()
cls.restore_profile_store()
request.addfinalizer(fin)
def add_certs(self, certs):
# pylint: disable=E1102
result = self.cert_add_cmd(self.entity_pkey, usercertificate=certs)
return dict(
usercertificate=result['result'].get('usercertificate', []),
value=result.get('value'),
summary=result.get('summary')
)
def remove_certs(self, certs):
# pylint: disable=E1102
result = self.cert_del_cmd(self.entity_pkey, usercertificate=certs)
return dict(
usercertificate=result['result'].get('usercertificate', []),
value=result.get('value'),
summary=result.get('summary')
)
def test_01_add_cert_to_nonexistent_entity(self):
"""
Tests whether trying to add certificates to a non-existent entry
raises NotFound error.
"""
raises(errors.NotFound, self.cert_add_cmd,
self.non_existent_entity, usercertificate=self.certs)
def test_02_remove_cert_from_nonexistent_entity(self):
"""
Tests whether trying to remove certificates from a non-existent entry
raises NotFound error.
"""
raises(errors.NotFound, self.cert_add_cmd,
self.non_existent_entity, usercertificate=self.certs)
def test_03_remove_cert_from_entity_with_no_certs(self):
"""
Attempt to remove certificates from an entity that has none raises
AttrValueNotFound
"""
raises(errors.AttrValueNotFound, self.remove_certs, self.certs)
def test_04_add_invalid_b64_blob_to_entity(self):
raises(errors.Base64DecodeError, self.add_certs, self.invalid_b64)
def test_05_add_malformed_cert_to_entity(self):
raises(errors.CertificateFormatError, self.add_certs,
self.malformed_cert)
def test_06_add_single_cert_to_entity(self):
"""
Add single certificate to entry
"""
assert_deepequal(
dict(
usercertificate=[base64.b64decode(self.certs[0])],
summary=self.cert_add_summary % self.entity_pkey,
value=self.entity_pkey,
),
self.add_certs([self.certs[0]])
)
def test_07_add_more_certs_to_entity(self):
"""
Add the rest of the certificate set to the entry.
"""
assert_deepequal(
dict(
usercertificate=[base64.b64decode(c) for c in self.certs],
summary=self.cert_add_summary % self.entity_pkey,
value=self.entity_pkey,
),
self.add_certs(self.certs[1:])
)
def test_08_add_already_present_cert_to_entity(self):
"""
Tests that ExecutionError is raised when attempting to add certificates
to the entry that already contains them.
"""
raises(
errors.ExecutionError,
self.add_certs,
self.certs_subset
)
def test_09_remove_nonexistent_certs_from_entity(self):
"""
Tests that an attempt to remove certificates that are not present in
the entry raises AttrValueNotFound
"""
raises(
errors.AttrValueNotFound,
self.remove_certs,
self.nonexistent_certs
)
def test_10_remove_valid_and_nonexistent_certs_from_entity(self):
"""
Try to remove multiple certificates. Some of them are not present in
the entry. This scenario should raise InvocationError.
"""
raises(
errors.AttrValueNotFound,
self.remove_certs,
self.mixed_certs
)
def test_11_remove_cert_subset_from_entity(self):
"""
Test correct removal of a subset of entry's certificates.
"""
assert_deepequal(
dict(
usercertificate=[base64.b64decode(c)
for c in self.certs_remainder],
summary=self.cert_del_summary % self.entity_pkey,
value=self.entity_pkey,
),
self.remove_certs(self.certs_subset)
)
def test_12_remove_remaining_certs_from_entity(self):
"""
Test correct removal of all the remaining certificates from the entry.
"""
assert_deepequal(
dict(
usercertificate=[],
summary=self.cert_del_summary % self.entity_pkey,
value=self.entity_pkey,
),
self.remove_certs(self.certs_remainder)
)
def test_99_check_final_entity_consistency(self):
"""
Tests that all the previous operations do not modify other attributes
of the entry. Make sure that the show command returns the same
information as in the beginning of the test suite.
"""
assert_deepequal(
self.entity_attrs,
api.Command['%s_show' % self.entity_class](self.entity_pkey)
)
@pytest.mark.tier1
class TestCertManipCmdUser(CertManipCmdTestBase):
entity_class = 'user'
entity_pkey = u'tuser'
entity_subject = entity_pkey
entity_principal = u'tuser'
non_existent_entity = u'nonexistentuser'
cmd_options = dict(
entity_add=dict(givenname=u'Test', sn=u'User'),
caacl=dict(user=[u'tuser']),
)
cert_add_cmd = api.Command.user_add_cert
cert_del_cmd = api.Command.user_remove_cert
cert_add_summary = u'Added certificates to user "%s"'
cert_del_summary = u'Removed certificates from user "%s"'
@classmethod
def add_caacl(cls):
api.Command['caacl_add_%s' % cls.entity_class](
cls.default_caacl, **cls.cmd_options['caacl'])
@classmethod
def remove_caacl(cls):
api.Command['caacl_remove_%s' % cls.entity_class](
cls.default_caacl, **cls.cmd_options['caacl'])
@pytest.mark.tier1
class TestCertManipCmdStageuser(CertManipCmdTestBase):
entity_class = 'stageuser'
entity_pkey = u'suser'
entity_subject = entity_pkey
entity_principal = u'suser'
non_existent_entity = u'nonexistentstageuser'
cmd_options = dict(
entity_add=dict(givenname=u'Stage', sn=u'User'),
)
cert_add_cmd = api.Command.stageuser_add_cert
cert_del_cmd = api.Command.stageuser_remove_cert
cert_add_summary = u'Added certificates to stageuser "%s"'
cert_del_summary = u'Removed certificates from stageuser "%s"'
@pytest.mark.tier1
class TestCertManipCmdHost(CertManipCmdTestBase):
entity_class = 'host'
entity_pkey = u'host.example.com'
entity_subject = entity_pkey
entity_principal = u'host/%s' % entity_pkey
non_existent_entity = u'non.existent.host.com'
cmd_options = dict(
entity_add=dict(force=True),
)
cert_add_cmd = api.Command.host_add_cert
cert_del_cmd = api.Command.host_remove_cert
cert_add_summary = u'Added certificates to host "%s"'
cert_del_summary = u'Removed certificates from host "%s"'
@pytest.mark.tier1
class TestCertManipCmdService(CertManipCmdTestBase):
entity_class = 'service'
entity_pkey = u'testservice/%s@%s' % (TestCertManipCmdHost.entity_pkey,
api.env.realm)
entity_subject = TestCertManipCmdHost.entity_pkey
entity_principal = entity_pkey
non_existent_entity = u'testservice/non.existent.host.com'
cmd_options = dict(
entity_add=dict(force=True),
)
cert_add_cmd = api.Command.service_add_cert
cert_del_cmd = api.Command.service_remove_cert
cert_add_summary = u'Added certificates to service principal "%s"'
cert_del_summary = u'Removed certificates from service principal "%s"'
@classmethod
def add_entity(cls):
api.Command.host_add(TestCertManipCmdHost.entity_pkey, force=True)
super(TestCertManipCmdService, cls).add_entity()
@classmethod
def delete_entity(cls):
super(TestCertManipCmdService, cls).delete_entity()
try:
api.Command.host_del(TestCertManipCmdHost.entity_pkey)
except errors.NotFound:
pass
@pytest.mark.tier1
class TestCertManipIdOverride(XMLRPC_test):
entity_subject = u'testuser'
entity_principal = u'testuser'
def test_00_add_idoverrideuser(self, testuser, idview):
testuser.create()
idview.create()
idview.idoverrideuser_add(testuser)
def test_01_add_cert_to_idoverride(self, testuser, idview, cert1):
assert_deepequal(
dict(usercertificate=(base64.b64decode(cert1),),
summary=u'Added certificates to'
' idoverrideuser \"%s\"' % testuser.name,
value=testuser.name,
),
idview.add_cert_to_idoverrideuser(testuser.name, cert1)
)
def test_02_add_second_cert_to_idoverride(self, testuser,
idview, cert1, cert2):
assert_deepequal(
dict(
usercertificate=(base64.b64decode(cert1),
base64.b64decode(cert2)),
summary=u'Added certificates to'
' idoverrideuser \"%s\"' % testuser.name,
value=testuser.name,
),
idview.add_cert_to_idoverrideuser(testuser.name, cert2)
)
def test_03_add_the_same_cert_to_idoverride(self, testuser,
idview, cert1, cert2):
pytest.raises(errors.ExecutionError,
idview.add_cert_to_idoverrideuser,
testuser.name, cert1)
def test_04_user_show_displays_cert(self, testuser, idview, cert1, cert2):
result = api.Command.idoverrideuser_show(idview.cn, testuser.name)
assert_deepequal((base64.b64decode(cert1),
base64.b64decode(cert2)),
result['result']['usercertificate']
)
def test_05_remove_cert(self, testuser, idview, cert1, cert2):
assert_deepequal(
dict(
usercertificate=(base64.b64decode(cert2),),
value=testuser.name,
summary=u'Removed certificates from'
' idoverrideuser "%s"' % testuser.name
),
idview.del_cert_from_idoverrideuser(testuser.name, cert1)
)
| 20,734
|
Python
|
.py
| 454
| 35.753304
| 79
| 0.670513
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,443
|
test_hbac_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_hbac_plugin.py
|
# Authors:
# Pavel Zuna <pzuna@redhat.com>
#
# Copyright (C) 2009 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/plugins/hbacrule.py` module.
"""
import pytest
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, assert_attr_equal
from ipalib import api
from ipalib import errors
@pytest.mark.tier1
class test_hbac(XMLRPC_test):
"""
Test the `hbacrule` plugin.
"""
rule_name = u'testing_rule1234'
rule_renamed = u'mega_testing_rule'
rule_type = u'allow'
rule_type_fail = u'value not allowed'
rule_service = u'ssh'
rule_time = u'absolute 20081010000000 ~ 20081015120000'
rule_time2 = u'absolute 20081010000000 ~ 20081016120000'
# wrong time, has 30th day in February in first date
rule_time_fail = u'absolute 20080230000000 ~ 20081015120000'
rule_desc = u'description'
rule_desc_mod = u'description modified'
test_user = u'hbacrule_test_user'
test_group = u'hbacrule_test_group'
test_host = u'hbacrule.testnetgroup'
test_hostgroup = u'hbacrule_test_hostgroup'
test_service = u'sshd'
test_host_external = u'notfound.example.com'
test_invalid_sourcehost = u'inv+alid#srchost.nonexist.com'
def test_0_hbacrule_add(self):
"""
Test adding a new HBAC rule using `xmlrpc.hbacrule_add`.
"""
ret = self.failsafe_add(api.Object.hbacrule,
self.rule_name,
accessruletype=self.rule_type,
description=self.rule_desc,
)
entry = ret['result']
assert_attr_equal(entry, 'cn', self.rule_name)
assert_attr_equal(entry, 'accessruletype', self.rule_type)
assert_attr_equal(entry, 'ipaenabledflag', True)
assert_attr_equal(entry, 'description', self.rule_desc)
def test_1_hbacrule_add(self):
"""
Test adding an existing HBAC rule using `xmlrpc.hbacrule_add'.
"""
with pytest.raises(errors.DuplicateEntry):
api.Command['hbacrule_add'](
self.rule_name, accessruletype=self.rule_type
)
def test_2_hbacrule_show(self):
"""
Test displaying a HBAC rule using `xmlrpc.hbacrule_show`.
"""
entry = api.Command['hbacrule_show'](self.rule_name)['result']
assert_attr_equal(entry, 'cn', self.rule_name)
assert_attr_equal(entry, 'ipaenabledflag', True)
assert_attr_equal(entry, 'description', self.rule_desc)
def test_3_hbacrule_mod(self):
"""
Test modifying a HBAC rule using `xmlrpc.hbacrule_mod`.
"""
ret = api.Command['hbacrule_mod'](
self.rule_name, description=self.rule_desc_mod
)
entry = ret['result']
assert_attr_equal(entry, 'description', self.rule_desc_mod)
# def test_4_hbacrule_add_accesstime(self):
# """
# Test adding access time to HBAC rule using `xmlrpc.hbacrule_add_accesstime`.
# """
# return
# ret = api.Command['hbacrule_add_accesstime'](
# self.rule_name, accesstime=self.rule_time2
# )
# entry = ret['result']
# assert_attr_equal(entry, 'accesstime', self.rule_time);
# assert_attr_equal(entry, 'accesstime', self.rule_time2);
# def test_5_hbacrule_add_accesstime(self):
# """
# Test adding invalid access time to HBAC rule using `xmlrpc.hbacrule_add_accesstime`.
# """
# try:
# api.Command['hbacrule_add_accesstime'](
# self.rule_name, accesstime=self.rule_time_fail
# )
# except errors.ValidationError:
# pass
# else:
# assert False
def test_6_hbacrule_find(self):
"""
Test searching for HBAC rules using `xmlrpc.hbacrule_find`.
"""
ret = api.Command['hbacrule_find'](
cn=self.rule_name, accessruletype=self.rule_type,
description=self.rule_desc_mod
)
assert ret['truncated'] is False
entries = ret['result']
assert_attr_equal(entries[0], 'cn', self.rule_name)
assert_attr_equal(entries[0], 'accessruletype', self.rule_type)
assert_attr_equal(entries[0], 'description', self.rule_desc_mod)
def test_7_hbacrule_init_testing_data(self):
"""
Initialize data for more HBAC plugin testing.
"""
self.failsafe_add(api.Object.user,
self.test_user, givenname=u'first', sn=u'last'
)
self.failsafe_add(api.Object.group,
self.test_group, description=u'description'
)
self.failsafe_add(api.Object.host,
self.test_host, force=True
)
self.failsafe_add(api.Object.hostgroup,
self.test_hostgroup, description=u'description'
)
self.failsafe_add(api.Object.hbacsvc,
self.test_service, description=u'desc',
)
def test_8_hbacrule_add_user(self):
"""
Test adding user and group to HBAC rule using `xmlrpc.hbacrule_add_user`.
"""
ret = api.Command['hbacrule_add_user'](
self.rule_name, user=self.test_user, group=self.test_group
)
assert ret['completed'] == 2
failed = ret['failed']
assert 'memberuser' in failed
assert 'user' in failed['memberuser']
assert not failed['memberuser']['user']
assert 'group' in failed['memberuser']
assert not failed['memberuser']['group']
entry = ret['result']
assert_attr_equal(entry, 'memberuser_user', self.test_user)
assert_attr_equal(entry, 'memberuser_group', self.test_group)
def test_9_a_show_user(self):
"""
Test showing a user to verify HBAC rule membership
`xmlrpc.user_show`.
"""
ret = api.Command['user_show'](self.test_user, all=True)
entry = ret['result']
assert_attr_equal(entry, 'memberof_hbacrule', self.rule_name)
def test_9_b_show_group(self):
"""
Test showing a group to verify HBAC rule membership
`xmlrpc.group_show`.
"""
ret = api.Command['group_show'](self.test_group, all=True)
entry = ret['result']
assert_attr_equal(entry, 'memberof_hbacrule', self.rule_name)
def test_9_hbacrule_remove_user(self):
"""
Test removing user and group from HBAC rule using `xmlrpc.hbacrule_remove_user'.
"""
ret = api.Command['hbacrule_remove_user'](
self.rule_name, user=self.test_user, group=self.test_group
)
assert ret['completed'] == 2
failed = ret['failed']
assert 'memberuser' in failed
assert 'user' in failed['memberuser']
assert not failed['memberuser']['user']
assert 'group' in failed['memberuser']
assert not failed['memberuser']['group']
entry = ret['result']
assert 'memberuser_user' not in entry
assert 'memberuser_group' not in entry
def test_a_hbacrule_add_host(self):
"""
Test adding host and hostgroup to HBAC rule using `xmlrpc.hbacrule_add_host`.
"""
ret = api.Command['hbacrule_add_host'](
self.rule_name, host=self.test_host, hostgroup=self.test_hostgroup
)
assert ret['completed'] == 2
failed = ret['failed']
assert 'memberhost' in failed
assert 'host' in failed['memberhost']
assert not failed['memberhost']['host']
assert 'hostgroup' in failed['memberhost']
assert not failed['memberhost']['hostgroup']
entry = ret['result']
assert_attr_equal(entry, 'memberhost_host', self.test_host)
assert_attr_equal(entry, 'memberhost_hostgroup', self.test_hostgroup)
def test_a_hbacrule_show_host(self):
"""
Test showing host to verify HBAC rule membership
`xmlrpc.host_show`.
"""
ret = api.Command['host_show'](self.test_host, all=True)
entry = ret['result']
assert_attr_equal(entry, 'memberof_hbacrule', self.rule_name)
def test_a_hbacrule_show_hostgroup(self):
"""
Test showing hostgroup to verify HBAC rule membership
`xmlrpc.hostgroup_show`.
"""
ret = api.Command['hostgroup_show'](self.test_hostgroup, all=True)
entry = ret['result']
assert_attr_equal(entry, 'memberof_hbacrule', self.rule_name)
def test_b_hbacrule_remove_host(self):
"""
Test removing host and hostgroup from HBAC rule using `xmlrpc.hbacrule_remove_host`.
"""
ret = api.Command['hbacrule_remove_host'](
self.rule_name, host=self.test_host, hostgroup=self.test_hostgroup
)
assert ret['completed'] == 2
failed = ret['failed']
assert 'memberhost' in failed
assert 'host' in failed['memberhost']
assert not failed['memberhost']['host']
assert 'hostgroup' in failed['memberhost']
assert not failed['memberhost']['hostgroup']
entry = ret['result']
assert 'memberhost_host' not in entry
assert 'memberhost_hostgroup' not in entry
def test_a_hbacrule_add_sourcehost_deprecated(self):
"""
Test deprecated command hbacrule_add_sourcehost.
"""
with pytest.raises(errors.DeprecationError):
api.Command['hbacrule_add_sourcehost'](
self.rule_name, host=self.test_host,
hostgroup=self.test_hostgroup
)
def test_a_hbacrule_add_service(self):
"""
Test adding service to HBAC rule using `xmlrpc.hbacrule_add_service`.
"""
ret = api.Command['hbacrule_add_service'](
self.rule_name, hbacsvc=self.test_service
)
assert ret['completed'] == 1
failed = ret['failed']
assert 'memberservice' in failed
assert 'hbacsvc' in failed['memberservice']
assert not failed['memberservice']['hbacsvc']
entry = ret['result']
assert_attr_equal(entry, 'memberservice_hbacsvc', self.test_service)
def test_a_hbacrule_remove_service(self):
"""
Test removing service to HBAC rule using `xmlrpc.hbacrule_remove_service`.
"""
ret = api.Command['hbacrule_remove_service'](
self.rule_name, hbacsvc=self.test_service
)
assert ret['completed'] == 1
failed = ret['failed']
assert 'memberservice' in failed
assert 'hbacsvc' in failed['memberservice']
assert not failed['memberservice']['hbacsvc']
entry = ret['result']
assert 'memberservice service' not in entry
def test_b_hbacrule_remove_sourcehost_deprecated(self):
"""
Test deprecated command hbacrule_remove_sourcehost.
"""
with pytest.raises(errors.DeprecationError):
api.Command['hbacrule_remove_sourcehost'](
self.rule_name, host=self.test_host,
hostgroup=self.test_hostgroup
)
def test_c_hbacrule_mod_invalid_external_setattr(self):
"""
Test adding the same external host using `xmlrpc.hbacrule_add_host`.
"""
with pytest.raises(errors.ValidationError):
api.Command['hbacrule_mod'](
self.rule_name, setattr=self.test_invalid_sourcehost
)
def test_d_hbacrule_disable(self):
"""
Test disabling HBAC rule using `xmlrpc.hbacrule_disable`.
"""
assert api.Command['hbacrule_disable'](self.rule_name)['result'] is True
entry = api.Command['hbacrule_show'](self.rule_name)['result']
assert_attr_equal(entry, 'ipaenabledflag', False)
def test_e_hbacrule_enabled(self):
"""
Test enabling HBAC rule using `xmlrpc.hbacrule_enable`.
"""
assert api.Command['hbacrule_enable'](self.rule_name)['result'] is True
# check it's really enabled
entry = api.Command['hbacrule_show'](self.rule_name)['result']
assert_attr_equal(entry, 'ipaenabledflag', True)
def test_ea_hbacrule_disable_setattr(self):
"""
Test disabling HBAC rule using setattr
"""
command_result = api.Command['hbacrule_mod'](
self.rule_name, setattr=u'ipaenabledflag=false')
assert command_result['result']['ipaenabledflag'] == (False,)
entry = api.Command['hbacrule_show'](self.rule_name)['result']
assert_attr_equal(entry, 'ipaenabledflag', False)
def test_eb_hbacrule_enable_setattr(self):
"""
Test enabling HBAC rule using setattr
"""
command_result = api.Command['hbacrule_mod'](
self.rule_name, setattr=u'ipaenabledflag=1')
assert command_result['result']['ipaenabledflag'] == (True,)
# check it's really enabled
entry = api.Command['hbacrule_show'](self.rule_name)['result']
assert_attr_equal(entry, 'ipaenabledflag', True)
def test_f_hbacrule_exclusiveuser(self):
"""
Test adding a user to an HBAC rule when usercat='all'
"""
api.Command['hbacrule_mod'](self.rule_name, usercategory=u'all')
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['hbacrule_add_user'](
self.rule_name, user=u'admin'
)
finally:
api.Command['hbacrule_mod'](self.rule_name, usercategory=u'')
def test_g_hbacrule_exclusiveuser(self):
"""
Test setting usercat='all' in an HBAC rule when there are users
"""
api.Command['hbacrule_add_user'](self.rule_name, user=u'admin')
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['hbacrule_mod'](
self.rule_name, usercategory=u'all'
)
finally:
api.Command['hbacrule_remove_user'](self.rule_name, user=u'admin')
def test_h_hbacrule_exclusivehost(self):
"""
Test adding a host to an HBAC rule when hostcat='all'
"""
api.Command['hbacrule_mod'](self.rule_name, hostcategory=u'all')
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['hbacrule_add_host'](
self.rule_name, host=self.test_host
)
finally:
api.Command['hbacrule_mod'](self.rule_name, hostcategory=u'')
def test_i_hbacrule_exclusivehost(self):
"""
Test setting hostcat='all' in an HBAC rule when there are hosts
"""
api.Command['hbacrule_add_host'](self.rule_name, host=self.test_host)
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['hbacrule_mod'](
self.rule_name, hostcategory=u'all'
)
finally:
api.Command['hbacrule_remove_host'](
self.rule_name, host=self.test_host
)
def test_j_hbacrule_exclusiveservice(self):
"""
Test adding a service to an HBAC rule when servicecat='all'
"""
api.Command['hbacrule_mod'](self.rule_name, servicecategory=u'all')
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['hbacrule_add_service'](
self.rule_name, hbacsvc=self.test_service
)
finally:
api.Command['hbacrule_mod'](self.rule_name, servicecategory=u'')
def test_k_hbacrule_exclusiveservice(self):
"""
Test setting servicecat='all' in an HBAC rule when there are services
"""
api.Command['hbacrule_add_service'](
self.rule_name, hbacsvc=self.test_service
)
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['hbacrule_mod'](
self.rule_name, servicecategory=u'all'
)
finally:
api.Command['hbacrule_remove_service'](
self.rule_name, hbacsvc=self.test_service
)
def test_l_hbacrule_add(self):
"""
Test adding a new HBAC rule with a deny type.
"""
with pytest.raises(errors.ValidationError):
api.Command['hbacrule_add'](
u'denyrule',
accessruletype=u'deny',
description=self.rule_desc,
)
def test_m_hbacrule_add(self):
"""
Test changing an HBAC rule to the deny type
"""
with pytest.raises(errors.ValidationError):
api.Command['hbacrule_mod'](
self.rule_name,
accessruletype=u'deny',
)
def test_n_hbacrule_links(self):
"""
Test adding various links to HBAC rule
"""
api.Command['hbacrule_add_service'](
self.rule_name, hbacsvc=self.test_service
)
entry = api.Command['hbacrule_show'](self.rule_name)['result']
assert_attr_equal(entry, 'cn', self.rule_name)
assert_attr_equal(entry, 'memberservice_hbacsvc', self.test_service)
def test_o_hbacrule_rename(self):
"""
Test renaming an HBAC rule, rename it back afterwards
"""
api.Command['hbacrule_mod'](
self.rule_name, rename=self.rule_renamed
)
entry = api.Command['hbacrule_show'](self.rule_renamed)['result']
assert_attr_equal(entry, 'cn', self.rule_renamed)
# clean up by renaming the rule back
api.Command['hbacrule_mod'](
self.rule_renamed, rename=self.rule_name
)
def test_y_hbacrule_zap_testing_data(self):
"""
Clear data for HBAC plugin testing.
"""
api.Command['hbacrule_remove_host'](self.rule_name, host=self.test_host)
api.Command['hbacrule_remove_host'](self.rule_name, hostgroup=self.test_hostgroup)
api.Command['user_del'](self.test_user)
api.Command['group_del'](self.test_group)
api.Command['host_del'](self.test_host)
api.Command['hostgroup_del'](self.test_hostgroup)
api.Command['hbacsvc_del'](self.test_service)
def test_k_2_sudorule_referential_integrity(self):
"""
Test that links in HBAC rule were removed by referential integrity plugin
"""
entry = api.Command['hbacrule_show'](self.rule_name)['result']
assert_attr_equal(entry, 'cn', self.rule_name)
assert 'sourcehost_host' not in entry
assert 'sourcehost_hostgroup' not in entry
assert 'memberservice_hbacsvc' not in entry
def test_z_hbacrule_del(self):
"""
Test deleting a HBAC rule using `xmlrpc.hbacrule_del`.
"""
api.Command['hbacrule_del'](self.rule_name)
# verify that it's gone
with pytest.raises(errors.NotFound):
api.Command['hbacrule_show'](self.rule_name)
def test_zz_hbacrule_add_with_deprecated_option(self):
"""
Test using a deprecated command option 'sourcehostcategory' with 'hbacrule_add'.
"""
with pytest.raises(errors.ValidationError):
api.Command['hbacrule_add'](
self.rule_name, sourcehostcategory=u'all'
)
| 19,942
|
Python
|
.py
| 486
| 32.220165
| 93
| 0.615579
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,444
|
test_schema_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_schema_plugin.py
|
#
# Copyright (C) 2017 FreeIPA Contributors see COPYING for license
#
"""
Test the `ipaserver/plugins/schema.py` module.
"""
import pytest
from ipalib import api, errors
from ipapython.dnsutil import DNSName
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
@pytest.mark.tier1
class TestParamFindAndShowCommand(XMLRPC_test):
"""Test functionality of the ipa param-{find,show} command"""
def run_command(self, command, *args, **options):
cmd = api.Command[command]
cmd_result = cmd(*args, **options)
return cmd_result
def test_param_find(self):
"""Test param-find command"""
cmd = "param_find"
# right command without criteria
result = self.run_command(cmd, "user-add")
assert len(result['result']) != 0, result
assert result['result'][0]['name'] == 'uid', result
assert result['result'][0]['cli_name'] == 'login', result
assert result['result'][0]['label'] == 'User login', result
# right command, right criteria
criteria = u'postalcode'
result = self.run_command(cmd, "user-add", criteria)
assert len(result['result']) != 0, result
for item in result['result']:
assert (criteria in item['name'].lower() or
criteria in item['doc'].lower()), item
# right command, wrong criteria
result = self.run_command(cmd, "user-add", "fake")
assert len(result['result']) == 0, result
# wrong command, wrong criteria
result = self.run_command(cmd, "fake", "fake")
assert len(result['result']) == 0, result
# too many args
with pytest.raises(errors.MaxArgumentError):
self.run_command(cmd, "arg1", "arg2", "arg3")
def test_param_show(self):
"""Test param-show command"""
# right command, right criteria
criteria = "uid"
cmd = "param_show"
result = self.run_command(cmd, "user-add", criteria)
assert result['result'] is not None, result
assert result['result']['name'] == 'uid', result
assert result['result']['cli_name'] == 'login', result
assert result['result']['label'] == 'User login', result
# right command without criteria
with pytest.raises(errors.RequirementError):
self.run_command(cmd, "user-add")
# right command, wrong criteria
with pytest.raises(errors.NotFound):
self.run_command(cmd, "user-add", "fake")
# wrong command, wrong criteria
with pytest.raises(errors.NotFound):
self.run_command(cmd, "fake", "fake")
# too many args
with pytest.raises(errors.MaxArgumentError):
self.run_command(cmd, "arg1", "arg2", "arg3")
class TestOutputFindAndShowCommand(XMLRPC_test):
"""Test functionality of the ipa output-{find,show} command"""
def run_command(self, command, *args, **options):
cmd = api.Command[command]
cmd_result = cmd(*args, **options)
return cmd_result
def test_output_find(self):
"""Test output-find command"""
cmd = "output_find"
# right command without criteria
result = self.run_command(cmd, "user-add")
assert len(result['result']) != 0, result
assert result['result'][0]['name'] == 'summary', result
assert result['result'][0]['doc'] == \
'User-friendly description of action performed', result
# right command, right criteria
criteria = u'result'
result = self.run_command(cmd, "user-add", criteria)
assert len(result['result']) == 1, result
assert criteria in result['result'][0]['name'].lower(), result
# right command, wrong criteria
result = self.run_command(cmd, "user-add", "fake")
assert len(result['result']) == 0, result
# wrong command, wrong criteria
result = self.run_command(cmd, "fake", "fake")
assert len(result['result']) == 0, result
# too many args
with pytest.raises(errors.MaxArgumentError):
self.run_command(cmd, "arg1", "arg2", "arg3")
def test_output_show(self):
"""Test output-show command"""
# right command, right criteria
criteria = "value"
cmd = "output_show"
result = self.run_command(cmd, "user-add", criteria)
assert len(result['result']) != 0, result
assert criteria in result['result']['name'].lower(), result
assert result['result']['doc'] == \
"The primary_key value of the entry, e.g. 'jdoe' for a user", result
# right command without criteria
with pytest.raises(errors.RequirementError):
self.run_command(cmd, "user-add")
# right command, wrong criteria
with pytest.raises(errors.NotFound):
self.run_command(cmd, "user-add", "fake")
# wrong command, wrong criteria
with pytest.raises(errors.NotFound):
self.run_command(cmd, "fake", "fake")
# too many args
with pytest.raises(errors.MaxArgumentError):
self.run_command(cmd, "arg1", "arg2", "arg3")
class TestSchemaCommand(XMLRPC_test):
"""Test functionality of the ipa schema Command(no cli)"""
expected_keys = {
"classes", "commands", "fingerprint", "topics", "ttl", "version"
}
def run_command(self, command, *args, **options):
cmd = api.Command[command]
cmd_result = cmd(*args, **options)
return cmd_result
def test_schema_no_args(self):
"""Test schema command without any args"""
cmd_result = self.run_command("schema")
result = cmd_result["result"]
assert result.keys() == self.expected_keys
def test_schema_known_valid_fp(self):
"""Test schema command with valid fingerprint"""
# first, fetch current FP to reuse it
cmd_result = self.run_command("schema")
result = cmd_result["result"]
fp_valid = result["fingerprint"]
with pytest.raises(errors.SchemaUpToDate):
self.run_command("schema", known_fingerprints=(fp_valid,))
def test_schema_known_wrong_fp(self):
"""Test schema command with wrong fingerprint"""
fp_wrong = "wrong FP"
cmd_result = self.run_command("schema", known_fingerprints=(fp_wrong,))
result = cmd_result["result"]
assert result.keys() == self.expected_keys
def test_schema_too_many_args(self):
"""Test schema with too many args"""
with pytest.raises(errors.ZeroArgumentError):
self.run_command("schema", "arg1")
class TestCommandCommand(XMLRPC_test):
"""Test functionality of the ipa 'command' command"""
expected_keys = {
"doc",
"full_name",
"name",
"topic_topic",
"version",
}
def run_command(self, command, *args, **options):
cmd = api.Command[command]
cmd_result = cmd(*args, **options)
return cmd_result
def test_command_find_all(self):
"""Test command-find without any args"""
cmd_result = self.run_command("command_find")
result = cmd_result["result"]
assert len(result) != 0, result
for item in result:
assert self.expected_keys.issubset(item.keys()), item
def test_command_find_existent_command(self):
"""Test 'command' with existent command as arg"""
criteria = "user_add"
cmd_result = self.run_command("command_find", criteria)
result = cmd_result["result"]
assert len(result) != 0, result
for item in result:
assert self.expected_keys.issubset(item.keys()), item
name = item["name"].lower()
doc = item.get("doc", "").lower()
assert criteria in name or criteria in doc, item
def test_command_find_nonexistent_command(self):
"""Test command-find with nonexistent command as arg"""
cmd_result = self.run_command("command_find", "nonextentcommand")
result = cmd_result["result"]
assert len(result) == 0, result
def test_command_find_too_many_args(self):
"""Test command-find with too many args"""
with pytest.raises(errors.MaxArgumentError):
self.run_command("command_find", "arg1", "arg2")
def test_command_show_no_args(self):
"""Test command-show without args"""
with pytest.raises(errors.RequirementError):
self.run_command("command_show")
def test_command_show_existent_command(self):
"""Test command-show with existent command as arg"""
criteria = "user_add"
cmd_result = self.run_command("command_show", criteria)
result = cmd_result["result"]
assert self.expected_keys.issubset(result.keys()), result
assert result["name"] == criteria
def test_command_show_nonexistent_command(self):
"""Test command-show with nonexistent command as arg"""
with pytest.raises(errors.NotFound):
self.run_command("command_show", "nonextentcommand")
def test_command_show_too_many_args(self):
"""Test command-show with too many args"""
with pytest.raises(errors.MaxArgumentError):
self.run_command("command_show", "arg1", "arg2")
def test_command_defaults_no_args(self):
"""Test command_defaults without args"""
with pytest.raises(errors.RequirementError):
self.run_command("command_defaults")
def test_command_defaults_existent_command(self):
"""Test command_defaults with existent command as arg"""
criteria = "user_add"
cmd_result = self.run_command("command_defaults", criteria)
# 9c19dd350: do not validate unrequested params in command_defaults
result = cmd_result["result"]
assert len(result) == 0, result
def test_command_defaults_existent_command_params(self):
"""Test command_defaults with existent command as arg with params"""
criteria = "user_add"
params = ["all"]
cmd_result = self.run_command(
"command_defaults", criteria, params=params
)
result = cmd_result["result"]
assert len(result) == len(params), result
assert isinstance(result["all"], bool)
def test_command_defaults_existent_command_several_params(self):
"""
Test command_defaults with existent command as arg with several params
"""
criteria = "user_add"
params = ["all", "raw"]
cmd_result = self.run_command(
"command_defaults", criteria, params=params
)
result = cmd_result["result"]
assert len(result) == len(params), result
assert isinstance(result["all"], bool), result
assert isinstance(result["raw"], bool), result
def test_command_defaults_existent_command_kw(self):
"""Test command_defaults with existent command as arg with kw"""
criteria = "dnszone_add"
params = ["idnsname"]
kw = {"name_from_ip": "127.0.0.1"}
cmd_result = self.run_command(
"command_defaults", criteria, params=params
)
result = cmd_result["result"]
assert len(result) == 0, result
cmd_result = self.run_command(
"command_defaults", criteria, params=params, kw=kw
)
result = cmd_result["result"]
assert len(result) == len(params), result
assert isinstance(result["idnsname"], DNSName)
def test_command_defaults_nonexistent_command(self):
"""Test command-show with nonexistent command as arg"""
with pytest.raises(errors.NotFound):
self.run_command("command_defaults", "nonextentcommand")
def test_command_defaults_too_many_args(self):
"""Test command-show with too many args"""
with pytest.raises(errors.MaxArgumentError):
self.run_command("command_defaults", "arg1", "arg2")
class TestClassCommand(XMLRPC_test):
"""Test functionality of the ipa 'class' command"""
expected_keys = {
"name",
"full_name",
"version",
}
def run_command(self, command, *args, **options):
cmd = api.Command[command]
cmd_result = cmd(*args, **options)
return cmd_result
def test_class_find_all(self):
"""Test class-find without any args"""
cmd_result = self.run_command("class_find")
result = cmd_result["result"]
assert len(result) != 0, result
for item in result:
assert item.keys() == self.expected_keys, item
def test_class_find_existent_class(self):
"""Test class-find with existent class as arg"""
criteria = "user"
cmd_result = self.run_command("class_find", criteria)
result = cmd_result["result"]
assert len(result) != 0, result
for item in result:
assert item.keys() == self.expected_keys, item
name = item["name"].lower()
doc = item.get("doc", "").lower()
assert criteria in name or criteria in doc, item
def test_class_find_nonexistent_class(self):
"""Test class-find with nonexistent class as arg"""
cmd_result = self.run_command("class_find", "nonextentclass")
result = cmd_result["result"]
assert len(result) == 0, result
def test_class_find_too_many_args(self):
"""Test class-find with too many args"""
with pytest.raises(errors.MaxArgumentError):
self.run_command("class_find", "arg1", "arg2")
def test_class_show_no_args(self):
"""Test class-show without args"""
with pytest.raises(errors.RequirementError):
self.run_command("class_show")
def test_class_show_existent_class(self):
"""Test class-show with existent class as arg"""
criteria = "user"
cmd_result = self.run_command("class_show", criteria)
result = cmd_result["result"]
assert result.keys() == self.expected_keys, result
assert result["name"] == criteria
def test_class_show_nonexistent_class(self):
"""Test class-show with nonexistent class as arg"""
with pytest.raises(errors.NotFound):
self.run_command("class_show", "nonextentclass")
def test_class_show_too_many_args(self):
"""Test class-show with too many args"""
with pytest.raises(errors.MaxArgumentError):
self.run_command("class_show", "arg1", "arg2")
class TestTopicCommand(XMLRPC_test):
"""Test functionality of the ipa 'topic' command"""
expected_keys = {
"name",
"full_name",
"version",
"doc",
}
def run_command(self, command, *args, **options):
cmd = api.Command[command]
cmd_result = cmd(*args, **options)
return cmd_result
def test_topic_find_all(self):
"""Test topic-find without any args"""
cmd_result = self.run_command("topic_find")
result = cmd_result["result"]
assert len(result) != 0, result
for item in result:
assert self.expected_keys.issubset(item.keys()), item
def test_topic_find_existent_topic(self):
"""Test topic-find with existent topic as arg"""
criteria = "user"
cmd_result = self.run_command("topic_find", criteria)
result = cmd_result["result"]
assert len(result) != 0, result
for item in result:
assert self.expected_keys.issubset(item.keys()), item
name = item["name"].lower()
doc = item.get("doc", "").lower()
assert criteria in name or criteria in doc, item
def test_topic_find_nonexistent_topic(self):
"""Test topic-find with nonexistent topic as arg"""
cmd_result = self.run_command("topic_find", "nonextenttopic")
result = cmd_result["result"]
assert len(result) == 0, result
def test_topic_find_too_many_args(self):
"""Test topic-find with too many args"""
with pytest.raises(errors.MaxArgumentError):
self.run_command("topic_find", "arg1", "arg2")
def test_topic_show_no_args(self):
"""Test topic-show without args"""
with pytest.raises(errors.RequirementError):
self.run_command("topic_show")
def test_topic_show_existent_topic(self):
"""Test topic-show with existent topic as arg"""
criteria = "user"
cmd_result = self.run_command("topic_show", criteria)
result = cmd_result["result"]
assert self.expected_keys.issubset(result.keys()), result
assert result["name"] == criteria
def test_topic_show_nonexistent_topic(self):
"""Test topic-show with nonexistent topic as arg"""
with pytest.raises(errors.NotFound):
self.run_command("topic_show", "nonextenttopic")
def test_topic_show_too_many_args(self):
"""Test topic-show with too many args"""
with pytest.raises(errors.MaxArgumentError):
self.run_command("topic_show", "arg1", "arg2")
| 17,120
|
Python
|
.py
| 379
| 36.401055
| 80
| 0.6229
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,445
|
test_netgroup_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_netgroup_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Pavel Zuna <pzuna@redhat.com>
#
# Copyright (C) 2009 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/plugins/netgroup.py` module.
"""
from ipalib import api
from ipalib import errors
from ipatests.test_xmlrpc.xmlrpc_test import (Declarative, fuzzy_digits,
fuzzy_set_optional_oc,
fuzzy_uuid, fuzzy_netgroupdn)
from ipatests.test_xmlrpc import objectclasses
from ipapython.dn import DN
from ipatests.test_xmlrpc.test_user_plugin import get_user_result
import pytest
# Global so we can save the value between tests
netgroup_dn = None
netgroup1 = u'netgroup1'
netgroup2 = u'netgroup2'
netgroup_single = u'a'
host1 = u'ipatesthost.%s' % api.env.domain
host_dn1 = DN(('fqdn',host1),('cn','computers'),('cn','accounts'),
api.env.basedn)
unknown_host = u'unknown'
unknown_host2 = u'unknown2'
hostgroup1 = u'hg1'
hostgroup_dn1 = DN(('cn',hostgroup1),('cn','hostgroups'),('cn','accounts'),
api.env.basedn)
user1 = u'jexample'
# user2 is a member of testgroup
user2 = u'pexample'
group1 = u'testgroup'
invalidnetgroup1=u'+badnetgroup'
invalidnisdomain1=u'domain1,domain2'
invalidnisdomain2=u'+invalidnisdomain'
invalidhost=u'+invalid&host'
@pytest.mark.tier1
class test_netgroup(Declarative):
"""
Test the `netgroup` plugin.
"""
cleanup_commands = [
('netgroup_del', [netgroup1], {}),
('netgroup_del', [netgroup2], {}),
('host_del', [host1], {}),
('hostgroup_del', [hostgroup1], {}),
('user_del', [user1], {}),
('user_del', [user2], {}),
('group_del', [group1], {}),
]
tests=[
dict(
desc='Try to retrieve non-existent %r' % netgroup1,
command=('netgroup_show', [netgroup1], {}),
expected=errors.NotFound(
reason=u'%s: netgroup not found' % netgroup1),
),
dict(
desc='Try to update non-existent %r' % netgroup1,
command=('netgroup_mod', [netgroup1],
dict(description=u'Updated hostgroup 1')
),
expected=errors.NotFound(
reason=u'%s: netgroup not found' % netgroup1),
),
dict(
desc='Try to delete non-existent %r' % netgroup1,
command=('netgroup_del', [netgroup1], {}),
expected=errors.NotFound(
reason=u'%s: netgroup not found' % netgroup1),
),
dict(
desc='Test an invalid netgroup name %r' % invalidnetgroup1,
command=('netgroup_add', [invalidnetgroup1], dict(description=u'Test')),
expected=errors.ValidationError(name='name',
error=u'may only include letters, numbers, _, -, and .'),
),
dict(
desc='Test an invalid nisdomain1 name %r' % invalidnisdomain1,
command=('netgroup_add', [netgroup1],
dict(description=u'Test',nisdomainname=invalidnisdomain1)),
expected=errors.ValidationError(name='nisdomain',
error='may only include letters, numbers, _, -, and .'),
),
dict(
desc='Test an invalid nisdomain2 name %r' % invalidnisdomain2,
command=('netgroup_add', [netgroup1],
dict(description=u'Test',nisdomainname=invalidnisdomain2)),
expected=errors.ValidationError(name='nisdomain',
error='may only include letters, numbers, _, -, and .'),
),
dict(
desc='Create %r' % netgroup1,
command=('netgroup_add', [netgroup1],
dict(description=u'Test netgroup 1')
),
expected=dict(
value=netgroup1,
summary=u'Added netgroup "%s"' % netgroup1,
result=dict(
dn=fuzzy_netgroupdn,
cn=[netgroup1],
objectclass=objectclasses.netgroup,
description=[u'Test netgroup 1'],
nisdomainname=['%s' % api.env.domain],
ipauniqueid=[fuzzy_uuid],
),
),
),
dict(
desc='Create %r' % netgroup2,
command=('netgroup_add', [netgroup2],
dict(description=u'Test netgroup 2')
),
expected=dict(
value=netgroup2,
summary=u'Added netgroup "%s"' % netgroup2,
result=dict(
dn=fuzzy_netgroupdn,
cn=[netgroup2],
objectclass=objectclasses.netgroup,
description=[u'Test netgroup 2'],
nisdomainname=['%s' % api.env.domain],
ipauniqueid=[fuzzy_uuid],
),
),
),
dict(
desc='Create netgroup with name containing only one letter: %r' % netgroup_single,
command=('netgroup_add', [netgroup_single],
dict(description=u'Test netgroup_single')
),
expected=dict(
value=netgroup_single,
summary=u'Added netgroup "%s"' % netgroup_single,
result=dict(
dn=fuzzy_netgroupdn,
cn=[netgroup_single],
objectclass=objectclasses.netgroup,
description=[u'Test netgroup_single'],
nisdomainname=['%s' % api.env.domain],
ipauniqueid=[fuzzy_uuid],
),
),
),
dict(
desc='Delete %r' % netgroup_single,
command=('netgroup_del', [netgroup_single], {}),
expected=dict(
value=[netgroup_single],
summary=u'Deleted netgroup "%s"' % netgroup_single,
result=dict(failed=[]),
),
),
dict(
desc='Try to create duplicate %r' % netgroup1,
command=('netgroup_add', [netgroup1],
dict(description=u'Test netgroup 1')
),
expected=errors.DuplicateEntry(
message=u'netgroup with name "%s" already exists' % netgroup1),
),
dict(
desc='Create host %r' % host1,
command=('host_add', [host1],
dict(
description=u'Test host 1',
l=u'Undisclosed location 1',
force=True,
),
),
expected=dict(
value=host1,
summary=u'Added host "%s"' % host1,
result=dict(
dn=host_dn1,
fqdn=[host1],
description=[u'Test host 1'],
l=[u'Undisclosed location 1'],
krbprincipalname=[u'host/%s@%s' % (host1, api.env.realm)],
krbcanonicalname=[u'host/%s@%s' % (host1, api.env.realm)],
objectclass=objectclasses.host,
ipauniqueid=[fuzzy_uuid],
managedby_host=[host1],
has_keytab=False,
has_password=False,
),
),
),
dict(
desc='Create %r' % hostgroup1,
command=('hostgroup_add', [hostgroup1],
dict(description=u'Test hostgroup 1')
),
expected=dict(
value=hostgroup1,
summary=u'Added hostgroup "%s"' % hostgroup1,
result=dict(
dn=hostgroup_dn1,
cn=[hostgroup1],
objectclass=objectclasses.hostgroup,
description=[u'Test hostgroup 1'],
mepmanagedentry=[DN(('cn',hostgroup1),('cn','ng'),('cn','alt'),
api.env.basedn)],
ipauniqueid=[fuzzy_uuid],
),
),
),
dict(
desc='Create %r' % user1,
command=(
'user_add', [user1], dict(givenname=u'Test', sn=u'User1')
),
expected=dict(
value=user1,
summary=u'Added user "%s"' % user1,
result=get_user_result(user1, u'Test', u'User1', 'add'),
),
),
dict(
desc='Create %r' % user2,
command=(
'user_add', [user2], dict(givenname=u'Test', sn=u'User2')
),
expected=dict(
value=user2,
summary=u'Added user "%s"' % user2,
result=get_user_result(user2, u'Test', u'User2', 'add'),
),
),
dict(
desc='Create %r' % group1,
command=(
'group_add', [group1], dict(description=u'Test desc 1')
),
expected=dict(
value=group1,
summary=u'Added group "%s"' % group1,
result=dict(
cn=[group1],
description=[u'Test desc 1'],
gidnumber=[fuzzy_digits],
objectclass=fuzzy_set_optional_oc(
objectclasses.posixgroup, 'ipantgroupattrs'),
ipauniqueid=[fuzzy_uuid],
dn=DN(('cn',group1),('cn','groups'),('cn','accounts'),
api.env.basedn),
),
),
),
dict(
desc='Add user %r to group %r' % (user2, group1),
command=(
'group_add_member', [group1], dict(user=user2)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
group=tuple(),
user=tuple(),
service=tuple(),
idoverrideuser=tuple(),
),
),
result={
'dn': DN(('cn',group1),('cn','groups'),('cn','accounts'),
api.env.basedn),
'member_user': (user2,),
'gidnumber': [fuzzy_digits],
'cn': [group1],
'description': [u'Test desc 1'],
},
),
),
dict(
desc='Add invalid host %r to netgroup %r' % (invalidhost, netgroup1),
command=('netgroup_add_member', [netgroup1], dict(host=invalidhost)),
expected=errors.ValidationError(name='host',
error=u"only letters, numbers, '_', '-' are allowed. " +
u"DNS label may not start or end with '-'"),
),
dict(
desc='Add host %r to netgroup %r' % (host1, netgroup1),
command=(
'netgroup_add_member', [netgroup1], dict(host=host1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
},
),
),
dict(
desc='Add hostgroup %r to netgroup %r' % (hostgroup1, netgroup1),
command=(
'netgroup_add_member', [netgroup1], dict(hostgroup=hostgroup1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
},
),
),
dict(
desc='Search for netgroups using no_user with members',
command=('netgroup_find', [], dict(
no_user=user1, no_members=False)),
expected=dict(
count=2,
truncated=False,
summary=u'2 netgroups matched',
result=[
{
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
},
{
'dn': fuzzy_netgroupdn,
'cn': [netgroup2],
'description': [u'Test netgroup 2'],
'nisdomainname': [u'%s' % api.env.domain],
},
],
),
),
dict(
desc='Search for netgroups using no_user',
command=('netgroup_find', [], dict(no_user=user1)),
expected=dict(
count=2,
truncated=False,
summary=u'2 netgroups matched',
result=[
{
'dn': fuzzy_netgroupdn,
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
},
{
'dn': fuzzy_netgroupdn,
'cn': [netgroup2],
'description': [u'Test netgroup 2'],
'nisdomainname': [u'%s' % api.env.domain],
},
],
),
),
dict(
desc="Check %r doesn't match when searching for %s" % (netgroup1, user1),
command=('netgroup_find', [], dict(user=user1)),
expected=dict(
count=0,
truncated=False,
summary=u'0 netgroups matched',
result=[],
),
),
dict(
desc='Add user %r to netgroup %r' % (user1, netgroup1),
command=(
'netgroup_add_member', [netgroup1], dict(user=user1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
},
),
),
dict(
desc="Check %r doesn't match when searching for no %s" % (netgroup1, user1),
command=('netgroup_find', [], dict(no_user=user1)),
expected=dict(
count=1,
truncated=False,
summary=u'1 netgroup matched',
result=[
{
'dn': fuzzy_netgroupdn,
'cn': [netgroup2],
'description': [u'Test netgroup 2'],
'nisdomainname': [u'%s' % api.env.domain],
},
],
),
),
dict(
desc='Add group %r to netgroup %r' % (group1, netgroup1),
command=(
'netgroup_add_member', [netgroup1], dict(group=group1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
},
),
),
dict(
desc='Add netgroup %r to netgroup %r' % (netgroup2, netgroup1),
command=(
'netgroup_add_member', [netgroup1], dict(netgroup=netgroup2)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
},
),
),
dict(
desc='Add non-existent netgroup to netgroup %r' % (netgroup1),
command=(
'netgroup_add_member', [netgroup1], dict(netgroup=u'notfound')
),
expected=dict(
completed=0,
failed=dict(
member=dict(
netgroup=[(u'notfound', u'no such entry')],
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
},
),
),
dict(
desc='Add duplicate user %r to netgroup %r' % (user1, netgroup1),
command=(
'netgroup_add_member', [netgroup1], dict(user=user1)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=[('%s' % user1, u'This entry is already a member')],
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
},
),
),
dict(
desc='Add duplicate group %r to netgroup %r' % (group1, netgroup1),
command=(
'netgroup_add_member', [netgroup1], dict(group=group1)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=[('%s' % group1, u'This entry is already a member')],
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
},
),
),
dict(
desc='Add duplicate host %r to netgroup %r' % (host1, netgroup1),
command=(
'netgroup_add_member', [netgroup1], dict(host=host1)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=[('%s' % host1, u'This entry is already a member')],
),
),
result={
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
},
),
),
dict(
desc='Add duplicate hostgroup %r to netgroup %r' % (hostgroup1, netgroup1),
command=(
'netgroup_add_member', [netgroup1], dict(hostgroup=hostgroup1)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=[('%s' % hostgroup1, u'This entry is already a member')],
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
},
),
),
dict(
desc='Add unknown host %r to netgroup %r' % (unknown_host, netgroup1),
command=(
'netgroup_add_member', [netgroup1], dict(host=unknown_host)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Add invalid host %r to netgroup %r using setattr' %
(invalidhost, netgroup1),
command=(
'netgroup_mod', [netgroup1],
dict(setattr='externalhost=%s' % invalidhost)
),
expected=errors.ValidationError(name='externalhost',
error=u"only letters, numbers, '_', '-' are allowed. " +
u"DNS label may not start or end with '-'"),
),
dict(
desc='Add unknown host %r to netgroup %r using addattr' %
(unknown_host2, netgroup1),
command=(
'netgroup_mod', [netgroup1],
dict(addattr='externalhost=%s' % unknown_host2)
),
expected=dict(
value=u'netgroup1',
summary=u'Modified netgroup "netgroup1"',
result={
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host, unknown_host2],
},
)
),
dict(
desc='Remove unknown host %r from netgroup %r using delattr' %
(unknown_host2, netgroup1),
command=(
'netgroup_mod', [netgroup1],
dict(delattr='externalhost=%s' % unknown_host2)
),
expected=dict(
value=u'netgroup1',
summary=u'Modified netgroup "netgroup1"',
result={
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
)
),
dict(
desc='Retrieve %r' % netgroup1,
command=('netgroup_show', [netgroup1], {}),
expected=dict(
value=netgroup1,
summary=None,
result={
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Search for %r with members' % netgroup1,
command=('netgroup_find', [], dict(
cn=netgroup1, no_members=False)),
expected=dict(
count=1,
truncated=False,
summary=u'1 netgroup matched',
result=[
{
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
],
),
),
dict(
desc='Search for %r' % netgroup1,
command=('netgroup_find', [], dict(cn=netgroup1)),
expected=dict(
count=1,
truncated=False,
summary=u'1 netgroup matched',
result=[
{
'dn': fuzzy_netgroupdn,
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
],
),
),
dict(
desc='Search for %r using user with members' % netgroup1,
command=('netgroup_find', [], dict(
user=user1, no_members=False)),
expected=dict(
count=1,
truncated=False,
summary=u'1 netgroup matched',
result=[
{
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
],
),
),
dict(
desc='Search for %r using user' % netgroup1,
command=('netgroup_find', [], dict(user=user1)),
expected=dict(
count=1,
truncated=False,
summary=u'1 netgroup matched',
result=[
{
'dn': fuzzy_netgroupdn,
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
],
),
),
dict(
desc=('Search for all netgroups using empty member user with '
'members'),
command=('netgroup_find', [], dict(user=None, no_members=False)),
expected=dict(
count=2,
truncated=False,
summary=u'2 netgroups matched',
result=[
{
'dn': fuzzy_netgroupdn,
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
{
'dn': fuzzy_netgroupdn,
'memberof_netgroup': (netgroup1,),
'cn': [netgroup2],
'description': [u'Test netgroup 2'],
'nisdomainname': [u'%s' % api.env.domain],
},
],
),
),
dict(
desc='Search for all netgroups using empty member user',
command=('netgroup_find', [], dict(user=None)),
expected=dict(
count=2,
truncated=False,
summary=u'2 netgroups matched',
result=[
{
'dn': fuzzy_netgroupdn,
'cn': [netgroup1],
'description': [u'Test netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
{
'dn': fuzzy_netgroupdn,
'cn': [netgroup2],
'description': [u'Test netgroup 2'],
'nisdomainname': [u'%s' % api.env.domain],
},
],
),
),
dict(
desc='Update %r' % netgroup1,
command=('netgroup_mod', [netgroup1],
dict(description=u'Updated netgroup 1')
),
expected=dict(
value=netgroup1,
summary=u'Modified netgroup "%s"' % netgroup1,
result={
'memberhost_host': (host1,),
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Updated netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Remove host %r from netgroup %r' % (host1, netgroup1),
command=(
'netgroup_remove_member', [netgroup1], dict(host=host1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberhost_hostgroup': (hostgroup1,),
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Updated netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Remove hostgroup %r from netgroup %r' % (hostgroup1, netgroup1),
command=(
'netgroup_remove_member', [netgroup1], dict(hostgroup=hostgroup1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberuser_user': (user1,),
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Updated netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Remove user %r from netgroup %r' % (user1, netgroup1),
command=(
'netgroup_remove_member', [netgroup1], dict(user=user1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'memberuser_group': (group1,),
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Updated netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Remove group %r from netgroup %r' % (group1, netgroup1),
command=(
'netgroup_remove_member', [netgroup1], dict(group=group1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'member_netgroup': (netgroup2,),
'cn': [netgroup1],
'description': [u'Updated netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Remove netgroup %r from netgroup %r' % (netgroup2, netgroup1),
command=(
'netgroup_remove_member', [netgroup1], dict(netgroup=netgroup2)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'cn': [netgroup1],
'description': [u'Updated netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Remove host %r from netgroup %r again' % (host1, netgroup1),
command=(
'netgroup_remove_member', [netgroup1], dict(host=host1)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=[('%s' % host1, u'This entry is not a member')]
),
),
result={
'dn': fuzzy_netgroupdn,
'cn': [netgroup1],
'description': [u'Updated netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Remove hostgroup %r from netgroup %r again' % (hostgroup1, netgroup1),
command=(
'netgroup_remove_member', [netgroup1], dict(hostgroup=hostgroup1)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=[('%s' % hostgroup1, u'This entry is not a member')],
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'cn': [netgroup1],
'description': [u'Updated netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Remove user %r from netgroup %r again' % (user1, netgroup1),
command=(
'netgroup_remove_member', [netgroup1], dict(user=user1)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group=tuple(),
user=[('%s' % user1, u'This entry is not a member')],
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'cn': [netgroup1],
'description': [u'Updated netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Remove group %r from netgroup %r again' % (group1, netgroup1),
command=(
'netgroup_remove_member', [netgroup1], dict(group=group1)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
netgroup=tuple(),
),
memberuser=dict(
group= [('%s' % group1, u'This entry is not a member')],
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'cn': [netgroup1],
'description': [u'Updated netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Remove netgroup %r from netgroup %r again' % (netgroup2, netgroup1),
command=(
'netgroup_remove_member', [netgroup1], dict(netgroup=netgroup2)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
netgroup=[('%s' % netgroup2, u'This entry is not a member')],
),
memberuser=dict(
group=tuple(),
user=tuple(),
),
memberhost=dict(
hostgroup=tuple(),
host=tuple(),
),
),
result={
'dn': fuzzy_netgroupdn,
'cn': [netgroup1],
'description': [u'Updated netgroup 1'],
'nisdomainname': [u'%s' % api.env.domain],
'externalhost': [unknown_host],
},
),
),
dict(
desc='Delete %r' % netgroup1,
command=('netgroup_del', [netgroup1], {}),
expected=dict(
value=[netgroup1],
summary=u'Deleted netgroup "%s"' % netgroup1,
result=dict(failed=[]),
),
),
]
# No way to convert this test just yet.
# def test_6b_netgroup_show(self):
# """
# Confirm the underlying triples
# """
# # Do an LDAP query to the compat area and verify that the entry
# # is correct
# conn = ldap2(api)
# conn.connect()
# try:
# entries = conn.find_entries('cn=%s' % self.ng_cn,
# base_dn='cn=ng,cn=compat,%s' % api.env.basedn)
# except errors.NotFound:
# pytest.skip(
# 'compat and nis are not enabled, skipping test'
# )
# finally:
# conn.disconnect()
# triples = entries[0][0]['nisnetgrouptriple']
#
# # This may not prove to be reliable since order is not guaranteed
# # and even which user gets into which triple can be random.
# assert '(nosuchhost,jexample,example.com)' in triples
# assert '(ipatesthost.%s,pexample,example.com)' % api.env.domain in triples
| 50,027
|
Python
|
.py
| 1,299
| 20.849885
| 94
| 0.398346
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,446
|
test_trust_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_trust_plugin.py
|
# Authors:
# Martin Kosek <mkosek@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 the `ipaserver/plugins/trust.py` module.
"""
import six
from ipalib import api, errors
from ipapython.dn import DN
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import (
Declarative, fuzzy_guid, fuzzy_domain_sid, fuzzy_string, fuzzy_uuid,
fuzzy_set_optional_oc,
fuzzy_digits)
import pytest
if six.PY3:
unicode = str
trustconfig_ad_config = DN(('cn', api.env.domain),
api.env.container_cifsdomains, api.env.basedn)
testgroup = u'adtestgroup'
testgroup_dn = DN(('cn', testgroup), api.env.container_group, api.env.basedn)
default_group = u'Default SMB Group'
default_group_dn = DN(('cn', default_group), api.env.container_group, api.env.basedn)
@pytest.mark.tier1
class test_trustconfig(Declarative):
@pytest.fixture(autouse=True, scope="class")
def trustconfig_setup(self, declarative_setup):
if not api.Backend.rpcclient.isconnected():
api.Backend.rpcclient.connect()
try:
api.Command['trustconfig_show'](trust_type=u'ad')
except errors.NotFound:
pytest.skip('Trusts are not configured')
cleanup_commands = [
('group_del', [testgroup], {}),
('trustconfig_mod', [], {'trust_type': u'ad',
'ipantfallbackprimarygroup': default_group}),
]
tests = [
dict(
desc='Retrieve trust configuration for AD domains',
command=('trustconfig_show', [], {'trust_type': u'ad'}),
expected={
'value': u'ad',
'summary': None,
'result': {
'dn': trustconfig_ad_config,
'cn': [api.env.domain],
'ipantdomainguid': [fuzzy_guid],
'ipantfallbackprimarygroup': [default_group],
'ipantflatname': [fuzzy_string],
'ipantsecurityidentifier': [fuzzy_domain_sid],
'ad_trust_agent_server': [api.env.host],
'ad_trust_controller_server': [api.env.host]
},
},
),
dict(
desc='Retrieve trust configuration for AD domains with --raw',
command=('trustconfig_show', [], {'trust_type': u'ad', 'raw': True}),
expected={
'value': u'ad',
'summary': None,
'result': {
'dn': trustconfig_ad_config,
'cn': [api.env.domain],
'ipantdomainguid': [fuzzy_guid],
'ipantfallbackprimarygroup': [default_group_dn],
'ipantflatname': [fuzzy_string],
'ipantsecurityidentifier': [fuzzy_domain_sid]
},
},
),
dict(
desc='Create auxiliary group %r' % testgroup,
command=(
'group_add', [testgroup], dict(description=u'Test group')
),
expected=dict(
value=testgroup,
summary=u'Added group "%s"' % testgroup,
result=dict(
cn=[testgroup],
description=[u'Test group'],
gidnumber=[fuzzy_digits],
objectclass=fuzzy_set_optional_oc(
objectclasses.posixgroup, 'ipantgroupattrs'),
ipauniqueid=[fuzzy_uuid],
dn=testgroup_dn,
),
),
),
dict(
desc='Try to change primary fallback group to nonexistent group',
command=('trustconfig_mod', [],
{'trust_type': u'ad', 'ipantfallbackprimarygroup': u'doesnotexist'}),
expected=errors.NotFound(reason=u'%s: group not found' % 'doesnotexist')
),
dict(
desc='Try to change primary fallback group to nonexistent group DN',
command=('trustconfig_mod', [], {'trust_type': u'ad',
'ipantfallbackprimarygroup': u'cn=doesnotexist,dc=test'}),
expected=errors.NotFound(reason=u'%s: group not found' % 'cn=doesnotexist,dc=test')
),
dict(
desc='Change primary fallback group to "%s"' % testgroup,
command=('trustconfig_mod', [], {'trust_type': u'ad',
'ipantfallbackprimarygroup': testgroup}),
expected={
'value': u'ad',
'summary': u'Modified "ad" trust configuration',
'result': {
'cn': [api.env.domain],
'ipantdomainguid': [fuzzy_guid],
'ipantfallbackprimarygroup': [testgroup],
'ipantflatname': [fuzzy_string],
'ipantsecurityidentifier': [fuzzy_domain_sid],
'ad_trust_agent_server': [api.env.host],
'ad_trust_controller_server': [api.env.host]
},
},
),
dict(
desc='Change primary fallback group back to "%s" using DN' % default_group,
command=('trustconfig_mod', [], {'trust_type': u'ad',
'ipantfallbackprimarygroup': unicode(default_group_dn)}),
expected={
'value': u'ad',
'summary': u'Modified "ad" trust configuration',
'result': {
'cn': [api.env.domain],
'ipantdomainguid': [fuzzy_guid],
'ipantfallbackprimarygroup': [default_group],
'ipantflatname': [fuzzy_string],
'ipantsecurityidentifier': [fuzzy_domain_sid],
'ad_trust_agent_server': [api.env.host],
'ad_trust_controller_server': [api.env.host]
},
},
),
]
| 6,573
|
Python
|
.py
| 156
| 30.282051
| 95
| 0.553281
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,447
|
test_dns_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_dns_plugin.py
|
# Authors:
# Pavel Zuna <pzuna@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 the `ipaserver/plugins/dns.py` module.
"""
from ipalib import api, errors
from ipalib.util import normalize_zone
from ipapython.dnsutil import DNSName
from ipapython.dn import DN
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import Declarative, fuzzy_digits
import pytest
try:
from ipaserver.plugins.ldap2 import ldap2
except ImportError:
have_ldap2 = False
else:
have_ldap2 = True
_dns_zone_record = DNSName(u'@')
# default value of idnssoamname is local DNS server
self_server_ns = normalize_zone(api.env.host)
self_server_ns_dnsname = DNSName(self_server_ns)
zone1 = u'dnszone.test'
zone1_dnsname = DNSName(zone1)
zone1_absolute = u'%s.' % zone1
zone1_absolute_dnsname = DNSName(zone1_absolute)
zone1_ip = u'172.16.29.111'
zone1_dn = DN(('idnsname',zone1_absolute), api.env.container_dns, api.env.basedn)
zone1_ns = u'ns1.%s' % zone1_absolute
zone1_ns_dnsname = DNSName(zone1_ns)
zone1_ns_dn = DN(('idnsname','ns1'), zone1_dn)
zone1_self_server_ns_dn = DN(('idnsname',self_server_ns), zone1_dn)
zone1_rname = u'root.%s' % zone1_absolute
zone1_rname_dnsname = DNSName(zone1_rname)
zone1_permission = u'Manage DNS zone %s' % zone1_absolute
zone1_permission_dn = DN(('cn',zone1_permission),
api.env.container_permission,api.env.basedn)
zone1_txtrec_dn = DN(('idnsname', '_kerberos'), zone1_dn)
zone1_sub = u'sub.%s' % zone1_absolute
zone1_sub_dnsname = DNSName(zone1_sub)
zone1_sub_dn = DN(('idnsname', zone1_sub),
api.env.container_dns, api.env.basedn)
zone1_sub_fw = u'fw.%s' % zone1_sub
zone1_sub_fw_dnsname = DNSName(zone1_sub_fw)
zone1_sub_fw_dn = DN(('idnsname', zone1_sub_fw),
api.env.container_dns, api.env.basedn)
zone1_sub2_fw = u'fw.sub2.%s' % zone1_sub
zone1_sub2_fw_dnsname = DNSName(zone1_sub2_fw)
zone1_sub2_fw_dn = DN(('idnsname', zone1_sub2_fw),
api.env.container_dns, api.env.basedn)
zone2 = u'zone2.test'
zone2_dnsname = DNSName(zone2)
zone2_absolute = u'%s.' % zone2
zone2_absolute_dnsname = DNSName(zone2_absolute)
zone2_dn = DN(('idnsname', zone2_absolute), api.env.container_dns, api.env.basedn)
zone2_ns = u'ns1.%s' % zone2_absolute
zone2_ns_dnsname = DNSName(zone2_ns)
zone2_rname = u'root.%s' % zone2_absolute
zone2_rname_dnsname = DNSName(zone2_rname)
zone2_sub = "sub.%s" % zone2_absolute
zone2_sub_ns = "ns1.%s" % zone2_sub
zone2_sub_ns_dnsname = DNSName(zone2_sub_ns)
zone2_sub_rname = "root.%s" % zone2_sub
zone2_sub_rname_dnsname = DNSName(zone2_sub_rname)
zone2_sub_dnsname = DNSName(zone2_sub)
zone2_sub_absolute_dnsname = DNSName(zone2_sub)
zone2_sub_dn = DN(
("idnsname", zone2_sub), api.env.container_dns, api.env.basedn
)
zone3 = u'zone3.test'
zone3_dnsname = DNSName(zone3)
zone3_absolute = u'%s.' % zone3
zone3_absolute_dnsname = DNSName(zone3_absolute)
zone3_ip = u'172.16.70.1'
zone3_ip2 = u'172.16.70.129'
zone3_dn = DN(('idnsname', zone3_absolute), api.env.container_dns, api.env.basedn)
zone3_ns = u'ns1.%s' % zone3_absolute
zone3_ns_dnsname = DNSName(zone3_ns)
zone3_ns2 = u'ns2.%s' % zone3_absolute
zone3_ns2_dnsname = DNSName(zone3_ns2)
zone3_rname = u'root.%s' % zone3_absolute
zone3_rname_dnsname = DNSName(zone3_rname)
zone3a = "zone3a.test"
zone3a_absolute = "%s." % zone3a
zone3a_rname = "root.%s" % zone3a_absolute
zone3a_sub = "sub.%s" % zone3a_absolute
zone3a_sub_rname = "root.%s" % zone3a_sub
zone3_ns2_arec = u'ns2'
zone3_ns2_arec_dnsname = DNSName(zone3_ns2_arec)
zone3_ns2_arec_dn = DN(('idnsname',zone3_ns2_arec), zone3_dn)
zone3_ns2_arec_absolute = u'%s.%s' % (zone3_ns2_arec, zone3_absolute)
zone4_upper = u'ZONE4.test'
zone4 = u'zone4.test.'
zone4_dnsname = DNSName(zone4)
zone4_dn = DN(('idnsname', zone4), api.env.container_dns, api.env.basedn)
zone4_ns = u'ns1.%s' % zone4
zone4_ns_dnsname = DNSName(zone4_ns)
zone4_rname = u'root.%s' % zone4
zone4_rname_dnsname = DNSName(zone4_rname)
zone5 = u'zone--5.test.'
zone5_dnsname = DNSName(zone5)
zone5_dn = DN(('idnsname', zone5), api.env.container_dns, api.env.basedn)
zone5_ns = u'ns1.%s' % zone5
zone5_ns_dnsname = DNSName(zone5_ns)
zone5_rname = u'root.%s' % zone5
zone5_rname_dnsname = DNSName(zone5_rname)
zone6b = u'zone6b.test'
zone6b_absolute = u'%s.' % zone6b
zone6b_dnsname = DNSName(zone6b)
zone6b_absolute_dnsname = DNSName(zone6b_absolute)
zone6b_dn = DN(('idnsname', zone6b), api.env.container_dns, api.env.basedn)
zone6b_absolute_dn = DN(('idnsname', zone6b_absolute),
api.env.container_dns, api.env.basedn)
zone6b_rname = u'hostmaster'
zone6b_rname_dnsname = DNSName(zone6b_rname)
zone6b_ip = u'172.16.70.1'
zone6b_ns_arec = u'ns'
zone6b_ns = u'%s.%s' % (zone6b_ns_arec, zone6b_absolute)
zone6b_ns_arec_dnsname = DNSName(zone6b_ns_arec)
zone6b_ns_arec_dn = DN(('idnsname', zone6b_ns_arec), zone6b_dn)
zone6b_ns_dnsname = DNSName(zone6b_ns)
zone6b_absolute_arec_dn = DN(('idnsname', zone6b_ns_arec), zone6b_absolute_dn)
zone6 = u'zone6.test'
zone6_invalid = u'invalid-zone.zone6..test'
zone6_absolute = u'%s.' % zone6
zone6_dnsname = DNSName(zone6)
zone6_absolute_dnsname = DNSName(zone6_absolute)
zone6_dn = DN(('idnsname', zone6), api.env.container_dns, api.env.basedn)
zone6_absolute_dn = DN(('idnsname', zone6_absolute),
api.env.container_dns, api.env.basedn)
zone6_ns_relative = u'ns1'
zone6_absolute_arec_dn = DN(('idnsname', zone6_ns_relative), zone6_absolute_dn)
zone6_ns = u'%s.%s' % (zone6_ns_relative, zone6_absolute)
zone6_ns_relative_dnsname = DNSName(zone6_ns_relative)
zone6_ns_dnsname = DNSName(zone6_ns)
zone6_ns_arec_dnsname = DNSName(zone6_ns_relative)
zone6_ns_invalid_dnsname = u'invalid name server! ..%s' % zone6_absolute
zone6_rname = u'root.%s' % zone6_absolute
zone6_rname_dnsname = DNSName(zone6_rname)
zone6_rname_default = u'hostmaster'
zone6_rname_default_dnsname = DNSName(zone6_rname_default)
zone6_rname_relative_dnsname = DNSName(u'root')
zone6_rname_absolute_dnsname = DNSName(u'root.%s' % zone6_absolute)
zone6_rname_invalid_dnsname = u'invalid ! @ ! .. root..%s' % zone6_absolute
zone6_unresolvable_ns_relative = u'unresolvable'
zone6_unresolvable_ns = u'%s.%s' % (zone6_unresolvable_ns_relative,
zone6_absolute)
zone6_unresolvable_ns_dnsname = DNSName(zone6_unresolvable_ns)
zone6_unresolvable_ns_relative_dnsname = DNSName(zone6_unresolvable_ns_relative)
revzone1 = u'31.16.172.in-addr.arpa.'
revzone1_dnsname = DNSName(revzone1)
revzone1_ip = u'172.16.31.0'
revzone1_ipprefix = u'172.16.31.'
revzone1_dn = DN(('idnsname', revzone1), api.env.container_dns, api.env.basedn)
revzone2 = u'18.198.in-addr.arpa.'
revzone2_dnsname = DNSName(revzone2)
revzone2_ip = u'198.18.0.30/16'
revzone2_dn = DN(('idnsname',revzone2), api.env.container_dns, api.env.basedn)
revzone3_classless1 = u'70.16.172.in-addr.arpa.'
revzone3_classless1_dnsname = DNSName(revzone3_classless1)
revzone3_classless1_ip = u'172.16.70.0'
revzone3_classless1_ipprefix = u'172.16.70.'
revzone3_classless1_dn = DN(('idnsname', revzone3_classless1), api.env.container_dns, api.env.basedn)
revzone3_classless2 = u'128/25.70.16.172.in-addr.arpa.'
revzone3_classless2_dnsname = DNSName(revzone3_classless2)
revzone3_classless2_ip = u'172.16.70.128'
revzone3_classless2_ipprefix = u'172.16.70.'
revzone3_classless2_dn = DN(('idnsname', revzone3_classless2), api.env.container_dns, api.env.basedn)
revzone3_classless2_permission = u'Manage DNS zone %s' % revzone3_classless2
revzone3_classless2_permission_dn = DN(('cn', revzone3_classless2_permission),
api.env.container_permission, api.env.basedn)
name1 = u'testdnsres'
name1_dnsname = DNSName(name1)
name1_dn = DN(('idnsname',name1), zone1_dn)
name_ns = u'testdnsres-ns'
name_ns_dnsname = DNSName(name_ns)
name_ns_dn = DN(('idnsname',name_ns), zone1_dn)
name_ns_renamed = u'testdnsres-ns-renamed'
name_ns_renamed_dnsname = DNSName(name_ns_renamed)
revname1 = u'80'
revname1_dnsname = DNSName(revname1)
revname1_ip = revzone1_ipprefix + revname1
revname1_dn = DN(('idnsname',revname1), revzone1_dn)
revname2 = u'81'
revname2_dnsname = DNSName(revname2)
revname2_ip = revzone1_ipprefix + revname2
revname2_dn = DN(('idnsname',revname2), revzone1_dn)
cname = u'testcnamerec'
cname_dnsname = DNSName(cname)
cname_dn = DN(('idnsname',cname), zone1_dn)
dname = u'testdns-dname'
dname_dnsname = DNSName(dname)
dname_dn = DN(('idnsname',dname), zone1_dn)
dlv = u'dlv'
dlv_dnsname = DNSName(dlv)
dlv_dn = DN(('idnsname', dlv), zone1_dn)
dlvrec = u'60485 5 1 2BB183AF5F22588179A53B0A98631FAD1A292118'
ds = u'ds'
ds_dnsname = DNSName(ds)
ds_dn = DN(('idnsname', ds), zone1_dn)
ds_rec = u'0 0 0 00'
tlsa = u'tlsa'
tlsa_dnsname = DNSName(tlsa)
tlsa_dn = DN(('idnsname', tlsa), zone1_dn)
tlsarec_err1 = u'300 0 1 d2abde240d7cd3ee6b4b28c54df034b97983a1d16e8a410e4561cb106618e971'
tlsarec_err2 = u'0 300 1 d2abde240d7cd3ee6b4b28c54df034b97983a1d16e8a410e4561cb106618e971'
tlsarec_err3 = u'0 0 300 d2abde240d7cd3ee6b4b28c54df034b97983a1d16e8a410e4561cb106618e971'
tlsarec_ok = u'0 0 1 d2abde240d7cd3ee6b4b28c54df034b97983a1d16e8a410e4561cb106618e971'
wildcard_rec1 = u'*.test'
wildcard_rec1_dnsname = DNSName(wildcard_rec1)
wildcard_rec1_dn = DN(('idnsname',wildcard_rec1), zone1_dn)
wildcard_rec1_addr = u'172.16.15.55'
wildcard_rec1_test1 = u'a.test.%s' % zone1_absolute
wildcard_rec1_test2 = u'b.test.%s' % zone1_absolute
nsrev = u'128/28'
nsrev_dnsname = DNSName(nsrev)
nsrev_dn = DN(('idnsname',nsrev), revzone3_classless1_dn)
cnamerev = u'129'
cnamerev_dnsname = DNSName(cnamerev)
cnamerev_dn = DN(('idnsname',cnamerev), revzone3_classless1_dn)
cnamerev_hostname = u'129.128/25.70.16.172.in-addr.arpa.'
ptr_revzone3 = u'129'
ptr_revzone3_dnsname = DNSName(ptr_revzone3)
ptr_revzone3_dn = DN(('idnsname',cnamerev), revzone3_classless2_dn)
ptr_revzone3_hostname = zone3_ns2
relnxname = "does-not-exist-test"
absnxname = "does.not.exist.test."
arec1 = u'172.16.29.111'
arec2 = u'172.31.254.222'
arec3 = u'172.16.250.123'
aaaarec1 = u'ff02::1'
fwd_ip = u'172.16.31.80'
allowtransfer_tofwd = u'%s;' % fwd_ip
# 198.18.0.0/15 testing range reserved by RFC2544
allowquery_restricted_in = u'!198.18.2.0/24;any;'
allowquery_restricted_out = u'!198.18.2.0/24;any;'
idnzone1 = u'\u010d.test.'
idnzone1_punycoded = u'xn--bea.test.'
idnzone1_dnsname = DNSName(idnzone1)
idnzone1_dn = DN(('idnsname',idnzone1_punycoded), api.env.container_dns, api.env.basedn)
idnzone1_mname = u'ns1.%s' % idnzone1
idnzone1_mname_punycoded = u'ns1.%s' % idnzone1_punycoded
idnzone1_mname_dnsname = DNSName(idnzone1_mname)
idnzone1_mname_dn = DN(('idnsname','ns1'), idnzone1_dn)
idnzone1_rname = u'root.%s' % idnzone1
idnzone1_rname_punycoded = u'root.%s' % idnzone1_punycoded
idnzone1_rname_dnsname = DNSName(idnzone1_rname)
idnzone1_ip = u'172.16.11.1'
revidnzone1 = u'15.16.172.in-addr.arpa.'
revidnzone1_dnsname = DNSName(revidnzone1)
revidnzone1_ip = u'172.16.15.0/24'
revidnzone1_dn = DN(('idnsname', revidnzone1), api.env.container_dns, api.env.basedn)
idnzone1_permission = u'Manage DNS zone %s' % idnzone1
idnzone1_permission_dn = DN(('cn',idnzone1_permission),
api.env.container_permission,api.env.basedn)
idnres1 = u'sk\xfa\u0161ka'
idnres1_punycoded = u'xn--skka-rra23d'
idnres1_dnsname = DNSName(idnres1)
idnres1_dn = DN(('idnsname',idnres1_punycoded), idnzone1_dn)
idnrescname1 = u'\u0161\u0161'
idnrescname1_punycoded = u'xn--pgaa'
idnrescname1_dnsname = DNSName(idnrescname1)
idnrescname1_dn = DN(('idnsname',idnrescname1_punycoded), idnzone1_dn)
idnresdname1 = u'\xe1\xe1'
idnresdname1_punycoded = u'xn--1caa'
idnresdname1_dnsname = DNSName(idnresdname1)
idnresdname1_dn = DN(('idnsname',idnresdname1_punycoded), idnzone1_dn)
idndomain1 = u'\u010d\u010d\u010d.test'
idndomain1_punycoded = u'xn--beaaa.test'
idndomain1_dnsname = DNSName(idndomain1)
dnsafsdbres1 = u'sk\xfa\u0161ka-c'
dnsafsdbres1_punycoded = u'xn--skka-c-qya83f'
dnsafsdbres1_dnsname = DNSName(dnsafsdbres1)
dnsafsdbres1_dn = DN(('idnsname',dnsafsdbres1_punycoded), idnzone1_dn)
idnzone1_txtrec_dn = DN(('idnsname', '_kerberos'), idnzone1_dn)
fwzone1 = u'fwzone1.test.'
fwzone1_dnsname = DNSName(fwzone1)
fwzone1_dn = DN(('idnsname', fwzone1), api.env.container_dns, api.env.basedn)
fwzone1_permission = u'Manage DNS zone %s' % fwzone1
fwzone1_permission_dn = DN(('cn', fwzone1_permission),
api.env.container_permission, api.env.basedn)
fwzone2 = u'fwzone2.test.'
fwzone2_dnsname = DNSName(fwzone2)
fwzone2_dn = DN(('idnsname', fwzone2), api.env.container_dns, api.env.basedn)
fwzone3 = u'fwzone3.test.'
fwzone3_dnsname = DNSName(fwzone3)
fwzone3_dn = DN(('idnsname', fwzone3), api.env.container_dns, api.env.basedn)
fwzone_search_all_name = u'fwzone'
forwarder1 = u'172.16.15.1'
forwarder2 = u'172.16.15.2'
forwarder3 = u'172.16.15.3'
forwarder4 = u'172.16.15.4'
zone_findtest = u'.find.test.'
zone_findtest_master = u'master.find.test.'
zone_findtest_master_dnsname = DNSName(zone_findtest_master)
zone_findtest_master_dn = DN(('idnsname', zone_findtest_master),
api.env.container_dns, api.env.basedn)
zone_findtest_master_ns = u'ns1.%s' % zone_findtest_master
zone_findtest_master_ns_dnsname = DNSName(zone_findtest_master_ns)
zone_findtest_master_rname = u'root.%s' % zone_findtest_master
zone_findtest_master_rname_dnsname = DNSName(zone_findtest_master_rname)
zone_findtest_forward = u'forward.find.test.'
zone_findtest_forward_dnsname = DNSName(zone_findtest_forward)
zone_findtest_forward_dn = DN(('idnsname', zone_findtest_forward), api.env.container_dns, api.env.basedn)
zone_fw_wildcard = u'*.wildcardforwardzone.test.'
nonexistent_fwzone = u'non-existent.fwzone.test.'
nonexistent_fwzone_dnsname = DNSName(nonexistent_fwzone)
zone_root = u'.'
zone_root_dnsname = DNSName(zone_root)
zone_root_ip = u'172.16.29.222'
zone_root_dn = DN(('idnsname', zone_root),
api.env.container_dns, api.env.basedn)
zone_root_ns = u'ns'
zone_root_ns_dnsname = DNSName(zone_root_ns)
zone_root_ns_dn = DN(('idnsname', zone_root_ns), zone_root_dn)
zone_root_rname = u'root.example.com.'
zone_root_rname_dnsname = DNSName(zone_root_rname)
zone_root_permission = u'Manage DNS zone %s' % zone_root
zone_root_permission_dn = DN(('cn', zone_root_permission),
api.env.container_permission, api.env.basedn)
def _get_nameservers_ldap(conn):
base_dn = DN(('cn', 'masters'), ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn)
ldap_filter = '(&(objectClass=ipaConfigObject)(cn=DNS))'
dns_masters = []
try:
entries = conn.find_entries(filter=ldap_filter, base_dn=base_dn)[0]
for entry in entries:
try:
master = entry.dn[1]['cn']
dns_masters.append(master)
except (IndexError, KeyError):
pass
except errors.NotFound:
return []
return dns_masters
def get_nameservers():
ldap = ldap2(api)
ldap.connect()
nameservers = [normalize_zone(x) for x in _get_nameservers_ldap(ldap)]
return nameservers
# FIXME to avoid this hack with nameservers, tests should be functional
nameservers = []
# get list of nameservers from LDAP
get_nameservers_error = None
if have_ldap2:
try:
nameservers = get_nameservers()
except Exception as e:
get_nameservers_error = e
else:
if not nameservers:
# if DNS is installed there must be at least one IPA DNS server
get_nameservers_error = "No DNS servers found in LDAP"
@pytest.mark.tier1
class test_dns(Declarative):
@pytest.fixture(autouse=True, scope="class")
def dns_setup(self, declarative_setup):
if not api.Backend.rpcclient.isconnected():
api.Backend.rpcclient.connect()
if not have_ldap2:
pytest.skip('server plugin not available')
if get_nameservers_error is not None:
pytest.skip(
'unable to get list of nameservers (%s)' %
get_nameservers_error
)
try:
api.Command['dnszone_add'](zone1,
idnssoarname = zone1_rname,
)
api.Command['dnszone_del'](zone1)
except errors.NotFound:
pytest.skip('DNS is not configured')
except errors.DuplicateEntry:
pass
cleanup_commands = [
(
"dnszone_del",
[
zone1,
zone2,
zone2_sub,
zone3,
zone3a,
zone3a_sub,
zone4,
zone5,
revzone1,
revzone2,
revzone3_classless1,
revzone3_classless2,
idnzone1,
revidnzone1,
],
{'continue': True},
),
('dnsconfig_mod', [], {'idnsforwarders' : None,
'idnsforwardpolicy' : None,
'idnsallowsyncptr' : None,
}),
('permission_del', [zone1_permission, idnzone1_permission,
revzone3_classless2_permission], {'force': True}
),
]
tests = [
dict(
desc='Try to retrieve non-existent zone %r' % zone1,
command=('dnszone_show', [zone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS zone not found' % zone1_absolute),
),
dict(
desc='Try to retrieve non-existent IDN zone %r' % idnzone1,
command=('dnszone_show', [idnzone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS zone not found' % idnzone1),
),
dict(
desc='Try to update non-existent zone %r' % zone1,
command=('dnszone_mod', [zone1], {'idnssoaminimum': 3500}),
expected=errors.NotFound(
reason=u'%s: DNS zone not found' % zone1_absolute),
),
dict(
desc='Try to delete non-existent zone %r' % zone1,
command=('dnszone_del', [zone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS zone not found' % zone1_absolute),
),
dict(
desc='Create zone %r' % zone1,
command=(
'dnszone_add', [zone1], {
'idnssoarname': zone1_rname,
}
),
expected={
'value': zone1_absolute_dnsname,
'summary': None,
'result': {
'dn': zone1_dn,
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Try to create duplicate zone %r' % zone1,
command=(
'dnszone_add', [zone1], {
'idnssoarname': zone1_rname,
}
),
expected=errors.DuplicateEntry(
message=u'DNS zone with name "%s" already exists' % zone1_absolute),
),
dict(
desc=f"Parent zone for {zone2} tests",
command=(
'dnszone_add', [zone2], {
'idnssoarname': zone2_rname,
}
),
expected=lambda x, y: True,
),
dict(
desc="Try to create a zone with nonexistent NS entry",
command=(
"dnszone_add", [zone2_sub], {
"idnssoamname": zone2_sub_ns,
"idnssoarname": zone2_sub_rname,
}
),
expected=errors.NotFound(
reason=(
"Nameserver '%s' does not have a corresponding A/AAAA "
"record" % zone2_sub_ns
),
),
),
dict(
desc='Create a zone with nonexistent NS entry with --force',
command=(
"dnszone_add", [zone2_sub], {
"idnssoamname": zone2_sub_ns,
"idnssoarname": zone2_sub_rname,
"force": True,
}
),
expected={
'value': zone2_sub_absolute_dnsname,
'summary': None,
'result': {
'dn': zone2_sub_dn,
'idnsname': [zone2_sub_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [zone2_sub_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone2_sub_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
'messages': (
{'message': u"Semantic of setting Authoritative nameserver "
u"was changed. "
u"It is used only for setting the SOA MNAME "
u"attribute.\n"
u"NS record(s) can be edited in zone "
u"apex - '@'. ",
'code': 13005,
'type': u'warning',
'name': u'OptionSemanticChangedWarning',
'data': {
'current_behavior': u"It is used only for setting the "
u"SOA MNAME attribute.",
'hint': u"NS record(s) can be edited in zone apex - "
u"'@'. ",
'label': u"setting Authoritative nameserver"
}},
)
},
),
dict(
desc='Try to remove value of "idnssomrname" attribute using dnszone-mod --name-server=',
command=(
'dnszone_mod', [zone2], {
'idnssoamname': None,
}
),
expected=errors.ValidationError(name='name_server', error=u"is required"),
),
dict(
desc='Create a zone with upper case name',
command=(
'dnszone_add', [zone4_upper], {
'idnssoarname': zone4_rname,
}
),
expected={
'value': zone4_dnsname,
'summary': None,
'result': {
'dn': zone4_dn,
'idnsname': [zone4_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone4_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict( # https://fedorahosted.org/freeipa/ticket/4268
desc='Create a zone with consecutive dash characters',
command=(
'dnszone_add', [zone5], {
'idnssoarname': zone5_rname,
}
),
expected={
'value': zone5_dnsname,
'summary': None,
'result': {
'dn': zone5_dn,
'idnsname': [zone5_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone5_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Try to create a zone w/ a name and name-from-ipa %r' % zone1,
command=(
'dnszone_add', [zone1], {
'idnssoarname': zone1_rname,
'name_from_ip': revzone1_ip,
}
),
expected=errors.ValidationError(
message=u'invalid \'name-from-ip\': cannot be used when a '
'zone is specified'),
),
dict(
desc='Retrieve zone %r' % zone1,
command=('dnszone_show', [zone1], {}),
expected={
'value': zone1_absolute_dnsname,
'summary': None,
'result': {
'dn': zone1_dn,
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowquery': [u'any;'],
},
},
),
dict(
desc='Update zone %r' % zone1,
command=('dnszone_mod', [zone1], {'idnssoarefresh': 5478}),
expected={
'value': zone1_absolute_dnsname,
'summary': None,
'result': {
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [u'5478'],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowquery': [u'any;'],
},
},
),
dict(
desc='Try to add invalid NSEC3PARAM record to zone %s' % (zone1),
command=('dnszone_mod', [zone1], {'nsec3paramrecord': u'0 0 0 0 X'}),
expected=errors.ValidationError(name="nsec3param_rec",
error=(u'expected format: <0-255> <0-255> <0-65535> '
u'even-length_hexadecimal_digits_or_hyphen')
)
),
dict(
desc='Try to add invalid NSEC3PARAM record to zone %s' % (zone1),
command=('dnszone_mod', [zone1], {'nsec3paramrecord': u'0 0 0 X'}),
expected=errors.ValidationError(name="nsec3param_rec",
error=(u'expected format: <0-255> <0-255> <0-65535> '
u'even-length_hexadecimal_digits_or_hyphen')
)
),
dict(
desc='Try to add invalid NSEC3PARAM record to zone %s' % (zone1),
command=('dnszone_mod', [zone1], {'nsec3paramrecord': u'333 0 0 -'}),
expected=errors.ValidationError(name="nsec3param_rec",
error=u'algorithm value: allowed interval 0-255'
)
),
dict(
desc='Try to add invalid NSEC3PARAM record to zone %s' % (zone1),
command=('dnszone_mod', [zone1], {'nsec3paramrecord': u'0 333 0 -'}),
expected=errors.ValidationError(name="nsec3param_rec",
error=u'flags value: allowed interval 0-255'
)
),
dict(
desc='Try to add invalid NSEC3PARAM record to zone %s' % (zone1),
command=('dnszone_mod', [zone1], {'nsec3paramrecord': u'0 0 65536 -'}),
expected=errors.ValidationError(name="nsec3param_rec",
error=u'iterations value: allowed interval 0-65535'
)
),
dict(
desc='Try to add invalid NSEC3PARAM record to zone %s' % (zone1),
command=('dnszone_mod', [zone1], {'nsec3paramrecord': u'0 0 0 A'}),
expected=errors.ValidationError(name="nsec3param_rec",
error=(u'expected format: <0-255> <0-255> <0-65535> '
u'even-length_hexadecimal_digits_or_hyphen')
)
),
dict(
desc='Add NSEC3PARAM record to zone %s' % (zone1),
command=('dnszone_mod', [zone1], {'nsec3paramrecord': u'0 0 0 -'}),
expected={
'value': zone1_absolute_dnsname,
'summary': None,
'result': {
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [u'5478'],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowquery': [u'any;'],
'nsec3paramrecord': [u'0 0 0 -'],
},
},
),
dict(
desc='Delete NSEC3PARAM record from zone %s' % (zone1),
command=('dnszone_mod', [zone1], {'nsec3paramrecord': u''}),
expected={
'value': zone1_absolute_dnsname,
'summary': None,
'result': {
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [u'5478'],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowquery': [u'any;'],
},
},
),
dict(
desc='Try to create reverse zone %r with NS record in it' % revzone1,
command=(
'dnszone_add', [revzone1], {
'idnssoamname': u'ns',
'idnssoarname': zone1_rname,
}
),
expected=errors.ValidationError(name='name-server',
error=u"Nameserver for reverse zone cannot be a relative DNS name"),
),
dict(
desc='Create reverse zone %r' % revzone1,
command=(
'dnszone_add', [revzone1], {
'idnssoarname': zone1_rname,
}
),
expected={
'value': revzone1_dnsname,
'summary': None,
'result': {
'dn': revzone1_dn,
'idnsname': [revzone1_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-subdomain %(zone)s PTR;'
% dict(realm=api.env.realm, zone=revzone1)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Search for zones with admin email %r' % (zone1_rname),
command=('dnszone_find', [], {'idnssoarname': zone1_rname}),
expected={
'summary': None,
'count': 2,
'truncated': False,
'result': [{
'dn': revzone1_dn,
'idnsname': [revzone1_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy':
[u'grant %(realm)s krb5-subdomain %(zone)s PTR;'
% dict(
realm=api.env.realm, zone=revzone1_dnsname
)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
},
{
'dn': zone1_dn,
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [u'5478'],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
}],
},
),
dict(
desc='Search for zones with admin email %r with --forward-only' % zone1_rname,
command=('dnszone_find', [], {'idnssoarname': zone1_rname, 'forward_only' : True}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [{
'dn': zone1_dn,
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [u'5478'],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
}],
},
),
dict(
desc='Delete reverse zone %r' % revzone1,
command=('dnszone_del', [revzone1], {}),
expected={
'value': [revzone1_dnsname],
'summary': u'Deleted DNS zone "%s"' % revzone1,
'result': {'failed': []},
},
),
dict(
desc='Try to retrieve non-existent record %r in zone %r' % (name1, zone1),
command=('dnsrecord_show', [zone1, name1], {}),
expected=errors.NotFound(
reason=u'%s: DNS resource record not found' % name1),
),
dict(
desc='Try to delete non-existent record %r in zone %r' % (name1, zone1),
command=('dnsrecord_del', [zone1, name1], {'del_all' : True}),
expected=errors.NotFound(
reason=u'%s: DNS resource record not found' % name1),
),
dict(
desc='Try to delete root zone record \'@\' in %r' % (zone1),
command=('dnsrecord_del', [zone1, u'@'], {'del_all' : True}),
expected=errors.ValidationError(name='del_all',
error=u"Zone record '@' cannot be deleted"),
),
dict(
desc='Create record %r in zone %r' % (zone1, name1),
command=('dnsrecord_add', [zone1, name1], {'arecord': arec2}),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'dn': name1_dn,
'idnsname': [name1_dnsname],
'objectclass': objectclasses.dnsrecord,
'arecord': [arec2],
},
},
),
dict(
desc='Search for all records in zone %r' % zone1,
command=('dnsrecord_find', [zone1], {}),
expected={
'summary': None,
'count': 3,
'truncated': False,
'result': [
{
'dn': zone1_dn,
'nsrecord': nameservers,
'idnsname': [_dns_zone_record],
},
{
'dn': zone1_txtrec_dn,
'txtrecord': [api.env.realm],
'idnsname': [DNSName(u'_kerberos')],
},
{
'dn': name1_dn,
'idnsname': [name1_dnsname],
'arecord': [arec2],
},
],
},
),
dict(
desc='Add A record to %r in zone %r' % (name1, zone1),
command=('dnsrecord_add', [zone1, name1], {'arecord': arec3}),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'dn': name1_dn,
'idnsname': [name1_dnsname],
'arecord': [arec2, arec3],
'objectclass': objectclasses.dnsrecord,
},
},
),
dict(
desc='Remove A record from %r in zone %r' % (name1, zone1),
command=('dnsrecord_del', [zone1, name1], {'arecord': arec2}),
expected={
'value': [name1_dnsname],
'summary': None,
'result': {
'idnsname': [name1_dnsname],
'arecord': [arec3],
},
},
),
dict(
desc='Add AAAA record to %r in zone %r using dnsrecord_mod' % (name1, zone1),
command=('dnsrecord_mod', [zone1, name1], {'aaaarecord': u'::1'}),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'idnsname': [name1_dnsname],
'arecord': [arec3],
'aaaarecord': [u'::1'],
},
},
),
dict(
desc='Try to modify nonexistent record in zone %r' % zone1,
command=('dnsrecord_mod',
[zone1, u'ghostname'],
{'aaaarecord': u'f001:baad::1'}),
expected=errors.NotFound(
reason=u'ghostname: DNS resource record not found'),
),
dict(
desc='Modify AAAA record in %r in zone %r' % (name1, zone1),
command=(
'dnsrecord_mod', [zone1, name1], {'aaaarecord': aaaarec1}
),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'idnsname': [name1_dnsname],
'arecord': [arec3],
'aaaarecord': [aaaarec1],
},
},
),
dict(
desc=('Show record %r in zone %r with --structured and --all '
'options' % (name1, zone1)),
command=('dnsrecord_show', [zone1, name1],
{'structured': True, 'all': True}),
expected=lambda o, x: (
'result' in x and
'dnsrecords' in x['result'] and
(len(x['result']['dnsrecords']) in (1, 2)) and
(any(y[u'dnsdata'] in (aaaarec1, arec3)
for y in x['result']['dnsrecords']))),
),
dict(
desc='Remove AAAA record from %r in zone %r using dnsrecord_mod' % (name1, zone1),
command=('dnsrecord_mod', [zone1, name1], {'aaaarecord': u''}),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'idnsname': [name1_dnsname],
'arecord': [arec3],
},
},
),
dict(
desc='Try to add invalid MX record to zone %r using dnsrecord_add' % (zone1),
command=('dnsrecord_add', [zone1, u'@'], {'mxrecord': zone1_ns }),
expected=errors.ValidationError(name='mx_rec',
error=u'format must be specified as "PREFERENCE EXCHANGER" ' +
u' (see RFC 1035 for details)'),
),
dict(
desc='Add MX record to zone %r using dnsrecord_add' % (zone1),
command=('dnsrecord_add', [zone1, u'@'], {'mxrecord': u"0 %s" % zone1_ns }),
expected={
'value': _dns_zone_record,
'summary': None,
'result': {
'objectclass': objectclasses.dnszone,
'dn': zone1_dn,
'idnsname': [_dns_zone_record],
'mxrecord': [u"0 %s" % zone1_ns],
'nsrecord': nameservers,
},
},
),
dict(
desc='Try to add invalid SRV record to zone %r using dnsrecord_add' % (zone1),
command=('dnsrecord_add', [zone1, u'_foo._tcp'], {'srvrecord': zone1_ns}),
expected=errors.ValidationError(name='srv_rec',
error=u'format must be specified as "PRIORITY WEIGHT PORT TARGET" ' +
u' (see RFC 2782 for details)'),
),
dict(
desc='Try to add SRV record to zone %r both via parts and a raw value' % (zone1),
command=('dnsrecord_add', [zone1, u'_foo._tcp'], {'srv_part_priority': 0,
'srv_part_weight' : 0,
'srv_part_port' : 123,
'srv_part_target' : u'foo.bar.',
'srvrecord': [u"1 100 1234 %s" \
% zone1_ns]}),
expected=lambda x, output: (
type(x) == errors.ValidationError and
str(x).endswith('Raw value of a DNS record was already '
'set by "srv_rec" option'),
),
),
dict(
desc='Add SRV record to zone %r using dnsrecord_add' % (zone1),
command=('dnsrecord_add', [zone1, u'_foo._tcp'], {'srvrecord': u"0 100 1234 %s" % zone1_ns}),
expected={
'value': DNSName(u'_foo._tcp'),
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': DN(('idnsname', u'_foo._tcp'), zone1_dn),
'idnsname': [DNSName(u'_foo._tcp')],
'srvrecord': [u"0 100 1234 %s" % zone1_ns],
},
},
),
dict(
desc='Try to modify SRV record in zone %r without specifying modified value' % (zone1),
command=('dnsrecord_mod', [zone1, u'_foo._tcp'], {'srv_part_priority': 1,}),
expected=errors.RequirementError(name='srv_rec'),
),
dict(
desc='Try to modify SRV record in zone %r with non-existent modified value' % (zone1),
command=('dnsrecord_mod', [zone1, u'_foo._tcp'], {'srv_part_priority': 1,
'srvrecord' : [u"0 100 1234 %s" % absnxname] }),
expected=errors.AttrValueNotFound(attr='SRV record',
value=u'0 100 1234 %s' % absnxname),
),
dict(
desc='Try to modify SRV record in zone %r with invalid part value' % (zone1),
command=('dnsrecord_mod', [zone1, u'_foo._tcp'], {'srv_part_priority': 100000,
'srvrecord' : [u"0 100 1234 %s" % zone1_ns] }),
expected=errors.ValidationError(name='srv_priority', error=u'can be at most 65535'),
),
dict(
desc='Modify SRV record in zone %r using parts' % (zone1),
command=('dnsrecord_mod', [zone1, u'_foo._tcp'], {'srv_part_priority': 1,
'srvrecord' : [u"0 100 1234 %s" % zone1_ns] }),
expected={
'value': DNSName(u'_foo._tcp'),
'summary': None,
'result': {
'idnsname': [DNSName(u'_foo._tcp')],
'srvrecord': [u"1 100 1234 %s" % zone1_ns],
},
},
),
dict(
desc='Try to add invalid LOC record to zone %r using dnsrecord_add' % (zone1),
command=('dnsrecord_add', [zone1, u'@'], {'locrecord': u"91 11 42.4 N 16 36 29.6 E 227.64" }),
expected=errors.ValidationError(name='lat_deg',
error=u'can be at most 90'),
),
dict(
desc='Add LOC record to zone %r using dnsrecord_add' % (zone1),
command=('dnsrecord_add', [zone1, u'@'], {'locrecord': u"49 11 42.4 N 16 36 29.6 E 227.64m 10m 10.0m 0.1"}),
expected={
'value': _dns_zone_record,
'summary': None,
'result': {
'objectclass': objectclasses.dnszone,
'dn': zone1_dn,
'idnsname': [_dns_zone_record],
'mxrecord': [u"0 %s" % zone1_ns],
'nsrecord': nameservers,
'locrecord': [u"49 11 42.400 N 16 36 29.600 E 227.64 10.00 10.00 0.10"],
},
},
),
dict(
desc='Try to add CNAME record to %r using dnsrecord_add' % (name1),
command=('dnsrecord_add', [zone1, name1], {'cnamerecord': absnxname}),
expected=errors.ValidationError(name='cnamerecord',
error=u'CNAME record is not allowed to coexist with any other '
u'record (RFC 1034, section 3.6.2)'),
),
dict(
desc='Try to add multiple CNAME record %r using dnsrecord_add' % (cname),
command=('dnsrecord_add', [zone1, cname], {'cnamerecord':
[u'1.%s' % absnxname, u'2.%s' % absnxname]}),
expected=errors.ValidationError(name='cnamerecord',
error=u'only one CNAME record is allowed per name (RFC 2136, section 1.1.5)'),
),
dict(
desc='Add CNAME record to %r using dnsrecord_add' % (cname),
command=('dnsrecord_add', [zone1, cname], {'cnamerecord': absnxname}),
expected={
'value': cname_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': cname_dn,
'idnsname': [cname_dnsname],
'cnamerecord': [absnxname],
},
},
),
dict(
desc='Try to add other record to CNAME record %r using dnsrecord_add' % (cname),
command=('dnsrecord_add', [zone1, cname], {'arecord': arec1}),
expected=errors.ValidationError(name='cnamerecord',
error=u'CNAME record is not allowed to coexist with any other '
u'record (RFC 1034, section 3.6.2)'),
),
dict(
desc='Try to add other record to CNAME record %r using dnsrecord_mod' % (cname),
command=('dnsrecord_mod', [zone1, cname], {'arecord': arec1}),
expected=errors.ValidationError(name='cnamerecord',
error=u'CNAME record is not allowed to coexist with any other '
u'record (RFC 1034, section 3.6.2)'),
),
dict(
desc='Add A record and delete CNAME record in %r with dnsrecord_mod' % (cname),
command=('dnsrecord_mod', [zone1, cname], {'arecord': arec1,
'cnamerecord': None}),
expected={
'value': cname_dnsname,
'summary': None,
'result': {
'idnsname': [cname_dnsname],
'arecord': [arec1],
},
},
),
dict(
desc='Try to add multiple DNAME records to %r using dnsrecord_add' % (dname),
command=('dnsrecord_add', [zone1, name1], {'dnamerecord':
[u'foo-1.%s' % absnxname, u'foo-2.%s' % absnxname]}),
expected=errors.ValidationError(name='dnamerecord',
error=u'only one DNAME record is allowed per name (RFC 6672, section 2.4)'),
),
dict(
desc='Add DNAME record to %r using dnsrecord_add' % (dname),
command=('dnsrecord_add', [zone1, dname],
{'dnamerecord': u'd.%s' % absnxname, 'arecord': arec1}),
expected={
'value': dname_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': dname_dn,
'idnsname': [dname_dnsname],
'dnamerecord': [u'd.%s' % absnxname],
'arecord': [arec1],
},
},
),
dict(
desc='Try to add CNAME record to %r using dnsrecord_add' % (dname),
command=('dnsrecord_add', [zone1, dname], {'cnamerecord': u'foo-1.%s'
% absnxname}),
expected=errors.ValidationError(name='cnamerecord',
error=u'CNAME record is not allowed to coexist with any other '
u'record (RFC 1034, section 3.6.2)'),
),
dict(
desc='Try to add NS record to %r using dnsrecord_add' % (dname),
command=('dnsrecord_add', [zone1, dname],
{'nsrecord': u'%s.%s.' % (name1, zone1)}),
expected=errors.ValidationError(name='nsrecord',
error=u'NS record is not allowed to coexist with an DNAME '
u'record except when located in a zone root record '
'(RFC 2181, section 6.1)'),
),
dict(
desc='Add NS+DNAME record to %r zone record using dnsrecord_add' % (zone2),
command=('dnsrecord_add', [zone2, u'@'],
{'dnamerecord': u'd.%s' % absnxname,
'nsrecord': zone1_ns, 'force': True}),
expected = {
'value': _dns_zone_record,
'summary': None,
'result': {
'objectclass': objectclasses.dnszone,
'dnamerecord': [u'd.%s' % absnxname],
'dn': zone2_dn,
'nsrecord': [zone1_ns] + nameservers,
'idnsname': [_dns_zone_record]
}
},
),
dict(
desc='Delete zone %r' % zone2,
command=('dnszone_del', [zone2], {}),
expected={
'value': [zone2_absolute_dnsname],
'summary': u'Deleted DNS zone "%s"' % zone2_absolute,
'result': {'failed': []},
},
),
dict(
desc='Try to add invalid KX record %r using dnsrecord_add' % (name1),
command=('dnsrecord_add', [zone1, name1], {'kxrecord': absnxname}),
expected=errors.ValidationError(name='kx_rec',
error=u'format must be specified as "PREFERENCE EXCHANGER" ' +
u' (see RFC 2230 for details)'),
),
dict(
desc='Add KX record to %r using dnsrecord_add' % (name1),
command=('dnsrecord_add', [zone1, name1], {'kxrecord': u'1 foo-1' }),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': name1_dn,
'idnsname': [name1_dnsname],
'arecord': [arec3],
'kxrecord': [u'1 foo-1'],
},
},
),
dict(
desc='Add TXT record to %r using dnsrecord_add' % (name1),
command=('dnsrecord_add', [zone1, name1], {'txtrecord': u'foo bar' }),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': name1_dn,
'idnsname': [name1_dnsname],
'arecord': [arec3],
'kxrecord': [u'1 foo-1'],
'txtrecord': [u'foo bar'],
},
},
),
dict(
desc='Try to add unresolvable absolute NS record to %r using dnsrecord_add' % (name_ns),
command=(
"dnsrecord_add",
[zone1, name_ns],
{"nsrecord": "notexisted.%s" % zone1_absolute},
),
expected=errors.NotFound(
reason=(
"Nameserver '%s' does not have a corresponding A/AAAA "
"record" % "notexisted.%s" % zone1_absolute
),
),
),
dict(
desc='Try to add unresolvable relative NS record to %r using dnsrecord_add' % (name_ns),
command=('dnsrecord_add', [zone1, name_ns], {'nsrecord': relnxname}),
expected=errors.NotFound(reason=u"Nameserver '%s.%s.' does not "
"have a corresponding A/AAAA record" % (relnxname, zone1)),
),
dict(
desc='Add unresolvable NS record with --force to %r using dnsrecord_add' % (name_ns),
command=('dnsrecord_add', [zone1, name_ns], {'nsrecord': absnxname,
'force' : True}),
expected={
'value': name_ns_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': name_ns_dn,
'idnsname': [name_ns_dnsname],
'nsrecord': [absnxname],
},
},
),
dict(
desc='Try to to rename DNS zone %r root record' % (zone1),
command=('dnsrecord_mod', [zone1, u'@'], {'rename': u'renamed-zone',}),
expected=errors.ValidationError(name='rename',
error=u'DNS zone root record cannot be renamed')
),
dict(
desc='Rename DNS record %r to %r' % (name_ns, name_ns_renamed),
command=('dnsrecord_mod', [zone1, name_ns], {'rename': name_ns_renamed,}),
expected={
'value': name_ns_dnsname,
'summary': None,
'result': {
'idnsname': [name_ns_renamed_dnsname],
'nsrecord': [absnxname],
},
},
),
dict(
desc='Delete record %r in zone %r' % (name1, zone1),
command=('dnsrecord_del', [zone1, name1],
{'del_all': True}),
expected={
'value': [name1_dnsname],
'summary': u'Deleted record "%s"' % name1,
'result': {'failed': []},
},
),
dict(
desc='Add DLV record to %r using dnsrecord_add' % (dlv),
command=('dnsrecord_add', [zone1, dlv], {'dlvrecord': dlvrec}),
expected={
'value': dlv_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': dlv_dn,
'idnsname': [dlv_dnsname],
'dlvrecord': [dlvrec],
},
},
),
dict(
desc='Try to add DS record to zone %r apex, using dnsrecord_add' % (zone1),
command=('dnsrecord_add', [zone1, zone1_absolute], {'dsrecord': ds_rec}),
expected=errors.ValidationError(
name="dsrecord",
error=u'DS record must not be in zone apex (RFC 4035 section 2.4)'
),
),
dict(
desc='Try to add DS record %r without NS record in RRset, using dnsrecord_add' % (ds),
command=('dnsrecord_add', [zone1, ds], {'dsrecord': ds_rec}),
expected=errors.ValidationError(
name="dsrecord",
error=u'DS record requires to coexist with an NS record (RFC 4592 section 4.6, RFC 4035 section 2.4)'
),
),
dict(
desc='Add NS record to %r using dnsrecord_add' % (ds),
command=('dnsrecord_add', [zone1, ds],
{'nsrecord': zone1_ns, 'force': True}),
expected={
'value': ds_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': ds_dn,
'idnsname': [ds_dnsname],
'nsrecord': [zone1_ns],
},
},
),
dict(
desc='Add DS record to %r using dnsrecord_add' % (ds),
command=('dnsrecord_add', [zone1, ds],
{'dsrecord': ds_rec}),
expected={
'value': ds_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': ds_dn,
'idnsname': [ds_dnsname],
'nsrecord': [zone1_ns],
'dsrecord': [ds_rec],
},
},
),
dict(
desc='Try to delete NS record (with DS record) %r using dnsrecord_del' % (ds),
command=('dnsrecord_del', [zone1, ds],
{'nsrecord': zone1_ns}),
expected=errors.ValidationError(
name="dsrecord",
error=u'DS record requires to coexist with an NS record (RFC 4592 section 4.6, RFC 4035 section 2.4)'
),
),
dict(
desc='Delete NS+DS record %r in zone %r' % (ds, zone1),
command=('dnsrecord_del', [zone1, ds], {'nsrecord': zone1_ns, 'dsrecord': ds_rec}),
expected={
'value': [ds_dnsname],
'summary': u'Deleted record "%s"' % ds,
'result': {'failed': []},
},
),
dict(
desc='Delete record %r in zone %r' % (dlv, zone1),
command=('dnsrecord_del', [zone1, dlv], {'del_all': True}),
expected={
'value': [dlv_dnsname],
'summary': u'Deleted record "%s"' % dlv,
'result': {'failed': []},
},
),
dict(
desc='Try to add invalid TLSA record to %r using dnsrecord_add (1)' % (tlsa),
command=('dnsrecord_add', [zone1, tlsa], {'tlsarecord': tlsarec_err1}),
expected=errors.ValidationError(
name="cert_usage",
error=u'can be at most 255'
),
),
dict(
desc='Try to add invalid TLSA record to %r using dnsrecord_add (2)' % (tlsa),
command=('dnsrecord_add', [zone1, tlsa], {'tlsarecord': tlsarec_err2}),
expected=errors.ValidationError(
name="selector",
error=u'can be at most 255'
),
),
dict(
desc='Try to add invalid TLSA record to %r using dnsrecord_add (3)' % (tlsa),
command=('dnsrecord_add', [zone1, tlsa], {'tlsarecord': tlsarec_err3}),
expected=errors.ValidationError(
name="matching_type",
error=u'can be at most 255'
),
),
dict(
desc='Add TLSA record to %r using dnsrecord_add' % (tlsa),
command=('dnsrecord_add', [zone1, tlsa], {'tlsarecord': tlsarec_ok}),
expected={
'value': tlsa_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': tlsa_dn,
'idnsname': [tlsa_dnsname],
'tlsarecord': [tlsarec_ok],
},
},
),
dict(
desc='Remove record using dnsrecord-mod %r in zone %r' % (tlsa, zone1),
command=('dnsrecord_mod', [zone1, tlsa], {'tlsarecord': ''}),
expected={
'value': tlsa_dnsname,
'summary': u'Deleted record "%s"' % tlsa,
'result': {'failed': []},
},
),
dict(
desc='Try to create a reverse zone from invalid IP',
command=(
'dnszone_add', [], {
'name_from_ip': u'foo',
'idnssoamname': zone1_ns,
'idnssoarname': zone1_rname,
}
),
expected=errors.ValidationError(name='name_from_ip',
error=u'invalid IP network format'),
),
dict(
desc='Create reverse zone from IP/netmask %r using name_from_ip option' % revzone1_ip,
command=(
'dnszone_add', [], {
'name_from_ip': revzone1_ip,
'idnssoarname': zone1_rname,
}
),
expected={
'value': revzone1_dnsname,
'summary': None,
'result': {
'dn': revzone1_dn,
'idnsname': [revzone1_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-subdomain %(zone)s PTR;'
% dict(realm=api.env.realm, zone=revzone1)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Create reverse zone from IP %r using name_from_ip option' % revzone2_ip,
command=(
'dnszone_add', [], {
'name_from_ip': revzone2_ip,
'idnssoarname': zone1_rname,
}
),
expected={
'value': revzone2_dnsname,
'summary': None,
'result': {
'dn': revzone2_dn,
'idnsname': [revzone2_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-subdomain %(zone)s PTR;'
% dict(realm=api.env.realm, zone=revzone2)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Add PTR record %r to %r using dnsrecord_add' % (revname1, revzone1),
command=('dnsrecord_add', [revzone1, revname1], {'ptrrecord': absnxname}),
expected={
'value': revname1_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': revname1_dn,
'idnsname': [revname1_dnsname],
'ptrrecord': [absnxname],
},
},
),
dict(
desc='Show record %r in zone %r with --structured and --all options'\
% (revname1, revzone1),
command=('dnsrecord_show', [revzone1, revname1],
{'structured': True, 'all': True}),
expected={
'value': revname1_dnsname,
'summary': None,
'result': {
'dn': revname1_dn,
'idnsname': [revname1_dnsname],
'objectclass': objectclasses.dnsrecord,
'dnsrecords': [
{
'dnstype': u'PTR',
'dnsdata': absnxname,
'ptr_part_hostname': absnxname,
},
],
},
},
),
dict(
desc='Update global DNS settings',
command=('dnsconfig_mod', [], {'idnsforwarders' : [fwd_ip],}),
expected={
'value': None,
'summary': None,
u'messages': (
{u'message': lambda x: x.startswith(
u"Forwarding policy conflicts with some "
"automatic empty zones."),
u'code': 13021,
u'type': u'warning',
u'name': u'DNSForwardPolicyConflictWithEmptyZone',
u'data': {}},
{u'message': lambda x: x.startswith(
u"DNS server %s: query '. SOA':" % fwd_ip),
u'code': 13006,
u'type':u'warning',
u'name': u'DNSServerValidationWarning',
u'data': {
u'error': lambda x: x.startswith(u"query '. SOA':"),
u'server': u"%s" % fwd_ip
}},
),
'result': {
'dns_server_server': [api.env.host],
'idnsforwarders': [fwd_ip],
},
},
),
dict(
desc='Update global DNS settings - rollback',
command=('dnsconfig_mod', [], {'idnsforwarders' : None,}),
expected={
'value': None,
'summary': u'Global DNS configuration is empty',
'result': {'dns_server_server': [api.env.host]},
},
),
dict(
desc='Try to add invalid allow-query to zone %r' % zone1,
command=('dnszone_mod', [zone1], {'idnsallowquery': u'foo'}),
expected=errors.ValidationError(name='allow_query',
error=u"failed to detect a valid IP address from 'foo'"),
),
dict(
desc='Add allow-query ACL to zone %r' % zone1,
command=('dnszone_mod', [zone1], {'idnsallowquery': allowquery_restricted_in}),
expected={
'value': zone1_absolute_dnsname,
'summary': None,
'result': {
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'mxrecord': [u'0 ns1.dnszone.test.'],
'locrecord': [u"49 11 42.400 N 16 36 29.600 E 227.64 10.00 10.00 0.10"],
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [u'5478'],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowquery': [allowquery_restricted_out],
'idnsallowtransfer': [u'none;'],
'idnsallowdynupdate': (False,),
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
},
},
),
dict(
desc='Try to add invalid allow-transfer to zone %r' % zone1,
command=('dnszone_mod', [zone1], {'idnsallowtransfer': u'10.'}),
expected=errors.ValidationError(name='allow_transfer',
error=u"failed to detect a valid IP address from '10.'"),
),
dict(
desc='Add allow-transfer ACL to zone %r' % zone1,
command=('dnszone_mod', [zone1], {'idnsallowtransfer': fwd_ip}),
expected={
'value': zone1_absolute_dnsname,
'summary': None,
'result': {
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'mxrecord': [u'0 ns1.dnszone.test.'],
'locrecord': [u"49 11 42.400 N 16 36 29.600 E 227.64 10.00 10.00 0.10"],
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [u'5478'],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowquery': [allowquery_restricted_out],
'idnsallowtransfer': [allowtransfer_tofwd],
'idnsallowdynupdate': (False,),
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
},
},
),
dict(
desc='Set SOA serial of zone %r to high number' % zone1,
command=('dnszone_mod', [zone1], {'idnssoaserial': 4294967295}),
expected=errors.ValidationError(
name='serial',
error=u"this option is deprecated",
),
),
dict(
desc='Try to create duplicate PTR record for %r with --a-create-reverse' % name1,
command=('dnsrecord_add', [zone1, name1], {'arecord': revname1_ip,
'a_extra_create_reverse' : True}),
expected=errors.DuplicateEntry(message=u'Reverse record for IP '
'address %s already exists in reverse zone '
'%s.' % (revname1_ip, revzone1)),
),
dict(
desc='Create A record %r in zone %r with --a-create-reverse' % (name1, zone1),
command=('dnsrecord_add', [zone1, name1], {'arecord': revname2_ip,
'a_extra_create_reverse' : True}),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'dn': name1_dn,
'idnsname': [name1_dnsname],
'objectclass': objectclasses.dnsrecord,
'arecord': [revname2_ip],
},
},
),
dict(
desc='Check reverse record for %r created via --a-create-reverse' % name1,
command=('dnsrecord_show', [revzone1, revname2], {}),
expected={
'value': revname2_dnsname,
'summary': None,
'result': {
'dn': revname2_dn,
'idnsname': [revname2_dnsname],
'ptrrecord': [name1 + '.' + zone1 + '.'],
},
},
),
dict(
desc='Modify ttl of record %r in zone %r' % (name1, zone1),
command=('dnsrecord_mod', [zone1, name1], {'dnsttl': 500}),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'idnsname': [name1_dnsname],
'dnsttl': [u'500'],
'arecord': [revname2_ip],
},
},
),
dict(
desc='Delete ttl of record %r in zone %r' % (name1, zone1),
command=('dnsrecord_mod', [zone1, name1], {'dnsttl': None}),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'idnsname': [name1_dnsname],
'arecord': [revname2_ip],
},
},
),
dict(
desc='Try to add per-zone permission for unknown zone',
command=('dnszone_add_permission', [absnxname], {}),
expected=errors.NotFound(reason=u'%s: DNS zone not found' % absnxname)
),
dict(
desc='Add per-zone permission for zone %r' % zone1,
command=(
'dnszone_add_permission', [zone1], {}
),
expected=dict(
result=True,
value=zone1_permission,
summary=u'Added system permission "%s"' % zone1_permission,
),
),
dict(
desc='Try to add duplicate per-zone permission for zone %r' % zone1,
command=(
'dnszone_add_permission', [zone1], {}
),
expected=errors.DuplicateEntry(message=u'permission with name '
'"%s" already exists' % zone1_permission)
),
dict(
desc='Make sure the permission was created %r' % zone1,
command=(
'permission_show', [zone1_permission], {}
),
expected=dict(
value=zone1_permission,
summary=None,
result={
'dn': zone1_permission_dn,
'cn': [zone1_permission],
'objectclass': objectclasses.system_permission,
'ipapermissiontype': [u'SYSTEM'],
},
),
),
dict(
desc='Retrieve the permission %r with --all --raw' % zone1,
command=(
'permission_show', [zone1_permission], {}
),
expected=dict(
value=zone1_permission,
summary=None,
result={
'dn': zone1_permission_dn,
'cn': [zone1_permission],
'objectclass': objectclasses.system_permission,
'ipapermissiontype': [u'SYSTEM'],
},
),
),
dict(
desc='Try to remove per-zone permission for unknown zone',
command=('dnszone_remove_permission', [absnxname], {}),
expected=errors.NotFound(reason=u'%s: DNS zone not found'
% absnxname)
),
dict(
desc='Remove per-zone permission for zone %r' % zone1,
command=(
'dnszone_remove_permission', [zone1], {}
),
expected=dict(
result=True,
value=zone1_permission,
summary=u'Removed system permission "%s"' % zone1_permission,
),
),
dict(
desc='Make sure the permission for zone %r was deleted' % zone1,
command=(
'permission_show', [zone1_permission], {}
),
expected=errors.NotFound(reason=u'%s: permission not found'
% zone1_permission)
),
dict(
desc='Try to remove non-existent per-zone permission for zone %r' % zone1,
command=(
'dnszone_remove_permission', [zone1], {}
),
expected=errors.NotFound(reason=u'%s: permission not found'
% zone1_permission)
),
dict(
desc=f"Parent zone for {zone3a} tests",
command=(
"dnszone_add", [zone3a], {
"idnssoarname": zone3a_rname,
}
),
expected=lambda x, y: True,
),
dict(
desc="Try to create zone %r with relative nameserver" % zone3a_sub,
command=(
"dnszone_add", [zone3a_sub], {
"idnssoamname": "ns",
"idnssoarname": zone3a_sub_rname,
}
),
expected=errors.NotFound(
reason=(
"Nameserver 'ns.%s' does not have a corresponding A/AAAA "
"record" % zone3a_sub
)
),
),
dict(
desc=(
"Try to create zone %r with nameserver in the zone itself"
% zone3a_sub
),
command=(
"dnszone_add", [zone3a_sub], {
"idnssoamname": zone3a_sub,
"idnssoarname": zone3a_sub_rname,
}
),
expected=errors.NotFound(
reason=(
"Nameserver '%s' does not have a corresponding A/AAAA "
"record" % zone3a_sub
)
),
),
dict(
desc='Create zone %r' % zone3,
command=(
'dnszone_add', [zone3], {
'idnssoarname': zone3_rname,
}
),
expected={
'value': zone3_absolute_dnsname,
'summary': None,
'result': {
'dn': zone3_dn,
'idnsname': [zone3_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone3_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Add A record to %r in zone %r' % (zone3_ns2_arec, zone3),
command=('dnsrecord_add', [zone3, zone3_ns2_arec], {'arecord': zone3_ip2}),
expected={
'value': zone3_ns2_arec_dnsname,
'summary': None,
'result': {
'dn': zone3_ns2_arec_dn,
'idnsname': [zone3_ns2_arec_dnsname],
'arecord': [zone3_ip2],
'objectclass': objectclasses.dnsrecord,
},
},
),
dict(
desc='Create reverse zone %r' % revzone3_classless1,
command=(
'dnszone_add', [revzone3_classless1], {
'idnssoarname': zone3_rname,
}
),
expected={
'value': revzone3_classless1_dnsname,
'summary': None,
'result': {
'dn': revzone3_classless1_dn,
'idnsname': [revzone3_classless1_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone3_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-subdomain %(zone)s PTR;'
% dict(realm=api.env.realm, zone=revzone3_classless1)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Create classless reverse zone %r' % revzone3_classless2,
command=(
'dnszone_add', [revzone3_classless2], {
'idnssoarname': zone3_rname,
}
),
expected={
'value': revzone3_classless2_dnsname,
'summary': None,
'result': {
'dn': revzone3_classless2_dn,
'idnsname': [revzone3_classless2_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone3_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-subdomain %(zone)s PTR;'
% dict(realm=api.env.realm, zone=revzone3_classless2)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc=f"Create zone {zone1!r} specifying the SOA serial",
command=('dnszone_add', [zone1], {'idnssoaserial': 4294967298}),
expected=errors.ValidationError(
name='serial',
error=u"this option is deprecated",
),
),
dict(
desc='Add per-zone permission for classless zone %r' % revzone3_classless2,
command=(
'dnszone_add_permission', [revzone3_classless2], {}
),
expected=dict(
result=True,
value=revzone3_classless2_permission,
summary=u'Added system permission "%s"' % revzone3_classless2_permission,
),
),
dict(
desc='Remove per-zone permission for classless zone %r' % revzone3_classless2,
command=(
'dnszone_remove_permission', [revzone3_classless2], {}
),
expected=dict(
result=True,
value=revzone3_classless2_permission,
summary=u'Removed system permission "%s"' % revzone3_classless2_permission,
),
),
dict(
desc='Add NS record to %r in revzone %r' % (nsrev, revzone3_classless1),
command=('dnsrecord_add', [revzone3_classless1, nsrev], {'nsrecord': zone3_ns2_arec_absolute}),
expected={
'value': nsrev_dnsname,
'summary': None,
'result': {
'dn': nsrev_dn,
'idnsname': [nsrev_dnsname],
'nsrecord': [zone3_ns2_arec_absolute],
'objectclass': objectclasses.dnsrecord,
},
},
),
dict(
desc='Add CNAME record to %r in revzone %r' % (cnamerev, revzone3_classless1),
command=('dnsrecord_add', [revzone3_classless1, cnamerev], {'cnamerecord': cnamerev_hostname}),
expected={
'value': cnamerev_dnsname,
'summary': None,
'result': {
'dn': cnamerev_dn,
'idnsname': [cnamerev_dnsname],
'cnamerecord': [cnamerev_hostname],
'objectclass': objectclasses.dnsrecord,
},
},
),
dict(
desc='Add PTR record to %r in revzone %r' % (ptr_revzone3, revzone3_classless2),
command=('dnsrecord_add', [revzone3_classless2, cnamerev],
{'ptrrecord': ptr_revzone3_hostname}),
expected={
'value': ptr_revzone3_dnsname,
'summary': None,
'result': {
'dn': ptr_revzone3_dn,
'idnsname': [ptr_revzone3_dnsname],
'ptrrecord': [ptr_revzone3_hostname],
'objectclass': objectclasses.dnsrecord,
},
},
),
dict(
desc='Create IDN zone %r' % idnzone1,
command=(
'dnszone_add', [idnzone1], {
'idnssoarname': idnzone1_rname,
}
),
expected={
'value': idnzone1_dnsname,
'summary': None,
'result': {
'dn': idnzone1_dn,
'idnsname': [idnzone1_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [idnzone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Retrieve zone %r' % idnzone1,
command=(
'dnszone_show', [idnzone1], {}
),
expected={
'value': idnzone1_dnsname,
'summary': None,
'result': {
'dn': idnzone1_dn,
'idnsname': [idnzone1_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [idnzone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
},
},
),
dict(
desc='Retrieve zone raw %r' % idnzone1,
command=(
'dnszone_show', [idnzone1], {u'raw' : True,}
),
expected={
'value': idnzone1_dnsname,
'summary': None,
'result': {
'dn': idnzone1_dn,
'idnsname': [idnzone1_punycoded],
'idnszoneactive': ['TRUE'],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns],
'idnssoarname': [idnzone1_rname_punycoded],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': ['FALSE'],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
},
},
),
dict(
desc='Find zone %r' % idnzone1,
command=(
'dnszone_find', [idnzone1], {}
),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [
{ 'dn': idnzone1_dn,
'idnsname': [idnzone1_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [idnzone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self '
u'* AAAA; '
u'grant %(realm)s krb5-self '
u'* SSHFP;'
% dict(realm=api.env.realm)],
},
],
},
),
dict(
desc='Find zone %r raw' % idnzone1_punycoded,
command=(
'dnszone_find', [idnzone1_punycoded], {'raw': True,}
),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [
{ 'dn': idnzone1_dn,
'idnsname': [idnzone1_punycoded],
'idnszoneactive': ['TRUE'],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns],
'idnssoarname': [idnzone1_rname_punycoded],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': ['FALSE'],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self '
u'* AAAA; '
u'grant %(realm)s krb5-self '
u'* SSHFP;'
% dict(realm=api.env.realm)],
},
],
},
),
dict(
desc='Update zone %r' % idnzone1,
command=('dnszone_mod', [idnzone1], {'idnssoarefresh': 5478}),
expected={
'value': idnzone1_dnsname,
'summary': None,
'result': {
'idnsname': [idnzone1_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [idnzone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [u'5478'],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
},
},
),
dict(
desc='Create reverse zone %r' % revidnzone1,
command=(
'dnszone_add', [revidnzone1], {
'idnssoarname': idnzone1_rname,
}
),
expected={
'value': revidnzone1_dnsname,
'summary': None,
'result': {
'dn': revidnzone1_dn,
'idnsname': [revidnzone1_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [idnzone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-subdomain %(zone)s PTR;'
% dict(realm=api.env.realm, zone=revidnzone1)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Delete reverse zone %r' % revidnzone1,
command=('dnszone_del', [revidnzone1], {}),
expected={
'value': [revidnzone1_dnsname],
'summary': u'Deleted DNS zone "%s"' % revidnzone1,
'result': {'failed': []},
},
),
dict(
desc='Search for zones with name %r' % idnzone1,
command=('dnszone_find', [idnzone1], {}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [{
'dn': idnzone1_dn,
'idnsname': [idnzone1_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [idnzone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [u'5478'],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
}],
},
),
dict(
desc='Try to retrieve non-existent record %r in zone %r' % (idnres1, idnzone1),
command=('dnsrecord_show', [idnzone1, idnres1], {}),
expected=errors.NotFound(
reason=u'%s: DNS resource record not found' % idnres1),
),
dict(
desc='Create record %r in zone %r' % (idnzone1, idnres1),
command=('dnsrecord_add', [idnzone1, idnres1], {'arecord': u'127.0.0.1'}),
expected={
'value': idnres1_dnsname,
'summary': None,
'result': {
'dn': idnres1_dn,
'idnsname': [idnres1_dnsname],
'objectclass': objectclasses.dnsrecord,
'arecord': [u'127.0.0.1'],
},
},
),
dict(
desc='Search for all records in zone %r' % idnzone1,
command=('dnsrecord_find', [idnzone1], {}),
expected={
'summary': None,
'count': 2,
'truncated': False,
'result': [
{
'dn': idnzone1_dn,
'nsrecord': nameservers,
'idnsname': [_dns_zone_record],
},
{
'dn': idnres1_dn,
'idnsname': [idnres1_dnsname],
'arecord': [u'127.0.0.1'],
},
],
},
),
dict(
desc='Search for all records in zone %r with --pkey-only' % idnzone1,
command=('dnsrecord_find', [idnzone1], {'pkey_only':True,}),
expected={
'summary': None,
'count': 2,
'truncated': False,
'result': [
{
'dn': idnzone1_dn,
'idnsname': [_dns_zone_record],
},
{
'dn': idnres1_dn,
'idnsname': [idnres1_dnsname],
},
],
},
),
dict(
desc='Find %r record in zone %r' % (idnzone1, idnzone1),
command=('dnsrecord_find', [idnzone1, idnzone1], {}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [
{
'dn': idnzone1_dn,
'nsrecord': nameservers,
'idnsname': [_dns_zone_record],
},
],
},
),
dict(
desc='Find %r record in zone %r' % (idnres1, idnzone1),
command=('dnsrecord_find', [idnzone1, idnres1], {}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [
{
'dn': idnres1_dn,
'idnsname': [idnres1_dnsname],
'arecord': [u'127.0.0.1'],
},
],
},
),
dict(
desc='Find %r record in zone %r with --pkey-only' % (idnres1, idnzone1),
command=('dnsrecord_find', [idnzone1, idnres1], {'pkey_only':True,}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [
{
'dn': idnres1_dn,
'idnsname': [idnres1_dnsname],
},
],
},
),
dict(
desc='Find raw %r record in zone %r with --pkey-only' % (idnres1, idnzone1),
command=('dnsrecord_find', [idnzone1, idnres1],
{'pkey_only' : True, 'raw' : True,}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [
{
'dn': idnres1_dn,
'idnsname': [idnres1_punycoded],
},
],
},
),
dict(
desc='Find raw %r record in zone %r with --pkey-only' % (idnres1_punycoded, idnzone1),
command=('dnsrecord_find', [idnzone1, idnres1_punycoded], {'pkey_only':True, 'raw' : True}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [
{
'dn': idnres1_dn,
'idnsname': [idnres1_punycoded],
},
],
},
),
dict(
desc='Add A record to %r in zone %r' % (idnres1, idnzone1),
command=('dnsrecord_add', [idnzone1, idnres1], {'arecord': u'10.10.0.1'}),
expected={
'value': idnres1_dnsname,
'summary': None,
'result': {
'dn': idnres1_dn,
'idnsname': [idnres1_dnsname],
'arecord': [u'127.0.0.1', u'10.10.0.1'],
'objectclass': objectclasses.dnsrecord,
},
},
),
dict(
desc='Remove A record from %r in zone %r' % (idnres1, idnzone1),
command=('dnsrecord_del', [idnzone1, idnres1], {'arecord': u'127.0.0.1'}),
expected={
'value': [idnres1_dnsname],
'summary': None,
'result': {
'idnsname': [idnres1_dnsname],
'arecord': [u'10.10.0.1'],
},
},
),
dict(
desc='Add MX record to zone %r using dnsrecord_add' % (idnzone1),
command=('dnsrecord_add', [idnzone1, u'@'], {'mxrecord': u"0 %s" % idnzone1_mname }),
expected={
'value': _dns_zone_record,
'summary': None,
'result': {
'objectclass': objectclasses.dnszone,
'dn': idnzone1_dn,
'idnsname': [_dns_zone_record],
'mxrecord': [u"0 %s" % idnzone1_mname],
'nsrecord': nameservers,
},
},
),
#https://fedorahosted.org/freeipa/ticket/4232
dict(
desc='Add MX record (2) to zone %r using dnsrecord_add' % (idnzone1),
command=('dnsrecord_add', [idnzone1, idnzone1], {'mxrecord': u"10 %s" % idnzone1_mname }),
expected={
'value': idnzone1_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnszone,
'dn': idnzone1_dn,
'idnsname': [_dns_zone_record],
'mxrecord': [u"0 %s" % idnzone1_mname, u"10 %s" % idnzone1_mname],
'nsrecord': nameservers,
},
},
),
dict(
desc='Remove MX record (2) from zone %r using dnsrecord_add' % (idnzone1),
command=('dnsrecord_del', [idnzone1, idnzone1], {'mxrecord': u"10 %s" % idnzone1_mname }),
expected={
'value': [idnzone1_dnsname],
'summary': None,
'result': {
'idnsname': [_dns_zone_record],
'mxrecord': [u"0 %s" % idnzone1_mname],
'nsrecord': nameservers,
},
},
),
dict(
desc='Add KX record to zone %r using dnsrecord_add' % (idnzone1),
command=('dnsrecord_add', [idnzone1, u'@'], {'kxrecord': u"0 %s" % idnzone1_mname }),
expected={
'value': _dns_zone_record,
'summary': None,
'result': {
'objectclass': objectclasses.dnszone,
'dn': idnzone1_dn,
'idnsname': [_dns_zone_record],
'mxrecord': [u"0 %s" % idnzone1_mname],
'kxrecord': [u"0 %s" % idnzone1_mname],
'nsrecord': nameservers,
},
},
),
dict(
desc='Retrieve raw zone record of zone %r using dnsrecord_show' % (idnzone1),
command=('dnsrecord_show', [idnzone1, u'@'], {u'raw' : True}),
expected={
'value': _dns_zone_record,
'summary': None,
'result': {
'dn': idnzone1_dn,
'idnsname': [u'@'],
'mxrecord': [u"0 %s" % idnzone1_mname_punycoded],
'kxrecord': [u"0 %s" % idnzone1_mname_punycoded],
'nsrecord': nameservers,
},
},
),
dict(
desc='Add CNAME record to %r using dnsrecord_add' % (idnrescname1),
command=('dnsrecord_add', [idnzone1, idnrescname1], {'cnamerecord': idndomain1 + u'.'}),
expected={
'value': idnrescname1_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': idnrescname1_dn,
'idnsname': [idnrescname1_dnsname],
'cnamerecord': [idndomain1 + u'.'],
},
},
),
dict(
desc='Show raw record %r in zone %r' % (idnrescname1, idnzone1),
command=('dnsrecord_show', [idnzone1, idnrescname1], {u'raw' : True}),
expected={
'value': idnrescname1_dnsname,
'summary': None,
'result': {
'dn': idnrescname1_dn,
'idnsname': [idnrescname1_punycoded],
'cnamerecord': [idndomain1_punycoded + u'.'],
},
},
),
dict(
desc='Add DNAME record to %r using dnsrecord_add' % (idnresdname1),
command=('dnsrecord_add', [idnzone1, idnresdname1], {'dnamerecord': idndomain1 + u'.'}),
expected={
'value': idnresdname1_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': idnresdname1_dn,
'idnsname': [idnresdname1_dnsname],
'dnamerecord': [idndomain1 + u'.'],
},
},
),
dict(
desc='Show raw record %r in zone %r' % (idnresdname1, idnzone1),
command=('dnsrecord_show', [idnzone1, idnresdname1], {u'raw' : True}),
expected={
'value': idnresdname1_dnsname,
'summary': None,
'result': {
'dn': idnresdname1_dn,
'idnsname': [idnresdname1_punycoded],
'dnamerecord': [idndomain1_punycoded + u'.'],
},
},
),
dict(
desc='Add SRV record to zone %r using dnsrecord_add' % (idnzone1),
command=('dnsrecord_add', [idnzone1, u'_foo._tcp'], {'srvrecord': u"0 100 1234 %s" % idnzone1_mname}),
expected={
'value': DNSName(u'_foo._tcp'),
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': DN(('idnsname', u'_foo._tcp'), idnzone1_dn),
'idnsname': [DNSName(u'_foo._tcp')],
'srvrecord': [u"0 100 1234 %s" % idnzone1_mname],
},
},
),
dict(
desc='Show raw record %r in zone %r' % (u'_foo._tcp', idnzone1),
command=('dnsrecord_show', [idnzone1, u'_foo._tcp'], {u'raw' : True}),
expected={
'value': DNSName(u'_foo._tcp'),
'summary': None,
'result': {
'dn': DN(('idnsname', u'_foo._tcp'), idnzone1_dn),
'idnsname': [u'_foo._tcp'],
'srvrecord': [u"0 100 1234 %s" % idnzone1_mname_punycoded],
},
},
),
dict(
desc='Show raw record %r in zone %r' % (u'_foo._tcp', idnzone1_punycoded),
command=('dnsrecord_show', [idnzone1, u'_foo._tcp'], {u'raw' : True}),
expected={
'value': DNSName(u'_foo._tcp'),
'summary': None,
'result': {
'dn': DN(('idnsname', u'_foo._tcp'), idnzone1_dn),
'idnsname': [u'_foo._tcp'],
'srvrecord': [u"0 100 1234 %s" % idnzone1_mname_punycoded],
},
},
),
dict(
desc='Show structured record %r in zone %r' % (
u'_foo._tcp', idnzone1
),
command=(
'dnsrecord_show', [idnzone1, u'_foo._tcp'],
{u'structured': True, u'all': True}
),
expected={
'value': DNSName(u'_foo._tcp'),
'summary': None,
'result': {
'dn': DN(('idnsname', u'_foo._tcp'), idnzone1_dn),
'idnsname': [DNSName(u'_foo._tcp')],
'dnsrecords': [{
u'dnsdata': u'0 100 1234 {}'.format(
idnzone1_mname_punycoded),
u'dnstype': u'SRV',
u'srv_part_port': u'1234',
u'srv_part_priority': u'0',
u'srv_part_target': idnzone1_mname,
u'srv_part_weight': u'100'
}],
'objectclass': objectclasses.dnsrecord,
},
},
),
dict(
desc='Add AFSDB record to %r using dnsrecord_add' % (dnsafsdbres1),
command=('dnsrecord_add', [idnzone1, dnsafsdbres1], {
'afsdb_part_subtype': 0,
'afsdb_part_hostname' : idnzone1_mname}),
expected={
'value': dnsafsdbres1_dnsname,
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': dnsafsdbres1_dn,
'idnsname': [dnsafsdbres1_dnsname],
'afsdbrecord': [u'0 ' + idnzone1_mname],
},
},
),
dict(
desc='Show raw record %r in zone %r' % (dnsafsdbres1, idnzone1),
command=('dnsrecord_show', [idnzone1, dnsafsdbres1], {u'raw' : True}),
expected={
'value': dnsafsdbres1_dnsname,
'summary': None,
'result': {
'dn': dnsafsdbres1_dn,
'idnsname': [dnsafsdbres1_punycoded],
'afsdbrecord': [u'0 ' + idnzone1_mname_punycoded],
},
},
),
dict(
desc='Add A denormalized record in zone %r' % (idnzone1),
command=('dnsrecord_add', [idnzone1, u'gro\xdf'], {'arecord': u'172.16.0.1'}),
expected=errors.ConversionError(name='name',
error=u'domain name \'gro\xdf\' should be normalized to: gross')
),
dict(
desc='Add A record to %r in zone %r' % (wildcard_rec1, zone1),
command=('dnsrecord_add', [zone1, wildcard_rec1], {'arecord': wildcard_rec1_addr}),
expected={
'value': wildcard_rec1_dnsname,
'summary': None,
'result': {
'dn': wildcard_rec1_dn,
'idnsname': [wildcard_rec1_dnsname],
'arecord': [wildcard_rec1_addr],
'objectclass': objectclasses.dnsrecord,
},
},
),
dict(
desc='Resolve name %r (wildcard)' % (wildcard_rec1_test1),
command=('dns_resolve', [wildcard_rec1_test1], {}),
expected={
'result': True,
'summary': "Found '%s'" % wildcard_rec1_test1,
'value': wildcard_rec1_test1,
'messages': ({
'message': u"'dns-resolve' is deprecated. The "
u"command may return an unexpected result, "
u"the resolution of the DNS domain is done "
u"on a randomly chosen IPA server.",
'code': 13015,
'type': u'warning',
'name': u'CommandDeprecatedWarning',
'data': {
'command': u"dns-resolve",
'additional_info': u"The command may return an "
u"unexpected result, the "
u"resolution of the DNS domain "
u"is done on a randomly chosen "
u"IPA server."
}
},)
},
),
dict(
desc='Resolve name %r (wildcard)' % (wildcard_rec1_test2),
command=('dns_resolve', [wildcard_rec1_test2], {}),
expected={
'result': True,
'summary': "Found '%s'" % wildcard_rec1_test2,
'value': wildcard_rec1_test2,
'messages': ({
'message': u"'dns-resolve' is deprecated. The "
u"command may return an unexpected result, "
u"the resolution of the DNS domain is done "
u"on a randomly chosen IPA server.",
'code': 13015,
'type': u'warning',
'name': u'CommandDeprecatedWarning',
'data': {
'command': u"dns-resolve",
'additional_info': u"The command may return an "
u"unexpected result, the "
u"resolution of the DNS domain "
u"is done on a randomly chosen "
u"IPA server."
}
},)
},
),
dict(
desc='Try to add NS record to wildcard owner %r in zone %r' % (wildcard_rec1, zone1),
command=('dnsrecord_add', [zone1, wildcard_rec1], {'nsrecord': zone2_ns, 'force': True}),
expected=errors.ValidationError(
name='idnsname',
error=(u'owner of DNAME, DS, NS records '
'should not be a wildcard domain name (RFC 4592 section 4)')
)
),
dict(
desc='Try to add DNAME record to wildcard owner %r in zone %r' % (wildcard_rec1, zone1),
command=('dnsrecord_add', [zone1, wildcard_rec1], {'dnamerecord': u'dname.test.'}),
expected=errors.ValidationError(
name='idnsname',
error=(u'owner of DNAME, DS, NS records '
'should not be a wildcard domain name (RFC 4592 section 4)')
)
),
dict(
desc='Try to add DS record to wildcard owner %r in zone %r' % (wildcard_rec1, zone1),
command=('dnsrecord_add', [zone1, wildcard_rec1], {'dsrecord': u'0 0 0 00'}),
expected=errors.ValidationError(
name='idnsname',
error=(u'owner of DNAME, DS, NS records '
'should not be a wildcard domain name (RFC 4592 section 4)')
)
),
dict(
desc='Disable zone %r' % zone1,
command=('dnszone_disable', [zone1], {}),
expected={
'value': zone1_absolute_dnsname,
'summary': u'Disabled DNS zone "%s"' % zone1_absolute,
'result': True,
},
),
dict(
desc='Check if zone %r is really disabled' % zone1,
command=('dnszone_show', [zone1], {}),
expected={
'value': zone1_absolute_dnsname,
'summary': None,
'result': {
'dn': zone1_dn,
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [False],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'172.16.31.80;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowquery': [allowquery_restricted_out],
'mxrecord': [u'0 ns1.dnszone.test.'],
'locrecord': [u"49 11 42.400 N 16 36 29.600 E 227.64 10.00 10.00 0.10"],
},
},
),
dict(
desc='Enable zone %r' % zone1,
command=('dnszone_enable', [zone1], {}),
expected={
'value': zone1_absolute_dnsname,
'summary': u'Enabled DNS zone "%s"' % zone1_absolute,
'result': True,
},
),
dict(
desc='Check if zone %r is really enabled' % zone1,
command=('dnszone_show', [zone1_absolute], {}),
expected={
'value': zone1_absolute_dnsname,
'summary': None,
'result': {
'dn': zone1_dn,
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [zone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'172.16.31.80;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowquery': [allowquery_restricted_out],
'mxrecord': [u'0 ns1.dnszone.test.'],
'locrecord': [u"49 11 42.400 N 16 36 29.600 E 227.64 10.00 10.00 0.10"],
},
},
),
dict(
desc='Disable zone %r' % idnzone1,
command=('dnszone_disable', [idnzone1], {}),
expected={
'value': idnzone1_dnsname,
'summary': u'Disabled DNS zone "%s"' % idnzone1,
'result': True,
},
),
dict(
desc='Check if zone %r is really disabled' % idnzone1,
command=('dnszone_show', [idnzone1], {}),
expected={
'value': idnzone1_dnsname,
'summary': None,
'result': {
'dn': idnzone1_dn,
'idnsname': [idnzone1_dnsname],
'idnszoneactive': [False],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [idnzone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowquery': [u'any;'],
'mxrecord': [u"0 %s" % idnzone1_mname],
'kxrecord': [u"0 %s" % idnzone1_mname],
},
},
),
dict(
desc='Enable zone %r' % idnzone1,
command=('dnszone_enable', [idnzone1], {}),
expected={
'value': idnzone1_dnsname,
'summary': u'Enabled DNS zone "%s"' % idnzone1,
'result': True,
},
),
dict(
desc='Check if zone %r is really enabled' % idnzone1,
command=('dnszone_show', [idnzone1], {}),
expected={
'value': idnzone1_dnsname,
'summary': None,
'result': {
'dn': idnzone1_dn,
'idnsname': [idnzone1_dnsname],
'idnszoneactive': [True],
'nsrecord': nameservers,
'idnssoamname': [self_server_ns_dnsname],
'idnssoarname': [idnzone1_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowquery': [u'any;'],
'mxrecord': [u"0 %s" % idnzone1_mname],
'kxrecord': [u"0 %s" % idnzone1_mname],
},
},
),
dict(
desc='Add PTR record in a non-.arpa zone [DNS-SD]',
command=(
'dnsrecord_add',
[zone1, '_http._tcp'],
{'ptrrecord': 'home._http._tcp'},
),
expected={
'value': DNSName('_http._tcp'),
'summary': None,
'result': {
'dn': DN(('idnsname', '_http._tcp'), zone1_dn),
'idnsname': [DNSName('_http._tcp')],
'ptrrecord': ['home._http._tcp'],
'objectclass': objectclasses.dnsrecord,
},
},
),
dict(
desc='Delete zone %r' % zone1,
command=('dnszone_del', [zone1], {}),
expected={
'value': [zone1_absolute_dnsname],
'summary': u'Deleted DNS zone "%s"' % zone1_absolute,
'result': {'failed': []},
},
),
]
@pytest.mark.tier1
class test_root_zone(Declarative):
@pytest.fixture(autouse=True, scope="class")
def root_zone_setup(self, declarative_setup):
if not api.Backend.rpcclient.isconnected():
api.Backend.rpcclient.connect()
if not have_ldap2:
pytest.skip('server plugin not available')
if get_nameservers_error is not None:
pytest.skip(
'unable to get list of nameservers (%s)' %
get_nameservers_error
)
try:
api.Command['dnszone_add'](zone1, idnssoarname=zone1_rname,)
api.Command['dnszone_del'](zone1)
except errors.NotFound:
pytest.skip('DNS is not configured')
except errors.DuplicateEntry:
pass
cleanup_commands = [
('dnszone_del', [zone_root, ],
{'continue': True}),
('permission_del', [zone_root_permission, ], {'force': True}),
]
tests = [
dict(
desc='Create zone %r' % zone_root,
command=(
'dnszone_add', [zone_root], {
'idnssoarname': zone_root_rname,
'skip_overlap_check': True
}
),
expected={
'value': zone_root_dnsname,
'summary': None,
'result': {
'dn': zone_root_dn,
'idnsname': [zone_root_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone_root_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Add per-zone permission for zone %r' % zone_root,
command=(
'dnszone_add_permission', [zone_root], {}
),
expected=dict(
result=True,
value=zone_root_permission,
summary=u'Added system permission "%s"' % zone_root_permission,
),
),
]
@pytest.mark.tier1
class test_forward_zones(Declarative):
# https://fedorahosted.org/freeipa/ticket/4750
@pytest.fixture(autouse=True, scope="class")
def forward_zone_setup(self, declarative_setup):
if not api.Backend.rpcclient.isconnected():
api.Backend.rpcclient.connect()
if not have_ldap2:
pytest.skip('server plugin not available')
try:
api.Command['dnszone_add'](zone1, idnssoarname=zone1_rname,)
api.Command['dnszone_del'](zone1)
except errors.NotFound:
pytest.skip('DNS is not configured')
except errors.DuplicateEntry:
pass
cleanup_commands = [
('dnsforwardzone_del', [zone_fw_wildcard, fwzone1, fwzone2, fwzone3],
{'continue': True}),
('permission_del', [fwzone1_permission, ], {'force': True}),
]
tests = [
dict(
desc='Search for forward zone with --forward-policy=none (no zones)',
command=('dnsforwardzone_find', [], {'idnsforwardpolicy': u'none'}),
expected={
'summary': None,
'count': 0,
'truncated': False,
'result': [],
},
),
dict(
desc='Search for forward zone with --forward-policy=only (no zones)',
command=('dnsforwardzone_find', [], {'idnsforwardpolicy': u'only'}),
expected={
'summary': None,
'count': 0,
'truncated': False,
'result': [],
},
),
dict(
desc='Search for forward zone with --forward-policy=first (no zones)',
command=('dnsforwardzone_find', [], {'idnsforwardpolicy': u'first'}),
expected={
'summary': None,
'count': 0,
'truncated': False,
'result': [],
},
),
dict(
desc='Try to create forward zone %r with wildcard domain name' % zone_fw_wildcard,
command=(
'dnsforwardzone_add', [zone_fw_wildcard], {'idnsforwardpolicy': u'none'}
),
expected=errors.ValidationError(name='name',
error=u'should not be a wildcard domain name (RFC 4592 section 4)')
),
dict(
desc='Try to create forward zone with empty name',
command=(
'dnsforwardzone_add', [u''], {}
),
expected=errors.RequirementError(name='name')
),
dict(
desc='Try to create forward zone %r with invalid name' % 'invalid..name.fwzone.test.',
command=(
'dnsforwardzone_add', [u'invalid..name.fwzone.test.', ], {}
),
expected=errors.ConversionError(
name='name',
error=u'empty DNS label')
),
dict(
desc='Try to create forward zone %r without forwarders with default "(first)" policy' % fwzone1,
command=(
'dnsforwardzone_add', [fwzone1], {}
),
expected=errors.ValidationError(name='idnsforwarders',
error=u'Please specify forwarders.')
),
dict(
desc='Try to create forward zone %r without forwarders with "only" policy' % fwzone1,
command=(
'dnsforwardzone_add', [fwzone1], {'idnsforwardpolicy': u'only'}
),
expected=errors.ValidationError(name='idnsforwarders',
error=u'Please specify forwarders.')
),
dict(
desc='Try to create forward zone %r without forwarders with "first" policy' % fwzone1,
command=(
'dnsforwardzone_add', [fwzone1], {'idnsforwardpolicy': u'first'}
),
expected=errors.ValidationError(
name='idnsforwarders',
error=u'Please specify forwarders.')
),
dict(
desc='Try to create forward zone %r with "only" policy and invalid IP address' % fwzone1,
command=(
'dnsforwardzone_add', [fwzone1], {
'idnsforwardpolicy': u'only',
'idnsforwarders': [u'127.0.0.999', ]
}
),
expected=errors.ValidationError(
name='forwarder',
error=u'invalid IP address format')
),
dict(
desc='Try to create forward zone %r with "first" policy and invalid IP address' % fwzone1,
command=(
'dnsforwardzone_add', [fwzone1], {
'idnsforwardpolicy': u'first',
'idnsforwarders': [u'127.0.0.999', ]
}
),
expected=errors.ValidationError(
name='forwarder',
error=u'invalid IP address format')
),
dict(
desc='Try to create forward zone %r with invalid policy' % fwzone1,
command=(
'dnsforwardzone_add', [fwzone1], {
'idnsforwardpolicy': u'invalid',
}
),
expected=errors.ValidationError(
name='forward_policy',
error=u"must be one of 'only', 'first', 'none'")
),
dict(
desc='Create forward zone %r without forwarders with "none" policy' % fwzone1,
command=(
'dnsforwardzone_add', [fwzone1], {'idnsforwardpolicy': u'none'}
),
expected={
'value': fwzone1_dnsname,
'summary': None,
'result': {
'dn': fwzone1_dn,
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
'objectclass': objectclasses.dnsforwardzone,
},
},
),
dict(
desc='Try to create duplicate forward zone %r' % fwzone1,
command=(
'dnsforwardzone_add', [fwzone1], {'idnsforwardpolicy': u'none'}
),
expected=errors.DuplicateEntry(
message=u'DNS forward zone with name "%s" already exists' % fwzone1),
),
dict(
desc='Create forward zone %r with forwarders with default ("first") policy' % fwzone2,
command=(
'dnsforwardzone_add', [fwzone2], {'idnsforwarders': [forwarder1]}
),
expected={
'value': fwzone2_dnsname,
'summary': None,
u'messages': ({u'message': lambda x: x.startswith(
u"DNS server %s: query '%s SOA':" %
(forwarder1, fwzone2)),
u'code': 13006,
u'type':u'warning',
u'name': u'DNSServerValidationWarning',
u'data': {
u'error': lambda x: x.startswith(
u"query '%s SOA':" % fwzone2),
u'server': u"%s" % forwarder1
}},
),
'result': {
'dn': fwzone2_dn,
'idnsname': [fwzone2_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder1],
'objectclass': objectclasses.dnsforwardzone,
},
},
),
dict(
desc='Delete forward zone %r (cleanup)' % fwzone2,
command=('dnsforwardzone_del', [fwzone2], {}),
expected={
'value': [fwzone2_dnsname],
'summary': u'Deleted DNS forward zone "%s"' % fwzone2,
'result': {'failed': []},
},
),
dict(
desc='Create forward zone %r with three forwarders with "only" policy' % fwzone2,
command=(
'dnsforwardzone_add', [fwzone2], {
'idnsforwarders': [forwarder1, forwarder2, forwarder3],
'idnsforwardpolicy': u'only'
}
),
expected={
'value': fwzone2_dnsname,
'summary': None,
'messages': lambda x: True, # fake forwarders - ignore message
'result': {
'dn': fwzone2_dn,
'idnsname': [fwzone2_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'only'],
'idnsforwarders': [forwarder1, forwarder2, forwarder3],
'objectclass': objectclasses.dnsforwardzone,
},
},
),
dict(
desc='Delete forward zone %r (cleanup)' % fwzone2,
command=('dnsforwardzone_del', [fwzone2], {}),
expected={
'value': [fwzone2_dnsname],
'summary': u'Deleted DNS forward zone "%s"' % fwzone2,
'result': {'failed': []},
},
),
dict(
desc='Create forward zone %r with one forwarder with "only" policy' % fwzone2,
command=(
'dnsforwardzone_add', [fwzone2], {
'idnsforwarders': forwarder2, 'idnsforwardpolicy': u'only'
}
),
expected={
'value': fwzone2_dnsname,
'summary': None,
'messages': lambda x: True, # fake forwarders - ignore message
'result': {
'dn': fwzone2_dn,
'idnsname': [fwzone2_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'only'],
'idnsforwarders': [forwarder2],
'objectclass': objectclasses.dnsforwardzone,
},
},
),
dict(
desc='Create forward zone %r with three forwarders with "first" policy' % fwzone3,
command=(
'dnsforwardzone_add', [fwzone3], {
'idnsforwarders': [forwarder1, forwarder2, forwarder3],
'idnsforwardpolicy': u'first'
}
),
expected={
'value': fwzone3_dnsname,
'summary': None,
'messages': lambda x: True, # fake forwarders - ignore message
'result': {
'dn': fwzone3_dn,
'idnsname': [fwzone3_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder1, forwarder2, forwarder3],
'objectclass': objectclasses.dnsforwardzone,
},
},
),
dict(
desc='Delete forward zone %r (cleanup)' % fwzone3,
command=('dnsforwardzone_del', [fwzone3], {}),
expected={
'value': [fwzone3_dnsname],
'summary': u'Deleted DNS forward zone "%s"' % fwzone3,
'result': {'failed': []},
},
),
dict(
desc='Create forward zone %r with one forwarder with "first" policy' % fwzone3,
command=(
'dnsforwardzone_add', [fwzone3], {
'idnsforwarders': forwarder3, 'idnsforwardpolicy': u'first'
}
),
expected={
'value': fwzone3_dnsname,
'summary': None,
'messages': lambda x: True, # fake forwarders - ignore message
'result': {
'dn': fwzone3_dn,
'idnsname': [fwzone3_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder3],
'objectclass': objectclasses.dnsforwardzone,
},
},
),
dict(
desc='Modify forward zone %r change one forwarder' % fwzone3,
command=(
'dnsforwardzone_mod', [fwzone3], {
'idnsforwarders': forwarder1,
}
),
expected={
'value': fwzone3_dnsname,
'summary': None,
'messages': lambda x: True, # fake forwarders - ignore message
'result': {
'idnsname': [fwzone3_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder1],
},
},
),
dict(
desc='Modify forward zone %r add one forwarder' % fwzone3,
command=(
'dnsforwardzone_mod', [fwzone3], {
'idnsforwarders': [forwarder1, forwarder2]
}
),
expected={
'value': fwzone3_dnsname,
'summary': None,
'messages': lambda x: True, # fake forwarders - ignore message
'result': {
'idnsname': [fwzone3_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder1, forwarder2],
},
},
),
dict(
desc='Modify forward zone %r change one forwarder if two exists' % fwzone3,
command=(
'dnsforwardzone_mod', [fwzone3], {
'idnsforwarders': [forwarder1, forwarder3]
}
),
expected={
'value': fwzone3_dnsname,
'summary': None,
'messages': lambda x: True, # fake forwarders - ignore message
'result': {
'idnsname': [fwzone3_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder1, forwarder3],
},
},
),
dict(
desc='Modify forward zone %r change two forwarders if two exists' % fwzone3,
command=(
'dnsforwardzone_mod', [fwzone3], {
'idnsforwarders': [forwarder2, forwarder4]
}
),
expected={
'value': fwzone3_dnsname,
'summary': None,
'messages': lambda x: True, # fake forwarders - ignore message
'result': {
'idnsname': [fwzone3_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder2, forwarder4],
},
},
),
dict(
desc='Modify forward zone %r with --policy=none, add forwarders' % fwzone1,
command=(
'dnsforwardzone_mod', [fwzone1], {
'idnsforwardpolicy': u'none',
'idnsforwarders': [forwarder3],
}
),
expected={
'value': fwzone1_dnsname,
'summary': None,
'messages': lambda x: True, # fake forwarders - ignore message
'result': {
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
'idnsforwarders': [forwarder3],
},
},
),
dict(
desc='Modify forward zone %r change --policy=none' % fwzone2,
command=(
'dnsforwardzone_mod', [fwzone2], {
'idnsforwardpolicy': u'none',
}
),
expected={
'value': fwzone2_dnsname,
'summary': None,
'result': {
'idnsname': [fwzone2_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
'idnsforwarders': [forwarder2],
},
},
),
dict(
desc='Modify forward zone %r change --policy=only (was "none", FW exists)' % fwzone2,
command=(
'dnsforwardzone_mod', [fwzone2], {
'idnsforwardpolicy': u'only',
}
),
expected={
'value': fwzone2_dnsname,
'summary': None,
'result': {
'idnsname': [fwzone2_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'only'],
'idnsforwarders': [forwarder2],
},
},
),
dict(
desc='Modify forward zone %r with --policy=first (was "none", FW exists)' % fwzone1,
command=(
'dnsforwardzone_mod', [fwzone1], {
'idnsforwardpolicy': u'first',
'idnsforwarders': [forwarder3],
}
),
expected={
'value': fwzone1_dnsname,
'summary': None,
'messages': lambda x: True, # fake forwarders - ignore message
'result': {
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder3],
},
},
),
dict(
desc='Modify forward zone %r with --policy=none, forwarder empty' % fwzone1,
command=(
'dnsforwardzone_mod', [fwzone1], {
'idnsforwardpolicy': u'none',
'idnsforwarders': [],
}
),
expected={
'value': fwzone1_dnsname,
'summary': None,
'result': {
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
},
},
),
dict(
desc='Modify forward zone %r --policy=only, add forwarders"' % fwzone1,
command=(
'dnsforwardzone_mod', [fwzone1], {
'idnsforwardpolicy': u'only',
'idnsforwarders': [forwarder1, forwarder2]
}
),
expected={
'value': fwzone1_dnsname,
'summary': None,
'messages': lambda x: True, # fake forwarders - ignore message
'result': {
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'only'],
'idnsforwarders': [forwarder1, forwarder2],
},
},
),
dict(
desc='Modify forward zone %r --policy=first (was "only")' % fwzone1,
command=(
'dnsforwardzone_mod', [fwzone1], {
'idnsforwardpolicy': u'first',
}
),
expected={
'value': fwzone1_dnsname,
'summary': None,
'result': {
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder1, forwarder2],
},
},
),
dict(
desc='Modify forward zone %r --policy=only (was "first")' % fwzone1,
command=(
'dnsforwardzone_mod', [fwzone1], {
'idnsforwardpolicy': u'only',
}
),
expected={
'value': fwzone1_dnsname,
'summary': None,
'result': {
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'only'],
'idnsforwarders': [forwarder1, forwarder2],
},
},
),
dict(
desc='Modify forward zone %r with --policy=none, forwarder empty (cleanup)' % fwzone1,
command=(
'dnsforwardzone_mod', [fwzone1], {
'idnsforwardpolicy': u'none',
'idnsforwarders': [],
}
),
expected={
'value': fwzone1_dnsname,
'summary': None,
'result': {
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
},
},
),
dict(
desc='Try to modify non-existent forward zone %r' % nonexistent_fwzone,
command=(
'dnsforwardzone_mod', [nonexistent_fwzone], {
'idnsforwardpolicy': u'only'
}
),
expected=errors.NotFound(reason="%s: DNS forward zone not found" %
nonexistent_fwzone)
),
dict(
desc='Try to modify forward zone %r without forwarders with "only" policy' % fwzone1,
command=(
'dnsforwardzone_mod', [fwzone1], {
'idnsforwardpolicy': u'only'
}
),
expected=errors.ValidationError(name='idnsforwarders',
error=u'Please specify forwarders.')
),
dict(
desc='Try to modify forward zone %r without forwarders with "first" policy' % fwzone1,
command=(
'dnsforwardzone_mod', [fwzone1], {
'idnsforwardpolicy': u'first'
}
),
expected=errors.ValidationError(name='idnsforwarders',
error=u'Please specify forwarders.')
),
dict(
desc='Try to modify forward zone %r with "only" policy change empty forwarders' % fwzone2,
command=(
'dnsforwardzone_mod', [fwzone2], {
'idnsforwarders': [],
}
),
expected=errors.ValidationError(
name='idnsforwarders',
error=u'Please specify forwarders.')
),
dict(
desc='Try to modify forward zone %r with "first" policy change empty forwarders' % fwzone3,
command=(
'dnsforwardzone_mod', [fwzone3], {
'idnsforwarders': [],
}
),
expected=errors.ValidationError(
name='idnsforwarders',
error=u'Please specify forwarders.')
),
dict(
desc='Try to modify forward zone %r with "only" policy change invalid forwarder IP' % fwzone2,
command=(
'dnsforwardzone_mod', [fwzone2], {
'idnsforwarders': [u'127.0.0.999', ],
}
),
expected=errors.ValidationError(
name='forwarder',
error=u'invalid IP address format')
),
dict(
desc='Try to modify forward zone %r with "first" policy change invalid forwarder IP' % fwzone3,
command=(
'dnsforwardzone_mod', [fwzone3], {
'idnsforwarders': [u'127.0.0.999', ],
}
),
expected=errors.ValidationError(
name='forwarder',
error=u'invalid IP address format')
),
dict(
desc='Try to modify forward zone %r with invalid policy' % fwzone1,
command=(
'dnsforwardzone_mod', [fwzone1], {
'idnsforwardpolicy': u'invalid',
}
),
expected=errors.ValidationError(
name='forward_policy',
error=u"must be one of 'only', 'first', 'none'")
),
dict(
desc='Retrieve forward zone %r' % fwzone1,
command=(
'dnsforwardzone_show', [fwzone1], {}
),
expected={
'value': fwzone1_dnsname,
'summary': None,
'result': {
'dn': fwzone1_dn,
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
},
},
),
dict(
desc='Try to retrieve nonexistent forward zone %r' % nonexistent_fwzone,
command=(
'dnsforwardzone_show', [nonexistent_fwzone], {}
),
expected=errors.NotFound(reason="%s: DNS forward zone not found" %
nonexistent_fwzone)
),
dict(
desc='Search for all forward zones',
command=('dnsforwardzone_find', [], {}),
expected={
'summary': None,
'count': 3,
'truncated': False,
'result': [
{
'dn': fwzone1_dn,
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
},
{
'dn': fwzone2_dn,
'idnsname': [fwzone2_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'only'],
'idnsforwarders': [forwarder2],
},
{
'dn': fwzone3_dn,
'idnsname': [fwzone3_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder2, forwarder4],
},
],
},
),
dict(
desc='Search for all forward zones with --pkey-only',
command=('dnsforwardzone_find', [], {'pkey_only': True}),
expected={
'summary': None,
'count': 3,
'truncated': False,
'result': [
{
'dn': fwzone1_dn,
'idnsname': [fwzone1_dnsname],
},
{
'dn': fwzone2_dn,
'idnsname': [fwzone2_dnsname],
},
{
'dn': fwzone3_dn,
'idnsname': [fwzone3_dnsname],
},
],
},
),
dict(
desc='Search for forward zone %r' % fwzone1,
command=('dnsforwardzone_find', [fwzone1], {}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [{
'dn': fwzone1_dn,
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
}],
},
),
dict(
desc='Search for 3 forward zones search with criteria "%r"' % fwzone_search_all_name,
command=('dnsforwardzone_find', [fwzone_search_all_name], {}),
expected={
'summary': None,
'count': 3,
'truncated': False,
'result': [
{
'dn': fwzone1_dn,
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
},
{
'dn': fwzone2_dn,
'idnsname': [fwzone2_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'only'],
'idnsforwarders': [forwarder2],
},
{
'dn': fwzone3_dn,
'idnsname': [fwzone3_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder2, forwarder4],
},
],
},
),
dict(
desc='Search for forward zone with --name %r' % fwzone1,
command=('dnsforwardzone_find', [], {'idnsname': fwzone1}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [
{
'dn': fwzone1_dn,
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
}
],
},
),
dict(
desc='Search for forward zone with --forward-policy=none',
command=('dnsforwardzone_find', [], {'idnsforwardpolicy': u'none'}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [
{
'dn': fwzone1_dn,
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
}
],
},
),
dict(
desc='Search for forward zone with --forward-policy=only',
command=('dnsforwardzone_find', [], {'idnsforwardpolicy': u'only'}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [
{
'dn': fwzone2_dn,
'idnsname': [fwzone2_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'only'],
'idnsforwarders': [forwarder2],
}
],
},
),
dict(
desc='Search for forward zone with --forward-policy=first',
command=('dnsforwardzone_find', [], {'idnsforwardpolicy': u'first'}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [
{
'dn': fwzone3_dn,
'idnsname': [fwzone3_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder2, forwarder4],
}
],
},
),
dict(
desc='Try to search for non-existent forward zone',
command=('dnsforwardzone_find', [nonexistent_fwzone], {}),
expected={
'summary': None,
'count': 0,
'truncated': False,
'result': [],
},
),
dict(
desc='Try to search for non-existent forward zone with --name',
command=('dnsforwardzone_find', [], {'idnsname': nonexistent_fwzone}),
expected={
'summary': None,
'count': 0,
'truncated': False,
'result': [],
},
),
dict(
desc='Delete forward zone %r' % fwzone2,
command=('dnsforwardzone_del', [fwzone2], {}),
expected={
'value': [fwzone2_dnsname],
'summary': u'Deleted DNS forward zone "%s"' % fwzone2,
'result': {'failed': []},
},
),
dict(
desc='Delete forward zone %r with --continue' % fwzone3,
command=('dnsforwardzone_del', [fwzone3], {'continue': True}),
expected={
'value': [fwzone3_dnsname],
'summary': u'Deleted DNS forward zone "%s"' % fwzone3,
'result': {'failed': []},
},
),
dict(
desc='Try to delete non-existent forward zone',
command=('dnsforwardzone_del', [nonexistent_fwzone], {}),
expected=errors.NotFound(reason="%s: DNS forward zone not found" %
nonexistent_fwzone)
),
dict(
desc='Try to delete non-existent forward zone with --continue',
command=('dnsforwardzone_del', [nonexistent_fwzone], {'continue': True}),
expected={
'value': [],
'summary': u'Deleted DNS forward zone ""',
'result': {
'failed': [nonexistent_fwzone_dnsname],
}
}
),
dict(
desc='Try to add per-zone permission for unknown forward zone',
command=('dnsforwardzone_add_permission', [absnxname], {}),
expected=errors.NotFound(reason=u'%s: DNS forward zone not found' % absnxname)
),
dict(
desc='Add per-zone permission for forward zone %r' % fwzone1,
command=(
'dnsforwardzone_add_permission', [fwzone1], {}
),
expected=dict(
result=True,
value=fwzone1_permission,
summary=u'Added system permission "%s"' % fwzone1_permission,
),
),
dict(
desc='Try to add duplicate per-zone permission for forward zone %r' % fwzone1,
command=(
'dnsforwardzone_add_permission', [fwzone1], {}
),
expected=errors.DuplicateEntry(message=u'permission with name '
'"%s" already exists' % fwzone1_permission)
),
dict(
desc='Make sure the permission was created %r' % fwzone1,
command=(
'permission_show', [fwzone1_permission], {}
),
expected=dict(
value=fwzone1_permission,
summary=None,
result={
'dn': fwzone1_permission_dn,
'cn': [fwzone1_permission],
'objectclass': objectclasses.system_permission,
'ipapermissiontype': [u'SYSTEM'],
},
),
),
dict(
desc='Retrieve the permission %r with --all --raw' % fwzone1,
command=(
'permission_show', [fwzone1_permission], {}
),
expected=dict(
value=fwzone1_permission,
summary=None,
result={
'dn': fwzone1_permission_dn,
'cn': [fwzone1_permission],
'objectclass': objectclasses.system_permission,
'ipapermissiontype': [u'SYSTEM'],
},
),
),
dict(
desc='Try to remove per-zone permission for unknown forward zone',
command=('dnsforwardzone_remove_permission', [absnxname], {}),
expected=errors.NotFound(reason=u'%s: DNS forward zone not found'
% absnxname)
),
dict(
desc='Remove per-zone permission for forward zone %r' % fwzone1,
command=(
'dnsforwardzone_remove_permission', [fwzone1], {}
),
expected=dict(
result=True,
value=fwzone1_permission,
summary=u'Removed system permission "%s"' % fwzone1_permission,
),
),
dict(
desc='Make sure the permission for forward zone %r was deleted' % fwzone1,
command=(
'permission_show', [fwzone1_permission], {}
),
expected=errors.NotFound(reason=u'%s: permission not found'
% fwzone1_permission)
),
dict(
desc='Try to remove per-zone permission for forward zone %r (permission does not exist)' % fwzone1,
command=(
'dnsforwardzone_remove_permission', [fwzone1], {}
),
expected=errors.NotFound(reason=u'%s: permission not found'
% fwzone1_permission)
),
dict(
desc='Disable forward zone %r' % fwzone1,
command=('dnsforwardzone_disable', [fwzone1], {}),
expected={
'value': fwzone1_dnsname,
'summary': u'Disabled DNS forward zone "%s"' % fwzone1,
'result': True,
},
),
dict(
desc='Check if forward zone %r is really disabled' % fwzone1,
command=('dnsforwardzone_show', [fwzone1], {}),
expected={
'value': fwzone1_dnsname,
'summary': None,
'result': {
'dn': fwzone1_dn,
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [False],
'idnsforwardpolicy': [u'none'],
},
},
),
dict(
desc='Disable already disabled forward zone %r' % fwzone1,
command=('dnsforwardzone_disable', [fwzone1], {}),
expected={
'value': fwzone1_dnsname,
'summary': u'Disabled DNS forward zone "%s"' % fwzone1,
'result': True,
},
),
dict(
desc='Try to disable non-existent forward zone',
command=('dnsforwardzone_disable', [nonexistent_fwzone], {}),
expected=errors.NotFound(
reason=u'%s: DNS forward zone not found' % nonexistent_fwzone
)
),
dict(
desc='Enable forward zone %r' % fwzone1,
command=('dnsforwardzone_enable', [fwzone1], {}),
expected={
'value': fwzone1_dnsname,
'summary': u'Enabled DNS forward zone "%s"' % fwzone1,
'result': True,
},
),
dict(
desc='Check if forward zone %r is really enabled' % fwzone1,
command=('dnsforwardzone_show', [fwzone1], {}),
expected={
'value': fwzone1_dnsname,
'summary': None,
'result': {
'dn': fwzone1_dn,
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
},
},
),
dict(
desc='Enable already enabled forward zone %r' % fwzone1,
command=('dnsforwardzone_enable', [fwzone1], {}),
expected={
'value': fwzone1_dnsname,
'summary': u'Enabled DNS forward zone "%s"' % fwzone1,
'result': True,
},
),
dict(
desc='Try to enable non-existent forward zone',
command=('dnsforwardzone_enable', [nonexistent_fwzone], {}),
expected=errors.NotFound(
reason=u'%s: DNS forward zone not found' % nonexistent_fwzone
)
),
]
@pytest.mark.tier1
class test_forward_master_zones_mutual_exlusion(Declarative):
# https://fedorahosted.org/freeipa/ticket/4750
@pytest.fixture(autouse=True, scope="class")
def forward_master_zone_setup(self, declarative_setup):
if not api.Backend.rpcclient.isconnected():
api.Backend.rpcclient.connect()
if not have_ldap2:
pytest.skip('server plugin not available')
try:
api.Command['dnszone_add'](zone1, idnssoarname=zone1_rname,)
api.Command['dnszone_del'](zone1)
except errors.NotFound:
pytest.skip('DNS is not configured')
except errors.DuplicateEntry:
pass
cleanup_commands = [
('dnszone_del', [zone1, zone_findtest_master], {'continue': True}),
('dnsforwardzone_del', [fwzone1, zone_findtest_forward],
{'continue': True}),
('permission_del', [fwzone1_permission, ], {'force': True}),
]
tests = [
dict(
desc='Create zone %r' % zone1,
command=(
'dnszone_add', [zone1], {
'idnssoarname': zone1_rname,
}
),
expected={
'value': zone1_absolute_dnsname,
'summary': None,
'result': {
'dn': zone1_dn,
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': lambda x: True, # don't care in this test
'nsrecord': lambda x: True, # don't care in this test
'idnssoarname': lambda x: True, # don't care in this test
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': lambda x: True, # don't care in this test
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Create forward zone %r without forwarders with "none" policy' % fwzone1,
command=(
'dnsforwardzone_add', [fwzone1], {'idnsforwardpolicy': u'none'}
),
expected={
'value': fwzone1_dnsname,
'summary': None,
'result': {
'dn': fwzone1_dn,
'idnsname': [fwzone1_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
'objectclass': objectclasses.dnsforwardzone,
},
},
),
dict(
desc='Try to create duplicate zone which is already forward zone %r' % fwzone1,
command=(
'dnszone_add', [fwzone1], {
'idnssoarname': zone1_rname,
}
),
expected=errors.DuplicateEntry(
message=u'Only one zone type is allowed per zone name'),
),
dict(
desc='Try to create duplicate forward zone which is already master zone %r' % zone1,
command=(
'dnsforwardzone_add', [zone1], {
'idnsforwardpolicy': u'none',
}
),
expected=errors.DuplicateEntry(
message=u'Only one zone type is allowed per zone name'),
),
dict(
desc='Try to modify forward zone %r using dnszone-mod' % fwzone1,
command=(
'dnszone_mod', [fwzone1], {
'idnssoarname': zone1_rname,
}
),
expected=errors.NotFound(
reason=u'%s: DNS zone not found' % fwzone1),
),
dict(
desc='Try to modify master zone %r using dnsforwardzone-mod' % zone1,
command=(
'dnsforwardzone_mod', [zone1], {
'idnsforwardpolicy': u'none',
}
),
expected=errors.NotFound(
reason=u'%s: DNS forward zone not found' % zone1_absolute),
),
dict(
desc='Try to delete forward zone %r using dnszone-del' % fwzone1,
command=('dnszone_del', [fwzone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS zone not found' % fwzone1),
),
dict(
desc='Try to delete master zone %r using dnsforwardzone-del' % zone1,
command=('dnsforwardzone_del', [zone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS forward zone not found' % zone1_absolute),
),
dict(
desc='Try to retrieve forward zone %r using dnszone-show' % fwzone1,
command=('dnszone_show', [fwzone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS zone not found' % fwzone1),
),
dict(
desc='Try to retrieve master zone %r using dnsforwardzone-show' % zone1,
command=('dnsforwardzone_show', [zone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS forward zone not found' % zone1_absolute),
),
dict(
desc='Try to add per-zone permission for forward zone %r using dnszone-add-permission' % fwzone1,
command=('dnszone_add_permission', [fwzone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS zone not found' % fwzone1),
),
dict(
desc='Try to add per-zone permission for master zone %r using dnsforwardzone-add-permission' % zone1,
command=('dnsforwardzone_add_permission', [zone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS forward zone not found' % zone1_absolute),
),
dict(
desc='Try to remove per-zone permission for forward zone %r using dnszone-remove-permission' % fwzone1,
command=('dnszone_remove_permission', [fwzone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS zone not found' % fwzone1),
),
dict(
desc='Try to remove per-zone permission for master zone %r using dnsforwardzone-remove-permission' % zone1,
command=('dnsforwardzone_remove_permission', [zone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS forward zone not found' % zone1_absolute),
),
dict(
desc='Try to disable forward zone %r using dnszone-disable' % fwzone1,
command=('dnszone_disable', [fwzone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS zone not found' % fwzone1),
),
dict(
desc='Try to disable zone %r using dnsforwardzone-disable' % zone1,
command=('dnsforwardzone_disable', [zone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS forward zone not found' % zone1_absolute),
),
dict(
desc='Try to enable forward zone %r using dnszone-disable' % fwzone1,
command=('dnszone_enable', [fwzone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS zone not found' % fwzone1),
),
dict(
desc='Try to enable zone %r using dnsforwardzone-disable' % zone1,
command=('dnsforwardzone_enable', [zone1], {}),
expected=errors.NotFound(
reason=u'%s: DNS forward zone not found' % zone1_absolute),
),
dict(
desc='Create zone %r' % zone_findtest_master,
command=(
'dnszone_add', [zone_findtest_master], {
'idnssoarname': zone_findtest_master_rname,
}
),
expected={
'value': zone_findtest_master_dnsname,
'summary': None,
'result': {
'dn': zone_findtest_master_dn,
'idnsname': [zone_findtest_master_dnsname],
'idnszoneactive': [True],
'idnssoamname': lambda x: True, # don't care in this test
'nsrecord': lambda x: True, # don't care in this test
'idnssoarname': lambda x: True, # don't care in this test
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': lambda x: True, # don't care in this test
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Create forward zone %r' % zone_findtest_forward,
command=(
'dnsforwardzone_add', [zone_findtest_forward],
{'idnsforwarders': [forwarder1]}
),
expected={
'value': zone_findtest_forward_dnsname,
'summary': None,
'messages': lambda x: True, # fake forwarders - ignore message
'result': {
'dn': zone_findtest_forward_dn,
'idnsname': [zone_findtest_forward_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder1],
'objectclass': objectclasses.dnsforwardzone,
},
},
),
dict(
desc='dnsforwardzone-find should return only forward zones',
command=('dnsforwardzone_find', [zone_findtest], {}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [{
'dn': zone_findtest_forward_dn,
'idnsname': [zone_findtest_forward_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'first'],
'idnsforwarders': [forwarder1],
}],
},
),
dict(
desc='dnszone-find should return only master zones',
command=('dnszone_find', [zone_findtest], {}),
expected={
'summary': None,
'count': 1,
'truncated': False,
'result': [{
'dn': zone_findtest_master_dn,
'idnsname': [zone_findtest_master_dnsname],
'idnszoneactive': [True],
'nsrecord': lambda x: True, # don't care in this test
'idnssoamname': lambda x: True, # don't care in this test
'idnssoarname': lambda x: True, # don't care in this test
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowquery': [u'any;'],
}],
},
),
dict(
desc='Try to add A record to forward zone %r in zone %r' % (name1, fwzone1),
command=('dnsrecord_add', [fwzone1, name1], {'arecord': arec3}),
expected=errors.ValidationError(
name='dnszoneidnsname',
error=(u'only master zones can contain records')
),
),
dict(
desc='Try to retrieve record %r in forward zone %r' % (name1, fwzone1),
command=('dnsrecord_show', [fwzone1, name1], {}),
expected=errors.ValidationError(
name='dnszoneidnsname',
error=(u'only master zones can contain records')
),
),
dict(
desc='Try to delete record %r in forward zone %r' % (name1, fwzone1),
command=('dnsrecord_del', [fwzone1, name1], {'del_all': True}),
expected=errors.ValidationError(
name='dnszoneidnsname',
error=(u'only master zones can contain records')
),
),
dict(
desc='Try to modify record in forward zone %r' % fwzone1,
command=('dnsrecord_mod',
[fwzone1, name1],
{'aaaarecord': u'f001:baad::1'}),
expected=errors.ValidationError(
name='dnszoneidnsname',
error=(u'only master zones can contain records')
),
),
dict(
desc='Try to search for all records in forward zone %r' % fwzone1,
command=('dnsrecord_find', [fwzone1], {}),
expected=errors.ValidationError(
name='dnszoneidnsname',
error=(u'only master zones can contain records')
),
),
]
@pytest.mark.tier1
class test_forwardzone_delegation_warnings(Declarative):
@pytest.fixture(autouse=True, scope="class")
def forw_zone_deleg_warn_setup(self, declarative_setup):
if not api.Backend.rpcclient.isconnected():
api.Backend.rpcclient.connect()
if not have_ldap2:
pytest.skip('server plugin not available')
try:
api.Command['dnszone_add'](zone1, idnssoarname=zone1_rname,)
api.Command['dnszone_del'](zone1)
except errors.NotFound:
pytest.skip('DNS is not configured')
except errors.DuplicateEntry:
pass
cleanup_commands = [
('dnsforwardzone_del', [zone1_sub_fw, zone1_sub2_fw],
{'continue': True}),
('dnszone_del', [zone1, zone1_sub],
{'continue': True}),
]
tests = [
dict(
desc='Create forward zone %r without forwarders with "none" '
'policy' % zone1_sub_fw,
command=(
'dnsforwardzone_add', [zone1_sub_fw],
{'idnsforwardpolicy': u'none'}
),
expected={
'value': zone1_sub_fw_dnsname,
'summary': None,
'result': {
'dn': zone1_sub_fw_dn,
'idnsname': [zone1_sub_fw_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
'objectclass': objectclasses.dnsforwardzone,
},
},
),
dict(
desc='Create zone %r (expected warning for %r)' % (zone1,
zone1_sub_fw),
command=(
'dnszone_add', [zone1_absolute], {}
),
expected={
'value': zone1_absolute_dnsname,
'summary': None,
'result': {
'dn': zone1_dn,
'idnsname': [zone1_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': lambda x: True, # don't care in this test
'nsrecord': lambda x: True, # don't care in this test
'idnssoarname': lambda x: True, # don't care in this test
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': lambda x: True, # don't care in this test
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
'messages': (
{'message': u'forward zone "fw.sub.dnszone.test." is not '
u'effective because of missing proper NS '
u'delegation in authoritative zone '
u'"dnszone.test.". Please add NS record '
u'"fw.sub" to parent zone "dnszone.test.".',
'code': 13008,
'type': u'warning',
'name': u'ForwardzoneIsNotEffectiveWarning',
'data': {
'authzone': zone1_absolute,
'fwzone': zone1_sub_fw,
'ns_rec': zone1_sub_fw[:-len(zone1_absolute) - 1]
}},),
},
),
dict(
desc='Create zone %r (expected warning for %r)' % (zone1_sub,
zone1_sub_fw),
command=(
'dnszone_add', [zone1_sub], {}
),
expected={
'value': zone1_sub_dnsname,
'summary': None,
'result': {
'dn': zone1_sub_dn,
'idnsname': [zone1_sub_dnsname],
'idnszoneactive': [True],
'idnssoamname': lambda x: True, # don't care in this test
'nsrecord': lambda x: True, # don't care in this test
'idnssoarname': lambda x: True, # don't care in this test
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': lambda x: True, # don't care in this test
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
'messages': (
{'message': u'forward zone "fw.sub.dnszone.test." is not '
u'effective because of missing proper NS '
u'delegation in authoritative zone '
u'"sub.dnszone.test.". Please add NS record '
u'"fw" to parent zone "sub.dnszone.test.".',
'code': 13008,
'type': u'warning',
'name': u'ForwardzoneIsNotEffectiveWarning',
'data': {
'authzone': zone1_sub,
'fwzone': zone1_sub_fw,
'ns_rec': zone1_sub_fw[:-len(zone1_sub) - 1]
}},
),
},
),
dict(
desc='Disable zone %r (expected warning for %r)' % (zone1_sub,
zone1_sub_fw),
command=(
'dnszone_disable', [zone1_sub], {}
),
expected={
'value': zone1_sub_dnsname,
'summary': u'Disabled DNS zone "%s"' % zone1_sub,
'result': True,
'messages': (
{'message': u'forward zone "fw.sub.dnszone.test." is not '
u'effective because of missing proper NS '
u'delegation in authoritative zone '
u'"dnszone.test.". Please add NS record '
u'"fw.sub" to parent zone "dnszone.test.".',
'code': 13008,
'type': u'warning',
'name': u'ForwardzoneIsNotEffectiveWarning',
'data': {
'authzone': zone1_absolute,
'fwzone': zone1_sub_fw,
'ns_rec': zone1_sub_fw[:-len(zone1_absolute) - 1]
}},
),
},
),
dict(
desc='Enable zone %r (expected warning for %r)' % (zone1_sub,
zone1_sub_fw),
command=(
'dnszone_enable', [zone1_sub], {}
),
expected={
'value': zone1_sub_dnsname,
'summary': u'Enabled DNS zone "%s"' % zone1_sub,
'result': True,
'messages': (
{'message': u'forward zone "fw.sub.dnszone.test." is not '
u'effective because of missing proper NS '
u'delegation in authoritative zone '
u'"sub.dnszone.test.". Please add NS record '
u'"fw" to parent zone "sub.dnszone.test.".',
'code': 13008,
'type': u'warning',
'name': u'ForwardzoneIsNotEffectiveWarning',
'data': {
'authzone': zone1_sub,
'fwzone': zone1_sub_fw,
'ns_rec': zone1_sub_fw[:-len(zone1_sub) - 1]
}},
),
},
),
dict(
desc='Disable forward zone %r' % (zone1_sub_fw),
command=(
'dnsforwardzone_disable', [zone1_sub_fw], {}
),
expected={
'value': zone1_sub_fw_dnsname,
'summary': u'Disabled DNS forward zone "%s"' % zone1_sub_fw,
'result': True,
},
),
dict(
desc='Enable forward zone %r (expected warning for %r)' % (
zone1_sub_fw, zone1_sub_fw),
command=(
'dnsforwardzone_enable', [zone1_sub_fw], {}
),
expected={
'value': zone1_sub_fw_dnsname,
'summary': u'Enabled DNS forward zone "%s"' % zone1_sub_fw,
'result': True,
'messages': (
{'message': u'forward zone "fw.sub.dnszone.test." is not '
u'effective because of missing proper NS '
u'delegation in authoritative zone '
u'"sub.dnszone.test.". Please add NS record '
u'"fw" to parent zone "sub.dnszone.test.".',
'code': 13008,
'type': u'warning',
'name': u'ForwardzoneIsNotEffectiveWarning',
'data': {
'authzone': zone1_sub,
'fwzone': zone1_sub_fw,
'ns_rec': zone1_sub_fw[:-len(zone1_sub) - 1]
}},
),
},
),
dict(
desc='Delegate zone %r from zone %r using NS record' % (
zone1_sub_fw, zone1_sub),
command=('dnsrecord_add', [zone1_sub, u'fw'],
{'nsrecord': self_server_ns}),
expected={
'value': DNSName(u'fw'),
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': DN(('idnsname', u'fw'), zone1_sub_dn),
'idnsname': [DNSName(u'fw')],
'nsrecord': [self_server_ns],
},
},
),
dict(
desc='Disable zone %r (expected warning for %r)' % (zone1_sub,
zone1_sub_fw),
command=(
'dnszone_disable', [zone1_sub], {}
),
expected={
'value': zone1_sub_dnsname,
'summary': u'Disabled DNS zone "%s"' % zone1_sub,
'result': True,
'messages': (
{'message': u'forward zone "fw.sub.dnszone.test." is not '
u'effective because of missing proper NS '
u'delegation in authoritative zone '
u'"dnszone.test.". Please add NS record '
u'"fw.sub" to parent zone "dnszone.test.".',
'code': 13008,
'type': u'warning',
'name': u'ForwardzoneIsNotEffectiveWarning',
'data': {
'authzone': zone1_absolute,
'fwzone': zone1_sub_fw,
'ns_rec': zone1_sub_fw[:-len(zone1_absolute) - 1]
}},
),
},
),
dict(
desc='Enable zone %r' % (zone1_sub),
command=(
'dnszone_enable', [zone1_sub], {}
),
expected={
'value': zone1_sub_dnsname,
'summary': u'Enabled DNS zone "%s"' % zone1_sub,
'result': True,
},
),
dict(
desc='Delete NS record which delegates zone %r from zone %r '
'(expected warning for %r)' % (zone1_sub_fw,
zone1_sub, zone1_sub_fw),
command=('dnsrecord_del', [zone1_sub, u'fw'],
{'del_all': True}),
expected={
'value': [DNSName(u'fw')],
'summary': u'Deleted record "fw"',
'result': {
'failed': [],
},
'messages': (
{'message': u'forward zone "fw.sub.dnszone.test." is not '
u'effective because of missing proper NS '
u'delegation in authoritative zone '
u'"sub.dnszone.test.". Please add NS record '
u'"fw" to parent zone "sub.dnszone.test.".',
'code': 13008,
'type': u'warning',
'name': u'ForwardzoneIsNotEffectiveWarning',
'data': {
'authzone': zone1_sub,
'fwzone': zone1_sub_fw,
'ns_rec': zone1_sub_fw[:-len(zone1_sub) - 1]
}},
),
},
),
dict(
desc='Create forward zone %r without forwarders with "none" '
'policy (expected warning)' % zone1_sub2_fw,
command=(
'dnsforwardzone_add', [zone1_sub2_fw],
{'idnsforwardpolicy': u'none'}
),
expected={
'value': zone1_sub2_fw_dnsname,
'summary': None,
'result': {
'dn': zone1_sub2_fw_dn,
'idnsname': [zone1_sub2_fw_dnsname],
'idnszoneactive': [True],
'idnsforwardpolicy': [u'none'],
'objectclass': objectclasses.dnsforwardzone,
},
'messages': (
{'message': u'forward zone "fw.sub2.sub.dnszone.test." '
u'is not effective because of missing proper '
u'NS delegation in authoritative zone '
u'"sub.dnszone.test.". Please add NS record '
u'"fw.sub2" to parent zone '
u'"sub.dnszone.test.".',
'code': 13008,
'type': u'warning',
'name': u'ForwardzoneIsNotEffectiveWarning',
'data': {
'authzone': zone1_sub,
'fwzone': zone1_sub2_fw,
'ns_rec': zone1_sub2_fw[:-len(zone1_sub) - 1]
}},
),
},
),
dict(
desc='Delegate zone %r from zone %r using NS record' % (
zone1_sub2_fw, zone1_sub),
command=('dnsrecord_add', [zone1_sub, u'fw.sub2'],
{'nsrecord': self_server_ns}),
expected={
'value': DNSName(u'fw.sub2'),
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': DN(('idnsname', u'fw.sub2'), zone1_sub_dn),
'idnsname': [DNSName(u'fw.sub2')],
'nsrecord': [self_server_ns],
},
},
),
dict(
desc='Disable forward zone %r' % (zone1_sub2_fw),
command=(
'dnsforwardzone_disable', [zone1_sub2_fw], {}
),
expected={
'value': zone1_sub2_fw_dnsname,
'summary': u'Disabled DNS forward zone "%s"' % zone1_sub2_fw,
'result': True,
},
),
dict(
desc='Enable forward zone %r' % (zone1_sub2_fw),
command=(
'dnsforwardzone_enable', [zone1_sub2_fw], {}
),
expected={
'value': zone1_sub2_fw_dnsname,
'summary': u'Enabled DNS forward zone "%s"' % zone1_sub2_fw,
'result': True,
},
),
dict(
desc='Delete zone %r (expected warning for %r, %r)' % (
zone1_sub, zone1_sub_fw, zone1_sub2_fw),
command=('dnszone_del', [zone1_sub], {}),
expected={
'value': [zone1_sub_dnsname],
'summary': u'Deleted DNS zone "%s"' % zone1_sub,
'result': {'failed': []},
'messages': (
{'message': u'forward zone "fw.sub.dnszone.test." is not '
u'effective because of missing proper NS '
u'delegation in authoritative zone '
u'"dnszone.test.". Please add NS record '
u'"fw.sub" to parent zone "dnszone.test.".',
'code': 13008,
'type': u'warning',
'name': u'ForwardzoneIsNotEffectiveWarning',
'data': {
'authzone': zone1_absolute,
'fwzone': zone1_sub_fw,
'ns_rec': zone1_sub_fw[:-len(zone1_absolute) - 1]
}},
{'message': u'forward zone "fw.sub2.sub.dnszone.test." '
u'is not effective because of missing proper '
u'NS delegation in authoritative zone '
u'"dnszone.test.". Please add NS record '
u'"fw.sub2.sub" to parent zone '
u'"dnszone.test.".',
'code': 13008,
'type': u'warning',
'name': u'ForwardzoneIsNotEffectiveWarning',
'data': {
'authzone': zone1_absolute,
'fwzone': zone1_sub2_fw,
'ns_rec': zone1_sub2_fw[:-len(zone1_absolute) - 1]
}}
),
},
),
dict(
desc='Delegate zone %r from zone %r using NS record' % (
zone1_sub2_fw, zone1),
command=('dnsrecord_add', [zone1, u'fw.sub2.sub'],
{'nsrecord': self_server_ns}),
expected={
'value': DNSName(u'fw.sub2.sub'),
'summary': None,
'result': {
'objectclass': objectclasses.dnsrecord,
'dn': DN(('idnsname', u'fw.sub2.sub'), zone1_dn),
'idnsname': [DNSName(u'fw.sub2.sub')],
'nsrecord': [self_server_ns],
},
},
),
dict(
desc='Delete (using dnsrecord-mod) NS record which delegates '
'zone %r from zone %r (expected warning for %r)' % (
zone1_sub2_fw, zone1, zone1_sub2_fw),
command=('dnsrecord_mod', [zone1, u'fw.sub2.sub'],
{'nsrecord': None}),
expected={
'value': DNSName(u'fw.sub2.sub'),
'summary': u'Deleted record "fw.sub2.sub"',
'result': {
'failed': [],
},
'messages': (
{'message': u'forward zone "fw.sub2.sub.dnszone.test." is '
u'not effective because of missing proper NS '
u'delegation in authoritative zone '
u'"dnszone.test.". Please add NS record '
u'"fw.sub2.sub" to parent zone '
u'"dnszone.test.".',
'code': 13008,
'type': u'warning',
'name': u'ForwardzoneIsNotEffectiveWarning',
'data': {
'authzone': zone1_absolute,
'fwzone': zone1_sub2_fw,
'ns_rec': zone1_sub2_fw[:-len(zone1_absolute) - 1]
}},
),
},
),
]
# https://fedorahosted.org/freeipa/ticket/4746
# http://www.freeipa.org/page/V4/DNS:_Automatic_Zone_NS/SOA_Record_Maintenance
@pytest.mark.tier1
class test_dns_soa(Declarative):
@pytest.fixture(autouse=True, scope="class")
def dns_soa_setup(self, declarative_setup):
if not api.Backend.rpcclient.isconnected():
api.Backend.rpcclient.connect()
if not have_ldap2:
pytest.skip('server plugin not available')
if get_nameservers_error is not None:
pytest.skip('unable to get list of nameservers (%s)' %
get_nameservers_error)
try:
api.Command['dnszone_add'](zone1,
idnssoarname=zone1_rname,)
api.Command['dnszone_del'](zone1)
except errors.NotFound:
pytest.skip('DNS is not configured')
except errors.DuplicateEntry:
pass
cleanup_commands = [
('dnszone_del', [zone6, zone6b], {'continue': True}),
]
tests = [
dict(
desc='Try to retrieve non-existent zone %r' % zone6,
command=('dnszone_show', [zone6], {}),
expected=errors.NotFound(
reason=u'%s: DNS zone not found' % zone6_absolute),
),
dict(
desc='Create zone %r' % zone6b,
command=(
'dnszone_add', [zone6b], {
'idnssoarname': zone6b_rname,
}
),
expected={
'value': zone6b_absolute_dnsname,
'summary': None,
'result': {
'dn': zone6b_absolute_dn,
'idnsname': [zone6b_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6b_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Add A record to %r in zone %r' % (zone6b_ns_arec, zone6b),
command=('dnsrecord_add',
[zone6b, zone6b_ns],
{'arecord': zone6b_ip}),
expected={
'value': zone6b_ns_dnsname,
'summary': None,
'result': {
'dn': zone6b_absolute_arec_dn,
'idnsname': [zone6b_ns_arec_dnsname],
'arecord': [zone6b_ip],
'objectclass': objectclasses.dnsrecord,
},
},
),
dict(
desc='Adding a zone - %r - just with zone name' % zone6,
command=('dnszone_add', [zone6], {}),
expected={
'value': zone6_absolute_dnsname,
'summary': None,
'result': {
'dn': zone6_absolute_dn,
'idnsname': [zone6_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6_rname_default_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Updating a zone - %r - with relative '
'admin\'s e-mail' %
zone6,
command=(
'dnszone_mod', [zone6], {
'idnssoarname': zone6_rname_relative_dnsname,
}
),
expected={
'value': zone6_absolute_dnsname,
'summary': None,
'result': {
'idnsname': [zone6_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6_rname_relative_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowquery': [u'any;'],
},
},
),
dict(
desc='Updating a zone - %r - with absolute '
'admin\'s e-mail' %
zone6,
command=(
'dnszone_mod', [zone6], {
'idnssoarname': zone6_rname_absolute_dnsname,
}
),
expected={
'value': zone6_absolute_dnsname,
'summary': None,
'result': {
'idnsname': [zone6_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6_rname_absolute_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowquery': [u'any;'],
},
},
),
dict(
desc='Updating a zone - %r - with default admin\'s e-mail' % zone6,
command=(
'dnszone_mod', [zone6], {
'idnssoarname': zone6_rname_default_dnsname,
}
),
expected={
'value': zone6_absolute_dnsname,
'summary': None,
'result': {
'idnsname': [zone6_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6_rname_default_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
},
},
),
dict(
desc='Updating a zone - %r - with name-server absolute' % zone6,
command=(
'dnszone_mod', [zone6], {
'idnssoamname': zone6b_ns,
}
),
expected={
'value': zone6_absolute_dnsname,
'summary': None,
'result': {
'idnsname': [zone6_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [zone6b_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6b_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
},
'messages': [{
'message': u"Semantic of setting Authoritative nameserver "
u"was changed. "
u"It is used only for setting the SOA MNAME "
u"attribute.\n"
u"NS record(s) can be edited in zone "
u"apex - '@'. ",
'code': 13005,
'type': u'warning',
'name': u'OptionSemanticChangedWarning',
'data': {
'current_behavior': u"It is used only for setting the "
u"SOA MNAME attribute.",
'hint': u"NS record(s) can be edited in zone apex - "
u"'@'. ",
'label': u"setting Authoritative nameserver",
},
}],
},
),
dict(
desc='Add A record to %r in zone %r' % (zone6_ns, zone6),
command=('dnsrecord_add',
[zone6, zone6_ns],
{'arecord': zone6b_ip}),
expected={
'value': zone6_ns_dnsname,
'summary': None,
'result': {
'dn': zone6_absolute_arec_dn,
'idnsname': [zone6_ns_arec_dnsname],
'arecord': [zone6b_ip],
'objectclass': objectclasses.dnsrecord,
},
},
),
dict(
desc='Updating a zone - %r - with name-server relative' % zone6,
command=(
'dnszone_mod', [zone6], {
'idnssoamname': zone6_ns_relative,
}
),
expected={
'value': zone6_absolute_dnsname,
'summary': None,
'result': {
'idnsname': [zone6_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [zone6_ns_arec_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6_rname_default_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
},
'messages': [{
'message': u"Semantic of setting Authoritative nameserver "
u"was changed. "
u"It is used only for setting the SOA MNAME "
u"attribute.\n"
u"NS record(s) can be edited in zone "
u"apex - '@'. ",
'code': 13005,
'type': u'warning',
'name': u'OptionSemanticChangedWarning',
'data': {
'current_behavior': u"It is used only for setting the "
u"SOA MNAME attribute.",
'hint': u"NS record(s) can be edited in zone apex - "
u"'@'. ",
'label': u"setting Authoritative nameserver",
},
}],
},
),
dict(
desc='Updating a zone - %r - with unresolvable name-server '
'absolute with --force' %
zone6,
command=(
'dnszone_mod', [zone6], {
'idnssoamname': zone6_unresolvable_ns,
'force': True,
}
),
expected={
'value': zone6_absolute_dnsname,
'summary': None,
'result': {
'idnsname': [zone6_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [zone6_unresolvable_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6_rname_default_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
},
'messages': [{
'message': u"Semantic of setting Authoritative nameserver "
u"was changed. "
u"It is used only for setting the SOA MNAME "
u"attribute.\n"
u"NS record(s) can be edited in zone "
u"apex - '@'. ",
'code': 13005,
'type': u'warning',
'name': u'OptionSemanticChangedWarning',
'data': {
'current_behavior': u"It is used only for setting the "
u"SOA MNAME attribute.",
'hint': u"NS record(s) can be edited in zone apex - "
u"'@'. ",
'label': u"setting Authoritative nameserver",
},
}],
},
),
dict(
desc='Updating a zone - %r - with unresolvable name-server '
'relative with --force' %
zone6,
command=(
'dnszone_mod', [zone6], {
'idnssoamname': zone6_unresolvable_ns_relative,
'force': True,
}
),
expected={
'value': zone6_absolute_dnsname,
'summary': None,
'result': {
'idnsname': [zone6_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [zone6_unresolvable_ns_relative_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6_rname_default_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
},
'messages': [{
'message': u"Semantic of setting Authoritative nameserver "
u"was changed. "
u"It is used only for setting the SOA MNAME "
u"attribute.\n"
u"NS record(s) can be edited in zone "
u"apex - '@'. ",
'code': 13005,
'type': u'warning',
'name': u'OptionSemanticChangedWarning',
'data': {
'current_behavior': u"It is used only for setting the "
u"SOA MNAME attribute.",
'hint': u"NS record(s) can be edited in zone apex - "
u"'@'. ",
'label': u"setting Authoritative nameserver",
},
}],
},
),
dict(
desc='Updating a zone - %r - with invalid s e-mail - %r' %
(zone6, zone6_rname_invalid_dnsname),
command=(
'dnszone_mod', [zone6], {
'idnssoarname': zone6_rname_invalid_dnsname,
}),
expected=errors.ConversionError(
name='admin_email',
error=u'empty DNS label'),
),
dict(
desc='Updating a zone - %r - with invalid name-server - %r' %
(zone6, zone6_ns_invalid_dnsname),
command=(
'dnszone_mod', [zone6], {
'idnssoamname': zone6_ns_invalid_dnsname,
}),
expected=errors.ConversionError(
name='name_server',
error=u'empty DNS label'),
),
dict(
desc='Updating a zone - %r - with unresolvable name-server - %r' %
(zone6, zone6_unresolvable_ns),
command=(
'dnszone_mod', [zone6], {
'idnssoamname': zone6_unresolvable_ns,
}),
expected=errors.NotFound(
reason=u"Nameserver '%s' does not have a corresponding "
u"A/AAAA record" %
zone6_unresolvable_ns_dnsname,),
),
dict(
desc='Updating a zone - %r - with unresolvable relative '
'name-server - %r' %
(zone6, zone6_unresolvable_ns_relative),
command=(
'dnszone_mod', [zone6], {
'idnssoamname': zone6_unresolvable_ns_relative,
}),
expected=errors.NotFound(
reason=u"Nameserver '%s' does not have a corresponding "
u"A/AAAA record" %
zone6_unresolvable_ns_dnsname,),
),
dict(
desc='Updating a zone - %r - with empty name-server - %r' %
(zone6, zone6_unresolvable_ns_relative),
command=(
'dnszone_mod', [zone6], {
'idnssoamname': "",
}),
expected=errors.ValidationError(name='name_server',
error=u'is required'),
),
dict(
desc='Deleting a zone - %r' % zone6,
command=('dnszone_del', [zone6], {}),
expected={
'value': [zone6_absolute_dnsname],
'summary': u'Deleted DNS zone "%s"' % zone6_absolute,
'result': {'failed': []},
},
),
dict(
desc='Adding a zone - %r - with relative admin\'s e-mail' % zone6,
command=(
'dnszone_add', [zone6], {
'idnssoarname': zone6_rname_relative_dnsname,
}
),
expected={
'value': zone6_absolute_dnsname,
'summary': None,
'result': {
'dn': zone6_absolute_dn,
'idnsname': [zone6_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6_rname_relative_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Deleting a zone - %r' % zone6,
command=('dnszone_del', [zone6], {}),
expected={
'value': [zone6_absolute_dnsname],
'summary': u'Deleted DNS zone "%s"' % zone6_absolute,
'result': {'failed': []},
},
),
dict(
desc='Adding a zone - %r - with absolute admin\'s e-mail' % zone6,
command=(
'dnszone_add', [zone6], {
'idnssoarname': zone6_rname_absolute_dnsname,
}
),
expected={
'value': zone6_absolute_dnsname,
'summary': None,
'result': {
'dn': zone6_absolute_dn,
'idnsname': [zone6_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6_rname_absolute_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
),
dict(
desc='Deleting a zone - %r' % zone6,
command=('dnszone_del', [zone6], {}),
expected={
'value': [zone6_absolute_dnsname],
'summary': u'Deleted DNS zone "%s"' % zone6_absolute,
'result': {'failed': []},
},
),
dict(
desc='Adding a zone - %r - with name-server %r' %
(zone6, zone6_ns_dnsname),
command=(
'dnszone_add', [zone6], {
'idnssoamname': zone6b_ns,
}),
expected={
'value': zone6_absolute_dnsname,
'summary': None,
'result': {
'dn': zone6_absolute_dn,
'idnsname': [zone6_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [zone6b_ns_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6b_rname_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
'messages': [
{
'message': u"Semantic of setting Authoritative nameserver "
u"was changed. "
u"It is used only for setting the SOA MNAME "
u"attribute.\n"
u"NS record(s) can be edited in zone "
u"apex - '@'. ",
'code': 13005,
'type': u'warning',
'name': u'OptionSemanticChangedWarning',
'data': {
'current_behavior': u"It is used only for setting the "
u"SOA MNAME attribute.",
'hint': u"NS record(s) can be edited in zone apex - "
u"'@'. ",
'label': u"setting Authoritative nameserver",
}},], },
),
dict(
desc='Deleting a zone - %r' % zone6,
command=('dnszone_del', [zone6], {}),
expected={
'value': [zone6_absolute_dnsname],
'summary': u'Deleted DNS zone "%s"' % zone6_absolute,
'result': {'failed': []},
},
),
dict(
desc='Adding a zone - %r - with unresolvable name-server '
'relative with --force' %
zone6,
command=(
'dnszone_add', [zone6], {
'idnssoamname': zone6_unresolvable_ns_relative,
'force': True,
}
),
expected={
'value': zone6_absolute_dnsname,
'summary': None,
'result': {
'dn': zone6_absolute_dn,
'idnsname': [zone6_absolute_dnsname],
'idnszoneactive': [True],
'idnssoamname': [zone6_unresolvable_ns_relative_dnsname],
'nsrecord': nameservers,
'idnssoarname': [zone6_rname_default_dnsname],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
'messages': [
{
'message': u"Semantic of setting Authoritative nameserver "
u"was changed. "
u"It is used only for setting the SOA MNAME "
u"attribute.\n"
u"NS record(s) can be edited in zone "
u"apex - '@'. ",
'code': 13005,
'type': u'warning',
'name': u'OptionSemanticChangedWarning',
'data': {
'current_behavior': u"It is used only for setting the "
u"SOA MNAME attribute.",
'hint': u"NS record(s) can be edited in zone apex - "
u"'@'. ",
'label': u"setting Authoritative nameserver",
}},], },
),
dict(
desc='Deleting a zone - %r' % zone6,
command=('dnszone_del', [zone6], {}),
expected={
'value': [zone6_absolute_dnsname],
'summary': u'Deleted DNS zone "%s"' % zone6_absolute,
'result': {'failed': []},
},
),
dict(
desc='Adding zone with invalid zone name - %r' % zone6_invalid,
command=('dnszone_add', [zone6_invalid], {}),
expected=errors.ConversionError(
name='name',
error=u'empty DNS label'
),
),
dict(
desc='Adding a zone - %r - with invalid s e-mail - %r' %
(zone6, zone6_rname_invalid_dnsname),
command=(
'dnszone_add', [zone6], {
'idnssoarname': zone6_rname_invalid_dnsname,
}),
expected=errors.ConversionError(
name='admin_email',
error=u'empty DNS label'),
),
dict(
desc='Adding a zone - %r - with invalid name-server - %r' %
(zone6, zone6_ns_invalid_dnsname),
command=(
'dnszone_add', [zone6], {
'idnssoamname': zone6_ns_invalid_dnsname,
}),
expected=errors.ConversionError(
name='name_server',
error=u'empty DNS label'),
),
dict(
desc='Adding a zone - %r - with unresolvable name-server - %r' %
(zone6, zone6_unresolvable_ns),
command=(
'dnszone_add', [zone6], {
'idnssoamname': zone6_unresolvable_ns,
}),
expected=errors.NotFound(
reason=u"Nameserver '%s' does not have a corresponding "
u"A/AAAA record" %
zone6_unresolvable_ns_dnsname,),
),
dict(
desc='Adding a zone - %r - with unresolvable '
'relative name-server - %r' %
(zone6,
zone6_unresolvable_ns_relative),
command=(
'dnszone_add', [zone6], {
'idnssoamname': zone6_unresolvable_ns_relative,
}),
expected=errors.NotFound(
reason=u"Nameserver '%s' does not have a corresponding "
u"A/AAAA record" %
zone6_unresolvable_ns_dnsname,),
),
]
@pytest.mark.tier1
class test_dns_type_uri(test_dns):
"""Test behavior specific for URI RR type."""
@pytest.fixture(autouse=True, scope="class")
def dns_type_uri_setup(self, dns_setup):
try:
api.Command['dnszone_add'](zone1, idnssoarname=zone1_rname)
except errors.DuplicateEntry:
pass
cleanup_commands = [
('dnszone_del', [zone1], {'continue': True}),
]
uri_priority = 1
uri_weight = 2
uri_target = 'http://example.com/'
uri_raw_value = u'{0} {1} "{2}"'.format(
uri_priority, uri_weight, uri_target)
tests = [
dict(
desc='Create URI record under %s zone %r' % (name1_dnsname, zone1),
command=('dnsrecord_add', [zone1, name1_dnsname],
{'urirecord': uri_raw_value}),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'dn': name1_dn,
'idnsname': [name1_dnsname],
'objectclass': objectclasses.dnsrecord,
'urirecord': [uri_raw_value],
},
},
),
dict(
desc='URI record is case sensitive on delete (one record)',
command=('dnsrecord_del', [zone1, name1_dnsname],
{'urirecord': uri_raw_value.upper()}),
expected=errors.AttrValueNotFound(attr='URI record',
value=uri_raw_value.upper()),
),
dict(
desc='URI record is case sensitive on add',
command=('dnsrecord_add', [zone1, name1_dnsname],
{'urirecord': uri_raw_value.upper()}),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'dn': name1_dn,
'idnsname': [name1_dnsname],
'objectclass': objectclasses.dnsrecord,
'urirecord': [uri_raw_value, uri_raw_value.upper()],
},
},
),
dict(
desc='URI record is case sensitive on delete (two records)',
command=('dnsrecord_del', [zone1, name1_dnsname],
{'urirecord': [uri_raw_value, uri_raw_value.upper()]}),
expected={
'value': [name1_dnsname],
'summary': u'Deleted record "%s"' % name1_dnsname,
'result': {'failed': []},
},
),
dict(
desc='URI record normalization does not double "" around target',
command=('dnsrecord_add', [zone1, name1_dnsname],
{'uri_part_target': u'"{0}"'.format(uri_target),
'uri_part_priority': uri_priority,
'uri_part_weight': uri_weight}),
expected={
'value': name1_dnsname,
'summary': None,
'result': {
'dn': name1_dn,
'idnsname': [name1_dnsname],
'objectclass': objectclasses.dnsrecord,
'urirecord': [uri_raw_value],
},
},
),
]
| 248,504
|
Python
|
.py
| 5,819
| 26.149854
| 120
| 0.451077
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,448
|
test_certmap_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_certmap_plugin.py
|
#
# Copyright (C) 2017 FreeIPA Contributors see COPYING for license
#
import itertools
import pytest
from ipalib import api, errors
from ipapython.dn import DN
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, raises_exact
from ipatests.test_xmlrpc.tracker.certmap_plugin import (CertmapruleTracker,
CertmapconfigTracker)
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
from ipatests.util import assert_deepequal
from ipatests.util import change_principal, unlock_principal_password
certmaprule_create_params = {
u'cn': u'test_rule',
u'description': u'Certificate mapping and matching rule for test '
u'purposes',
u'ipacertmapmaprule': u'arbitrary free-form mapping rule defined and '
u'consumed by SSSD',
u'ipacertmapmatchrule': u'arbitrary free-form matching rule defined '
u'and consumed by SSSD',
u'associateddomain': api.env.domain,
u'ipacertmappriority': u'1',
}
certmaprule_create_trusted_params = {
u'cn': u'test_trusted_rule',
u'description': u'Certificate mapping and matching rule for test '
u'purposes for trusted domain',
u'ipacertmapmaprule': u'altsecurityidentities=X509:<some map>',
u'ipacertmapmatchrule': u'arbitrary free-form matching rule defined '
u'and consumed by SSSD',
u'associateddomain': api.env.domain,
u'ipacertmappriority': u'1',
}
certmaprule_update_params = {
u'description': u'Changed description',
u'ipacertmapmaprule': u'changed arbitrary mapping rule',
u'ipacertmapmatchrule': u'changed arbitrary maching rule',
u'ipacertmappriority': u'5',
}
certmaprule_optional_params = (
'description',
'ipacertmapmaprule',
'ipacertmapmatchrule',
'ipaassociateddomain',
'ipacertmappriority',
)
certmapconfig_update_params = {u'ipacertmappromptusername': True}
CREATE_PERM = u'System: Add Certmap Rules'
READ_PERM = u'System: Read Certmap Rules'
UPDATE_PERM = u'System: Modify Certmap Rules'
DELETE_PERM = u'System: Delete Certmap Rules'
certmaprule_permissions = {
u'C': CREATE_PERM,
u'R': READ_PERM,
u'U': UPDATE_PERM,
u'D': DELETE_PERM,
}
CERTMAP_USER = u'cuser'
CERTMAP_PASSWD = 'Secret123'
def dontfill_idfn(dont_fill):
return u"dont_fill=({})".format(', '.join([
u"{}".format(d) for d in dont_fill
]))
def update_idfn(update):
return ', '.join(["{}: {}".format(k, v) for k, v in update.items()])
@pytest.fixture(scope='class')
def certmap_rule(request, xmlrpc_setup):
tracker = CertmapruleTracker(**certmaprule_create_params)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def certmap_rule_trusted_domain(request, xmlrpc_setup):
tracker = CertmapruleTracker(**certmaprule_create_trusted_params)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def certmap_config(request, xmlrpc_setup):
tracker = CertmapconfigTracker()
return tracker.make_fixture(request)
class TestCRUD(XMLRPC_test):
@pytest.mark.parametrize(
'dont_fill',
itertools.chain(*[
itertools.combinations(certmaprule_optional_params, l)
for l in range(len(certmaprule_optional_params)+1)
]),
ids=dontfill_idfn,
)
def test_create(self, dont_fill, certmap_rule):
certmap_rule.ensure_missing()
try:
certmap_rule.create(dont_fill)
finally:
certmap_rule.ensure_missing()
def test_retrieve(self, certmap_rule):
certmap_rule.ensure_exists()
certmap_rule.retrieve()
def test_find(self, certmap_rule):
certmap_rule.ensure_exists()
certmap_rule.find()
@pytest.mark.parametrize('update', [
dict(u) for l in range(1, len(certmaprule_update_params)+1)
for u in itertools.combinations(
list(certmaprule_update_params.items()), l)
],
ids=update_idfn,
)
def test_update(self, update, certmap_rule):
certmap_rule.ensure_missing()
certmap_rule.ensure_exists()
certmap_rule.update(update, {o: [v] for o, v in update.items()})
def test_delete(self, certmap_rule):
certmap_rule.ensure_exists()
certmap_rule.delete()
def test_failed_create(self, certmap_rule_trusted_domain):
certmap_rule_trusted_domain.ensure_missing()
try:
certmap_rule_trusted_domain.create([])
except errors.ValidationError:
certmap_rule_trusted_domain.exists = False
else:
certmap_rule_trusted_domain.exists = True
certmap_rule_trusted_domain.ensure_missing()
raise AssertionError("Expected validation error for "
"altSecurityIdentities used for IPA domain")
class TestEnableDisable(XMLRPC_test):
def test_disable(self, certmap_rule):
certmap_rule.ensure_exists()
certmap_rule.disable()
def test_enable(self, certmap_rule):
certmap_rule.ensure_exists()
certmap_rule.enable()
class TestConfig(XMLRPC_test):
def test_config_mod(self, certmap_config):
certmap_config.update(
certmapconfig_update_params,
{k: [v] for k, v in certmapconfig_update_params.items()}
)
def test_config_show(self, certmap_config):
certmap_config.retrieve()
certmapdata_create_params = {
u'issuer': u'CN=CA,O=EXAMPLE.ORG',
u'subject': u'CN={},O=EXAMPLE.ORG'.format(CERTMAP_USER),
u'ipacertmapdata': (u'X509:<I>O=EXAMPLE.ORG,CN=CA'
u'<S>O=EXAMPLE.ORG,CN={}'.format(CERTMAP_USER)),
u'certificate': (
u'MIICwzCCAaugAwIBAgICP9wwDQYJKoZIhvcNAQELBQAwIzEUMBIGA1UEChMLRVhB\n\r'
'TVBMRS5PUkcxCzAJBgNVBAMTAkNBMB4XDTE3MDIxMDEzMjAyNVoXDTE3MDUxMDEz\n\r'
'MjAyNVowJjEUMBIGA1UEChMLRVhBTVBMRS5PUkcxDjAMBgNVBAMTBWN1c2VyMIIB\n\r'
'IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAlEBxZ6RULSZZ+nW1YfJUfCaX\n\r'
'wHIIWJeAoU98m7dbdUtkZMgLCPXiceIkCkcHu0DLS3wYlsL6VDG+0nIpT56Qkxph\n\r'
'+qpWGdVptnuVZ5dEthbluoopzxpkAAz3ywM3NqfTCM78G9GQvftUZEOlwnfyEBbY\n\r'
'XXs2wBhynrVTZcpL+ORXMpzVAallU63/YUExNvBzHlqdGHy+pPJSw1gsRTpLm75p\n\r'
'36r3bn/5cnIih1WUygC0WnjxXQwqOdGUauBp/Z8JVRuLSe8qbPfcl/voQGnSt3u2\n\r'
'9CFkDKpMMp6pv/3RbnOmMwSZGO0/n4G13qEdoneIghF1SE9qaxFGWk8mSDYc5QID\n\r'
'AQABMA0GCSqGSIb3DQEBCwUAA4IBAQCKrvO7AUCt9YOyJ0RioDxgQZVJqQ0/E877\n\r'
'vBP3HPwN0xkiGgASKtEDi3uLWGQfDgJFX5qXtK1qu7yiM86cbKq9PlkLTC6UowjP\n\r'
'iaFAaVBwbS3nLVo731gn5cCJqZ0QrDt2NDiXaGxo4tBcqc/Y/taw5Py3f59tMDk6\n\r'
'TnTmKmFnI+hB4+oxZhpcFj6bX35XMJXnRyekraE5VWtSbq57SXiRnINW4gNS5B6w\n\r'
'dYUGo551tfFq+DOnSl0H7NnnL3q4VzCH/1AMOownorgVsw4LqMgY0NiaD/yqJyKe\n\r'
'SggODAjRznNYx/Sk/At/eStqDxMHjP9X8AucGFIt76bEwHAAL2uu\n'
),
}
@pytest.fixture
def certmap_user(request):
user = UserTracker(CERTMAP_USER, u'certmap', u'user')
return user.make_fixture(request)
def addcertmap_id(options):
if options:
return u', '.join(list(options))
else:
return u' '
class TestAddRemoveCertmap(XMLRPC_test):
@pytest.mark.parametrize(
'options', [
dict(o) for l in range(len(certmapdata_create_params)+1)
for o in itertools.combinations(
list(certmapdata_create_params.items()), l)
],
ids=addcertmap_id,
)
def test_add_certmap(self, options, certmap_user):
certmap_user.ensure_exists()
certmap_user.add_certmap(**options)
certmap_user.ensure_missing()
def test_remove_certmap(self, certmap_user):
certmap_user.ensure_exists()
certmap_user.add_certmap(ipacertmapdata=u'rawdata')
certmap_user.remove_certmap(ipacertmapdata=u'rawdata')
def test_add_certmap_multiple_subject(self, certmap_user):
certmap_user.ensure_exists()
cmd = certmap_user.make_command('user_add_certmapdata',
certmap_user.name)
with raises_exact(errors.ConversionError(
name='subject',
error=u"Only one value is allowed")):
cmd(subject=(u'CN=subject1', u'CN=subject2'), issuer=u'CN=issuer')
def test_add_certmap_multiple_issuer(self, certmap_user):
certmap_user.ensure_exists()
cmd = certmap_user.make_command('user_add_certmapdata',
certmap_user.name)
with raises_exact(errors.ConversionError(
name='issuer',
error=u"Only one value is allowed")):
cmd(issuer=(u'CN=issuer1', u'CN=issuer2'), subject=u'CN=subject')
class EWE:
"""
Context manager that checks the outcome of wrapped statement executed
under specified user against specified expected outcome based on permission
given to the user.
"""
def __init__(self, user, password):
"""
@param user Change to this user before calling the command
@param password Password to use for user change
"""
self.user = user
self.password = password
self.returned = False
self.value = None
def __call__(self, perms, exps, ok_expected=None):
"""
@param perms User has those permissions
@param exps Iterable containing tuple
(permission, exception_class, expected_result,)
If permission is missing command must raise exception
of exception_class. If exception class is None command
must use send method with the result as the only
parameter
@param ok_expected When no permission is missing command must send
ok_expected
"""
for perm, exception, expected in exps:
if perm not in perms:
break
else:
exception = None
expected = ok_expected
self.exception = exception
self.expected = expected
return self
def send(self, value):
"""
Use send method to report result of executed statement to EWE
"""
self.returned = True
self.value = value
def __enter__(self):
self.returned = False
self.value = None
self.change_principal_cm = change_principal(self.user, self.password)
self.change_principal_cm.__enter__()
if self.exception:
self.assert_raises_cm = pytest.raises(self.exception)
self.assert_raises_cm.__enter__()
return self
def __exit__(self, exc_type, exc_value, tb):
self.change_principal_cm.__exit__(
exc_type, exc_value, tb)
if self.exception:
return self.assert_raises_cm.__exit__(exc_type, exc_value, tb)
else:
if self.expected and self.returned:
assert_deepequal(self.expected, self.value)
elif self.expected:
raise AssertionError("Value expected but not provided")
elif self.returned:
raise AssertionError("Value provided but not expected")
return None
def permissions_idfn(perms):
i = []
for short_name, long_name in certmaprule_permissions.items():
if long_name in perms:
i.append(short_name)
else:
i.append('-')
return ''.join(i)
def change_permissions_bindtype(perm, bindtype):
orig = api.Command.permission_show(perm)['result']['ipapermbindruletype']
if orig != (bindtype,):
api.Command.permission_mod(perm, ipapermbindruletype=bindtype)
return orig
@pytest.fixture(scope='class')
def bindtype_permission(request, xmlrpc_setup):
orig_bindtype = {}
# set bindtype to permission to actually test the permission
for perm_name in certmaprule_permissions.values():
orig_bindtype[perm_name] = change_permissions_bindtype(
perm_name, u'permission')
def finalize():
for perm_name, bindtype in orig_bindtype.items():
change_permissions_bindtype(perm_name, bindtype[0])
request.addfinalizer(finalize)
@pytest.fixture(
scope='class',
params=itertools.chain(
*[itertools.combinations(list(certmaprule_permissions.values()), l)
for l in range(len(list(certmaprule_permissions.values())) + 1)]
),
ids=permissions_idfn,
)
def certmap_user_permissions(request, bindtype_permission):
tmp_password = u'Initial123'
priv_name = u'test_certmap_privilege'
role_name = u'test_certmap_role'
api.Command.user_add(CERTMAP_USER, givenname=u'Certmap', sn=u'User',
userpassword=tmp_password)
unlock_principal_password(CERTMAP_USER, tmp_password,
CERTMAP_PASSWD)
api.Command.privilege_add(priv_name)
for perm_name in request.param:
# add to privilege for user
api.Command.privilege_add_permission(priv_name, permission=perm_name)
api.Command.role_add(role_name)
api.Command.role_add_privilege(role_name, privilege=priv_name)
api.Command.role_add_member(role_name, user=CERTMAP_USER)
def finalize():
try:
api.Command.user_del(CERTMAP_USER)
except Exception:
pass
try:
api.Command.role_del(role_name)
except Exception:
pass
try:
api.Command.privilege_del(priv_name)
except Exception:
pass
request.addfinalizer(finalize)
return request.param
class TestPermission(XMLRPC_test):
execute_with_expected = EWE(CERTMAP_USER, CERTMAP_PASSWD)
def test_create(self, certmap_rule, certmap_user_permissions):
certmap_rule.ensure_missing()
with self.execute_with_expected(
certmap_user_permissions,
[
(CREATE_PERM, errors.ACIError, None,),
(READ_PERM, errors.NotFound, None,),
],
):
certmap_rule.create()
# Tracker sets 'exists' to True even when the create does not
# succeed so ensure_missing wouldn't be reliable here
try:
certmap_rule.delete()
except Exception:
pass
def test_retrieve(self, certmap_rule, certmap_user_permissions):
certmap_rule.ensure_exists()
with self.execute_with_expected(
certmap_user_permissions,
[
(READ_PERM, errors.NotFound, None,),
],
):
certmap_rule.retrieve()
def test_find(self, certmap_rule, certmap_user_permissions):
certmap_rule.ensure_exists()
expected_without_read = {
u'count': 0,
u'result': (),
u'summary': u'0 Certificate Identity Mapping Rules matched',
u'truncated': False,
}
expected_ok = {
u'count': 1,
u'result': [{
k: (v,) for k, v in certmaprule_create_params.items()
}],
u'summary': u'1 Certificate Identity Mapping Rule matched',
u'truncated': False,
}
expected_ok[u'result'][0][u'dn'] = DN(
(u'cn', expected_ok[u'result'][0][u'cn'][0]),
api.env.container_certmaprules,
api.env.basedn,
)
expected_ok[u'result'][0][u'ipaenabledflag'] = (True,)
with self.execute_with_expected(
certmap_user_permissions,
[
(READ_PERM, None, expected_without_read,),
],
expected_ok,
) as ewe:
find = certmap_rule.make_find_command()
res = find(**{k: v for k, v in certmaprule_create_params.items()
if k != u'dn'})
ewe.send(res)
def test_update(self, certmap_rule, certmap_user_permissions):
certmap_rule.ensure_missing()
certmap_rule.ensure_exists()
with self.execute_with_expected(
certmap_user_permissions,
[
(READ_PERM, errors.NotFound, None,),
(UPDATE_PERM, errors.ACIError, None,),
],
):
certmap_rule.update(
certmaprule_update_params,
{o: [v] for o, v in certmaprule_update_params.items()},
)
def test_delete(self, certmap_rule, certmap_user_permissions):
certmap_rule.ensure_exists()
with self.execute_with_expected(
certmap_user_permissions,
[
(DELETE_PERM, errors.ACIError, None,),
],
):
certmap_rule.delete()
# Tracker sets 'exists' to False even when the delete does not
# succeed so ensure_missing wouldn't be reliable here
try:
certmap_rule.delete()
except Exception:
pass
def test_enable(self, certmap_rule, certmap_user_permissions):
certmap_rule.ensure_exists()
certmap_rule.disable()
with self.execute_with_expected(
certmap_user_permissions,
[
(READ_PERM, errors.NotFound, None,),
(UPDATE_PERM, errors.ACIError, None,),
],
):
certmap_rule.enable()
def test_disable(self, certmap_rule, certmap_user_permissions):
certmap_rule.ensure_exists()
certmap_rule.enable()
with self.execute_with_expected(
certmap_user_permissions,
[
(READ_PERM, errors.NotFound, None,),
(UPDATE_PERM, errors.ACIError, None,),
],
):
certmap_rule.disable()
| 17,877
|
Python
|
.py
| 441
| 31.086168
| 79
| 0.631054
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,449
|
mock_trust.py
|
freeipa_freeipa/ipatests/test_xmlrpc/mock_trust.py
|
# coding: utf-8
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
import six
from ipalib import api
def get_range_dn(name):
format_str = "cn={name},cn=ranges,cn=etc,{basedn}"
data = dict(name=name, basedn=api.env.basedn)
return format_str.format(**data)
def get_trust_dn(name):
format_str = "cn={name},cn=ad,cn=trusts,{basedn}"
data = dict(name=name, basedn=api.env.basedn)
return format_str.format(**data)
def encode_mockldap_value(value):
value = str(value)
if six.PY3:
return value.encode('utf-8')
else:
return value
def get_trusted_dom_range_dict(name, base_id, size, rangetype, base_rid, sid):
return dict(
objectClass=[b"ipaIDrange", b"ipatrustedaddomainrange"],
ipaBaseID=encode_mockldap_value("{base_id}".format(base_id=base_id)),
ipaBaseRID=encode_mockldap_value("{base_rid}".format(base_rid=base_rid)),
ipaIDRangeSize=encode_mockldap_value("{size}".format(size=size)),
ipaNTTrustedDomainSID=encode_mockldap_value("{sid}".format(sid=sid)),
ipaRangeType=encode_mockldap_value("{rangetype}".format(rangetype=rangetype)),
)
def get_trusted_dom_dict(name, sid):
return dict(
objectClass=[b"ipaNTTrustedDomain", b"ipaIDobject", b"top"],
ipaNTFlatName=encode_mockldap_value(name.split('.')[0].upper()),
ipaNTTrustedDomainSID=encode_mockldap_value(sid),
ipaNTSIDBlacklistIncoming=b'S-1-0',
ipaNTTrustPartner=encode_mockldap_value('{name}.mock'.format(name=name)),
ipaNTTrustType=b'2',
ipaNTTrustDirection=b'3',
ipaNTTrustAttributes=b'8',
)
| 1,662
|
Python
|
.py
| 40
| 35.575
| 86
| 0.685909
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,450
|
test_external_members.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_external_members.py
|
# Authors:
# Ana Krivokapic <akrivoka@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/>.
"""
Test adding/removing external members (trusted domain objects) to IPA groups.
These tests are skipped if trust is not established.
"""
from ipalib import api
from ipapython.dn import DN
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import (Declarative, fuzzy_uuid,
fuzzy_user_or_group_sid)
import pytest
group_name = u'external_group'
group_desc = u'Test external group'
group_dn = DN(('cn', group_name), api.env.container_group, api.env.basedn)
def get_trusted_group_name():
trusts = api.Command['trust_find']()
if trusts['count'] == 0:
return None
ad_netbios = trusts['result'][0]['ipantflatname']
return r'%s\Domain Admins' % ad_netbios
@pytest.mark.tier1
class test_external_members(Declarative):
@pytest.fixture(autouse=True, scope="class")
def ext_member_setup(self, declarative_setup):
if not api.Backend.rpcclient.isconnected():
api.Backend.rpcclient.connect()
trusts = api.Command['trust_find']()
if trusts['count'] == 0:
pytest.skip('Trust is not established')
cleanup_commands = [
('group_del', [group_name], {}),
]
tests = [
dict(
desc='Create external group "%s"' % group_name,
command=(
'group_add', [group_name], dict(description=group_desc, external=True)
),
expected=dict(
value=group_name,
summary=u'Added group "%s"' % group_name,
result=dict(
cn=[group_name],
description=[group_desc],
objectclass=objectclasses.externalgroup,
ipauniqueid=[fuzzy_uuid],
dn=group_dn,
),
),
),
dict(
desc='Add external member "%s" to group "%s"' % (get_trusted_group_name(), group_name),
command=(
'group_add_member', [group_name], dict(ipaexternalmember=get_trusted_group_name())
),
expected=dict(
completed=1,
failed=dict(
member=dict(
group=tuple(),
user=tuple(),
),
),
result=dict(
dn=group_dn,
ipaexternalmember=[fuzzy_user_or_group_sid],
cn=[group_name],
description=[group_desc],
),
),
),
dict(
desc='Try to add duplicate external member "%s" to group "%s"' % (get_trusted_group_name(), group_name),
command=(
'group_add_member', [group_name], dict(ipaexternalmember=get_trusted_group_name())
),
expected=dict(
completed=0,
failed=dict(
member=dict(
group=[(fuzzy_user_or_group_sid, u'This entry is already a member')],
user=tuple(),
),
),
result=dict(
dn=group_dn,
ipaexternalmember=[fuzzy_user_or_group_sid],
cn=[group_name],
description=[group_desc],
),
),
),
dict(
desc='Remove external member "%s" from group "%s"' % (get_trusted_group_name(), group_name),
command=(
'group_remove_member', [group_name], dict(ipaexternalmember=get_trusted_group_name())
),
expected=dict(
completed=1,
failed=dict(
member=dict(
group=tuple(),
user=tuple(),
),
),
result=dict(
dn=group_dn,
cn=[group_name],
ipaexternalmember=[],
description=[group_desc],
),
),
),
dict(
desc='Try to remove external entry "%s" which is not a member of group "%s" from group "%s"' % (get_trusted_group_name(), group_name, group_name),
command=(
'group_remove_member', [group_name], dict(ipaexternalmember=get_trusted_group_name())
),
expected=dict(
completed=0,
failed=dict(
member=dict(
group=[(fuzzy_user_or_group_sid, u'This entry is not a member')],
user=tuple(),
),
),
result=dict(
dn=group_dn,
cn=[group_name],
description=[group_desc],
),
),
),
]
| 5,751
|
Python
|
.py
| 151
| 25.139073
| 158
| 0.510376
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,451
|
test_hbactest_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_hbactest_plugin.py
|
# Authors:
# Pavel Zuna <pzuna@redhat.com>
# Alexander Bokovoy <abokovoy@redhat.com>
#
# Copyright (C) 2009-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 `ipaserver/plugins/hbactest.py` module.
"""
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
from ipalib import api
from ipalib import errors
import pytest
# Test strategy:
# 1. Create few allow rules: with user categories, with explicit users, with user groups, with groups, with services
# 2. Create users for test
# 3. Run detailed and non-detailed tests for explicitly specified rules, check expected result
#
@pytest.mark.tier1
class test_hbactest(XMLRPC_test):
"""
Test the `hbactest` plugin.
"""
rule_names = [u'testing_rule1234_%d' % (d) for d in [1,2,3,4]]
rule_type = u'allow'
rule_service = u'ssh'
rule_descs = [u'description %d' % (d) for d in [1,2,3,4]]
test_user = u'hbacrule_test_user'
test_group = u'hbacrule_test_group'
test_host = u'hbacrule.testhost'
test_hostgroup = u'hbacrule_test_hostgroup'
test_sourcehost = u'hbacrule.testsrchost'
test_sourcehostgroup = u'hbacrule_test_src_hostgroup'
test_service = u'ssh'
# Auxiliary funcion for checking existence of warning for specified rule
def check_rule_presence(self,rule_name,warnings):
for warning in warnings:
if rule_name in warning:
return True
return False
def test_0_hbactest_addrules(self):
"""
Prepare data by adding test HBAC rules using `xmlrpc.hbacrule_add'.
"""
self.failsafe_add(api.Object.user,
self.test_user, givenname=u'first', sn=u'last'
)
self.failsafe_add(api.Object.group,
self.test_group, description=u'description'
)
self.failsafe_add(api.Object.host,
self.test_host, force=True
)
self.failsafe_add(api.Object.hostgroup,
self.test_hostgroup, description=u'description'
)
self.failsafe_add(api.Object.host,
self.test_sourcehost, force=True
)
self.failsafe_add(api.Object.hostgroup,
self.test_sourcehostgroup, description=u'desc'
)
self.failsafe_add(api.Object.hbacsvc,
self.test_service, description=u'desc'
)
for i in [0,1,2,3]:
api.Command['hbacrule_add'](
self.rule_names[i], accessruletype=self.rule_type, description=self.rule_descs[i],
)
api.Command['hbacrule_add_user'](
self.rule_names[i], user=self.test_user, group=self.test_group
)
api.Command['hbacrule_add_host'](
self.rule_names[i], host=self.test_host, hostgroup=self.test_hostgroup
)
api.Command['hbacrule_add_service'](
self.rule_names[i], hbacsvc=self.test_service
)
if i & 1:
api.Command['hbacrule_disable'](self.rule_names[i])
def test_a_hbactest_check_rules_detail(self):
"""
Test 'ipa hbactest --rules' (explicit IPA rules, detailed output)
"""
ret = api.Command['hbactest'](
user=self.test_user,
targethost=self.test_host,
service=self.test_service,
rules=self.rule_names
)
assert ret['value']
assert ret['error'] is None
for i in [0,1,2,3]:
assert self.rule_names[i] in ret['matched']
def test_b_hbactest_check_rules_nodetail(self):
"""
Test 'ipa hbactest --rules --nodetail' (explicit IPA rules, no detailed output)
"""
ret = api.Command['hbactest'](
user=self.test_user,
targethost=self.test_host,
service=self.test_service,
rules=self.rule_names,
nodetail=True
)
assert ret['value']
assert ret['error'] is None
assert ret['matched'] is None
assert 'messages' not in ret
assert ret['notmatched'] is None
def test_c_hbactest_check_rules_enabled_detail(self):
"""
Test 'ipa hbactest --enabled' (all enabled IPA rules, detailed output)
"""
ret = api.Command['hbactest'](
user=self.test_user,
targethost=self.test_host,
service=self.test_service,
enabled=True
)
# --enabled will try to work with _all_ enabled rules in IPA database
# It means we could have matched something else (unlikely but possible)
# Thus, check that our two enabled rules are in matched, nothing more
for i in [0,2]:
assert self.rule_names[i] in ret['matched']
def test_d_hbactest_check_rules_disabled_detail(self):
"""
Test 'ipa hbactest --disabled' (all disabled IPA rules, detailed output)
"""
ret = api.Command['hbactest'](
user=self.test_user,
targethost=self.test_host,
service=self.test_service,
disabled=True
)
# --disabled will try to work with _all_ disabled rules in IPA database
# It means we could have matched something else (unlikely but possible)
# Thus, check that our two disabled rules are in matched, nothing more
for i in [1,3]:
assert self.rule_names[i] in ret['matched']
def test_e_hbactest_check_non_existing_rule_detail(self):
"""
Test running 'ipa hbactest' with non-existing rule in --rules
"""
ret = api.Command['hbactest'](
user=self.test_user,
targethost=self.test_host,
service=self.test_service,
rules=[u'%s_1x1' % (rule) for rule in self.rule_names],
nodetail=True
)
assert not ret['value']
assert ret['matched'] is None
assert ret['notmatched'] is None
for rule in self.rule_names:
assert u'%s_1x1' % (rule) in ret['error']
def test_f_hbactest_check_sourcehost_option_is_deprecated(self):
"""
Test running 'ipa hbactest' with --srchost option raises ValidationError
"""
with pytest.raises(errors.ValidationError):
api.Command['hbactest'](
user=self.test_user,
targethost=self.test_host,
sourcehost=self.test_sourcehost,
service=self.test_service,
rules=[u'%s_1x1' % rule for rule in self.rule_names],
nodetail=True
)
def test_g_hbactest_searchlimit_message(self):
"""
Test running 'ipa hbactest' with limited --sizelimit
We know there are at least 6 rules, 4 created here + 2 default.
"""
ret = api.Command['hbactest'](
user=self.test_user,
targethost=self.test_host,
service=self.test_service,
nodetail=True,
sizelimit=2,
)
assert ret['messages'] is not None
def test_h_hbactest_clear_testing_data(self):
"""
Clear data for HBAC test plugin testing.
"""
for i in [0,1,2,3]:
api.Command['hbacrule_remove_host'](self.rule_names[i], host=self.test_host)
api.Command['hbacrule_remove_host'](self.rule_names[i], hostgroup=self.test_hostgroup)
api.Command['hbacrule_del'](self.rule_names[i])
api.Command['user_del'](self.test_user)
api.Command['group_del'](self.test_group)
api.Command['host_del'](self.test_host)
api.Command['hostgroup_del'](self.test_hostgroup)
api.Command['host_del'](self.test_sourcehost)
api.Command['hostgroup_del'](self.test_sourcehostgroup)
api.Command['hbacsvc_del'](self.test_service)
| 8,462
|
Python
|
.py
| 210
| 31.442857
| 116
| 0.61991
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,452
|
test_cert_request_ip_address.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_cert_request_ip_address.py
|
#
# Copyright (C) 2019 FreeIPA Contributors see COPYING for license
#
"""
Test certificate requests with IP addresses in SAN, and error
scenarios.
Tests use the default profile (caIPAserviceCert) and the main CA.
The operator is ``admin``.
Various DNS records are created, modified and deleted during this
test.
"""
import ipaddress
import pytest
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 ipalib import api, errors
from ipatests.test_xmlrpc.tracker.host_plugin import HostTracker
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
host_shortname = 'iptest'
host_fqdn = f'{host_shortname}.{api.env.domain}'
host_princ = f'host/{host_fqdn}'
host_ptr = f'{host_fqdn}.'
host2_shortname = 'iptest2'
host2_fqdn = f'{host2_shortname}.{api.env.domain}'
host2_princ = f'host/{host2_fqdn}'
host2_ptr = f'{host2_fqdn}.'
other_fqdn = f'other.{api.env.domain}'
other_ptr = f'{other_fqdn}.'
ipv4_address = '169.254.0.42'
ipv4_revzone_s = '0.254.169.in-addr.arpa.'
ipv4_revrec_s = '42'
host2_ipv4_address = '169.254.0.43'
host2_ipv4_revzone_s = '0.254.169.in-addr.arpa.'
host2_ipv4_revrec_s = '43'
ipv6_address = 'fe80::8f18:bdab:4299:95fa'
ipv6_revzone_s = '0.0.0.0.0.0.0.0.0.0.0.0.0.8.e.f.ip6.arpa.'
ipv6_revrec_s = 'a.f.5.9.9.9.2.4.b.a.d.b.8.1.f.8'
@pytest.fixture(scope='class')
def host(request, xmlrpc_setup):
tr = HostTracker(host_shortname)
return tr.make_fixture(request)
@pytest.fixture(scope='class')
def host2(request, xmlrpc_setup):
tr = HostTracker(host2_shortname)
return tr.make_fixture(request)
def _zone_setup(host, zone):
try:
host.run_command('dnszone_add', zone)
except errors.DuplicateEntry:
delete = False
else:
delete = True
yield zone
if delete:
host.run_command('dnszone_del', zone)
def _record_setup(host, zone, record, **kwargs):
try:
host.run_command('dnsrecord_add', zone, record, **kwargs)
except (errors.DuplicateEntry, errors.EmptyModlist):
delete = False
else:
delete = True
yield
if delete:
host.run_command('dnsrecord_del', zone, record, **kwargs)
@pytest.fixture(scope='class')
def ipv4_revzone(host):
yield from _zone_setup(host, ipv4_revzone_s)
@pytest.fixture(scope='class')
def ipv6_revzone(host):
yield from _zone_setup(host, ipv6_revzone_s)
@pytest.fixture(scope='class')
def host2_ipv4_ptr(host2, ipv4_revzone):
yield from _record_setup(
host2, ipv4_revzone, host2_ipv4_revrec_s, ptrrecord=host2_ptr)
@pytest.fixture(scope='class')
def ipv4_ptr(host, ipv4_revzone):
yield from _record_setup(
host, ipv4_revzone, ipv4_revrec_s, ptrrecord=host_ptr)
@pytest.fixture(scope='class')
def ipv6_ptr(host, ipv6_revzone):
yield from _record_setup(
host, ipv6_revzone, ipv6_revrec_s, ptrrecord=host_ptr)
@pytest.fixture(scope='class')
def host2_ipv4_a(host2):
yield from _record_setup(
host2, api.env.domain, host2_shortname, arecord=host2_ipv4_address)
@pytest.fixture(scope='class')
def ipv4_a(host):
yield from _record_setup(
host, api.env.domain, host_shortname, arecord=ipv4_address)
@pytest.fixture(scope='class')
def ipv6_aaaa(host):
yield from _record_setup(
host, api.env.domain, host_shortname, aaaarecord=ipv6_address)
@pytest.fixture(scope='class')
def other_forward_records(host):
"""
Create A and AAAA records (to the "correct" IP address) for
the name "other.{domain}.".
"""
yield from _record_setup(
host, api.env.domain, 'other',
arecord=ipv4_address, aaaarecord=ipv6_address)
@pytest.fixture(scope='function')
def ipv4_ptr_other(host, ipv4_revzone):
yield from _record_setup(
host, ipv4_revzone, ipv4_revrec_s, ptrrecord=other_ptr)
@pytest.fixture(scope='class')
def cname1(host):
yield from _record_setup(
host, api.env.domain, 'cname1', cnamerecord='iptest')
@pytest.fixture(scope='class')
def cname2(host):
yield from _record_setup(
host, api.env.domain, 'cname2', cnamerecord='cname1')
@pytest.fixture(scope='module')
def private_key():
return rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
def csr(altnames, cn=host_fqdn):
"""
Return a fixture that generates a CSR with the given altnames.
The altname values MUST be of type x509.DNSName, x509.IPAddress, etc.
The subject DN is always to CN={host_fqdn}.
"""
def inner(private_key):
builder = x509.CertificateSigningRequestBuilder()
builder = builder.subject_name(
x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, cn)]))
if len(altnames) > 0:
builder = builder.add_extension(
x509.SubjectAlternativeName(altnames), False)
csr = builder.sign(private_key, hashes.SHA256(), default_backend())
return csr.public_bytes(serialization.Encoding.PEM).decode('ascii')
return pytest.fixture(scope='module')(inner)
csr_ipv4 = csr([
x509.DNSName(host_fqdn),
x509.IPAddress(ipaddress.ip_address(ipv4_address)),
])
csr_ipv6 = csr([
x509.DNSName(host_fqdn),
x509.IPAddress(ipaddress.ip_address(ipv6_address)),
])
csr_ipv4_ipv6 = csr([
x509.DNSName(host_fqdn),
x509.IPAddress(ipaddress.ip_address(ipv4_address)),
x509.IPAddress(ipaddress.ip_address(ipv6_address)),
])
csr_extra_ipv4 = csr([
x509.DNSName(host_fqdn),
x509.IPAddress(ipaddress.ip_address(ipv4_address)),
x509.IPAddress(ipaddress.ip_address('172.16.254.254')),
])
csr_no_dnsname = csr([
x509.IPAddress(ipaddress.ip_address(ipv4_address)),
])
csr_alice = csr([
x509.DNSName(host_fqdn),
x509.IPAddress(ipaddress.ip_address(ipv4_address)),
], cn='alice')
csr_iptest_other = csr([
x509.DNSName(host_fqdn),
x509.DNSName(other_fqdn),
x509.IPAddress(ipaddress.ip_address(ipv4_address)),
])
csr_cname1 = csr([
x509.DNSName(f'cname1.{api.env.domain}'),
x509.IPAddress(ipaddress.ip_address(ipv4_address)),
])
csr_cname2 = csr([
x509.DNSName(f'cname2.{api.env.domain}'),
x509.IPAddress(ipaddress.ip_address(ipv4_address)),
])
csr_two_dnsname_two_ip = csr([
x509.DNSName(host_fqdn),
x509.IPAddress(ipaddress.ip_address(ipv4_address)),
x509.DNSName(host2_fqdn),
x509.IPAddress(ipaddress.ip_address(host2_ipv4_address)),
])
@pytest.fixture
def user_alice(request):
user = UserTracker('alice', 'Alice', 'Able')
return user.make_fixture(request)
# Patterns for ValidationError messages
PAT_FWD = "unreachable from DNS names"
PAT_REV = "does not have PTR record"
PAT_LOOP = "does not match A/AAAA records"
PAT_USER = "forbidden for user principals"
@pytest.mark.tier1
class TestIPAddressSANIssuance(XMLRPC_test):
"""
These are the tests that can be executed using the "correct" DNS
records. Tests for failure scenarios that require "incorrect"
records are found in other classes.
"""
def test_host_exists(self, host):
host.ensure_exists()
def test_issuance_ipv4(self, host, ipv4_a, ipv4_ptr, csr_ipv4):
host.run_command('cert_request', csr_ipv4, principal=host_princ)
def test_issuance_ipv6(self, host, ipv6_aaaa, ipv6_ptr, csr_ipv6):
host.run_command('cert_request', csr_ipv6, principal=host_princ)
def test_issuance_ipv4_ipv6(
self, host, ipv4_a, ipv6_aaaa, ipv4_ptr, ipv6_ptr, csr_ipv4_ipv6):
host.run_command('cert_request', csr_ipv4_ipv6, principal=host_princ)
def test_failure_extra_ip(self, host, ipv4_a, ipv4_ptr, csr_extra_ipv4):
with pytest.raises(errors.ValidationError, match=PAT_FWD):
host.run_command(
'cert_request', csr_extra_ipv4, principal=host_princ)
def test_failure_no_dnsname(self, host, ipv4_a, ipv4_ptr, csr_no_dnsname):
with pytest.raises(errors.ValidationError, match=PAT_FWD):
host.run_command(
'cert_request', csr_no_dnsname, principal=host_princ)
def test_failure_user_princ(
self, host, ipv4_a, ipv4_ptr, csr_alice, user_alice):
user_alice.ensure_exists()
with pytest.raises(errors.ValidationError, match=PAT_USER):
host.run_command(
'cert_request', csr_alice, principal=user_alice.uid)
@pytest.mark.tier1
class TestIPAddressSANMissingARecord(XMLRPC_test):
"""When there is no A record for the DNS name."""
def test_host_exists(self, host):
host.ensure_exists()
def test_issuance_ipv4(
self, host, ipv6_aaaa, ipv6_ptr, ipv4_ptr, csr_ipv4):
"""Issuing with IPv4 address fails."""
with pytest.raises(errors.ValidationError, match=PAT_FWD):
host.run_command('cert_request', csr_ipv4, principal=host_princ)
def test_issuance_ipv6(
self, host, ipv6_aaaa, ipv6_ptr, ipv4_ptr, csr_ipv6):
"""Issuing with IPv6 address succeeds."""
host.run_command('cert_request', csr_ipv6, principal=host_princ)
def test_issuance_ipv4_ipv6(
self, host, ipv6_aaaa, ipv4_ptr, ipv6_ptr, csr_ipv4_ipv6):
"""Issuing with IPv4 *and* IPv6 address fails."""
with pytest.raises(errors.ValidationError, match=PAT_FWD):
host.run_command(
'cert_request', csr_ipv4_ipv6, principal=host_princ)
@pytest.mark.tier1
class TestIPAddressSANMissingAAAARecord(XMLRPC_test):
"""When there is no AAAA record for the DNS name."""
def test_host_exists(self, host):
host.ensure_exists()
def test_issuance_ipv4(
self, host, ipv4_a, ipv6_ptr, ipv4_ptr, csr_ipv4):
"""Issuing with IPv4 address suceeds."""
host.run_command('cert_request', csr_ipv4, principal=host_princ)
def test_issuance_ipv6(
self, host, ipv4_a, ipv6_ptr, ipv4_ptr, csr_ipv6):
"""Issuing with IPv6 address fails."""
with pytest.raises(errors.ValidationError, match=PAT_FWD):
host.run_command('cert_request', csr_ipv6, principal=host_princ)
def test_issuance_ipv4_ipv6(
self, host, ipv4_a, ipv4_ptr, ipv6_ptr, csr_ipv4_ipv6):
"""Issuing with IPv4 *and* IPv6 address fails."""
with pytest.raises(errors.ValidationError, match=PAT_FWD):
host.run_command(
'cert_request', csr_ipv4_ipv6, principal=host_princ)
@pytest.mark.tier1
class TestIPAddressSANMissingIPv4Ptr(XMLRPC_test):
"""When there is no IPv4 PTR record for the address."""
def test_host_exists(self, host):
host.ensure_exists()
def test_issuance_ipv4(
self, host, ipv4_a, ipv6_aaaa, ipv6_ptr, csr_ipv4):
"""Issuing with IPv4 address fails."""
with pytest.raises(errors.ValidationError, match=PAT_REV):
host.run_command('cert_request', csr_ipv4, principal=host_princ)
def test_issuance_ipv6(
self, host, ipv4_a, ipv6_aaaa, ipv6_ptr, csr_ipv6):
"""Issuing with IPv6 address succeeds."""
host.run_command('cert_request', csr_ipv6, principal=host_princ)
def test_issuance_ipv4_ipv6(
self, host, ipv4_a, ipv6_aaaa, ipv6_ptr, csr_ipv4_ipv6):
"""Issuing with IPv4 *and* IPv6 address fails."""
with pytest.raises(errors.ValidationError, match=PAT_REV):
host.run_command(
'cert_request', csr_ipv4_ipv6, principal=host_princ)
@pytest.mark.tier1
class TestIPAddressSANMissingIPv6Ptr(XMLRPC_test):
"""When there is no IPv6 PTR record for the address."""
def test_host_exists(self, host):
host.ensure_exists()
def test_issuance_ipv4(
self, host, ipv4_a, ipv6_aaaa, ipv4_ptr, csr_ipv4):
"""Issuing with IPv4 address succeeds."""
host.run_command('cert_request', csr_ipv4, principal=host_princ)
def test_issuance_ipv6(
self, host, ipv4_a, ipv6_aaaa, ipv4_ptr, csr_ipv6):
"""Issuing with IPv6 address fails."""
with pytest.raises(errors.ValidationError, match=PAT_REV):
host.run_command('cert_request', csr_ipv6, principal=host_princ)
def test_issuance_ipv4_ipv6(
self, host, ipv4_a, ipv6_aaaa, ipv4_ptr, csr_ipv4_ipv6):
"""Issuing with IPv4 *and* IPv6 address fails."""
with pytest.raises(errors.ValidationError, match=PAT_REV):
host.run_command(
'cert_request', csr_ipv4_ipv6, principal=host_princ)
@pytest.mark.tier1
class TestIPAddressSANOtherForwardRecords(XMLRPC_test):
"""
A sanity check that we really are only looking at the
forward records of interest. We leave out records for
the DNS name of interest, but create A and AAAA records
for a different name in the same zone, which point to the
IP address of interest. Issuance must fail.
"""
def test_host_exists(self, host):
host.ensure_exists()
def test_issuance_ipv4(
self, host, other_forward_records, ipv4_ptr, ipv6_ptr, csr_ipv4):
"""Issuing with IPv4 address fails."""
with pytest.raises(errors.ValidationError, match=PAT_FWD):
host.run_command('cert_request', csr_ipv4, principal=host_princ)
def test_issuance_ipv6(
self, host, other_forward_records, ipv4_ptr, ipv6_ptr, csr_ipv6):
"""Issuing with IPv6 address fails."""
with pytest.raises(errors.ValidationError, match=PAT_FWD):
host.run_command('cert_request', csr_ipv6, principal=host_princ)
@pytest.mark.tier1
class TestIPAddressPTRLoopback(XMLRPC_test):
"""
A PTR record must point back to the name from which the IP
address was reached. Even when the PTR points to a name in the
SAN, unless the aforementioned condition is satisfied, issuance
must not proceed.
ORDER IS IMPORTANT for this test (because the ipv4_ptr fixture
has *class* scope).
"""
def test_host_exists(self, host):
host.ensure_exists()
host.run_command(
'host_add_principal', host.fqdn, f'host/other.{api.env.domain}')
def test_failure(self, host, ipv4_a, ipv4_ptr_other, csr_iptest_other):
"""The A and PTR records are not symmetric."""
with pytest.raises(errors.ValidationError, match=PAT_LOOP):
host.run_command(
'cert_request', csr_iptest_other, principal=host_princ)
def test_success(self, host, ipv4_a, ipv4_ptr, csr_iptest_other):
"""
The A and PTR records are symmetric. This test ensures that the
presence of an extra DNSName does not interfere with the IP address
validation.
"""
host.run_command(
'cert_request', csr_iptest_other, principal=host_princ)
@pytest.mark.tier1
class TestIPAddressCNAME(XMLRPC_test):
"""
A single level of CNAME indirection is supported. PTR must be
symmetric with the *canonical* name.
Relevant principal aliases or managedby relationships are
required by the DNSName validation regime.
"""
def test_host_exists(self, host, cname1, cname2, ipv4_a, ipv4_ptr):
# for convenience, this test also establishes the DNS
# record fixtures, which have class scope
host.ensure_exists()
host.run_command(
'host_add_principal', host.fqdn, f'host/cname1.{api.env.domain}')
host.run_command(
'host_add_principal', host.fqdn, f'host/cname2.{api.env.domain}')
def test_one_level(self, host, csr_cname1):
host.run_command('cert_request', csr_cname1, principal=host_princ)
def test_two_levels(self, host, csr_cname2):
with pytest.raises(errors.ValidationError, match=PAT_FWD):
host.run_command('cert_request', csr_cname2, principal=host_princ)
@pytest.mark.tier1
class TestTwoHostsTwoIPAddresses(XMLRPC_test):
"""
Test certificate issuance with CSR containing two hosts
and two IP addresses (one for each host).
"""
def test_host_exists(
self, host, host2, ipv4_a, ipv4_ptr, host2_ipv4_a, host2_ipv4_ptr,
):
# for convenience, this test also establishes the DNS
# record fixtures, which have class scope
host.ensure_exists()
host2.ensure_exists()
def test_issuance(self, host, csr_two_dnsname_two_ip):
host.run_command(
'cert_request', csr_two_dnsname_two_ip, principal=host_princ)
| 16,617
|
Python
|
.py
| 391
| 36.439898
| 78
| 0.685886
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,453
|
test_nesting.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_nesting.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 group nesting and indirect members
"""
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
from ipatests.test_xmlrpc.tracker.group_plugin import GroupTracker
from ipatests.test_xmlrpc.tracker.host_plugin import HostTracker
from ipatests.test_xmlrpc.tracker.hostgroup_plugin import HostGroupTracker
import pytest
@pytest.fixture(scope='class')
def user1(request, xmlrpc_setup):
tracker = UserTracker(name=u'tuser1', givenname=u'Test1', sn=u'User1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user2(request, xmlrpc_setup):
tracker = UserTracker(name=u'tuser2', givenname=u'Test2', sn=u'User2')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user3(request, xmlrpc_setup):
tracker = UserTracker(name=u'tuser3', givenname=u'Test3', sn=u'User3')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user4(request, xmlrpc_setup):
tracker = UserTracker(name=u'tuser4', givenname=u'Test4', sn=u'User4')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def group1(request, xmlrpc_setup):
tracker = GroupTracker(name=u'testgroup1', description=u'Test desc1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def group2(request, xmlrpc_setup):
tracker = GroupTracker(name=u'testgroup2', description=u'Test desc2')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def group3(request, xmlrpc_setup):
tracker = GroupTracker(name=u'testgroup3', description=u'Test desc3')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def group4(request, xmlrpc_setup):
tracker = GroupTracker(name=u'testgroup4', description=u'Test desc4')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def host1(request, xmlrpc_setup):
tracker = HostTracker(name=u'host1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def hostgroup1(request, xmlrpc_setup):
tracker = HostGroupTracker(name=u'hostgroup1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def hostgroup2(request, xmlrpc_setup):
tracker = HostGroupTracker(name=u'hostgroup2')
return tracker.make_fixture(request)
@pytest.mark.tier1
class TestNestingUserGroups(XMLRPC_test):
def test_create_groups_and_users(self, group1, group2, group3, group4,
user1, user2, user3, user4):
""" Create groups and users """
group1.ensure_exists()
group2.ensure_exists()
group3.ensure_exists()
group4.ensure_exists()
user1.ensure_exists()
user2.ensure_exists()
user3.ensure_exists()
user4.ensure_exists()
###############
# member stuff
#
# Create 4 groups and 4 users and set the following membership:
#
# g1:
# no direct memberships
#
# g2:
# memberof: g1
# member: user1, user2
#
# g3:
# memberof: g1
# member: user3, g4
#
# g4:
# memberof: g3
# member: user1, user4
#
# So when we do a show it looks like:
#
# g1:
# member groups: g2, g3
# indirect member group: g4
# indirect member users: user1, user2, tuser3, tuser4
#
# g2:
# member of group: g1
# member users: tuser1, tuser2
#
# g3:
# member users: tuser3
# member groups: g4
# member of groups: g1
# indirect member users: tuser4
#
# g4:
# member users: tuser1, tuser4
# member of groups: g3
# indirect member of groups: g1
#
# Note that tuser1 is an indirect member of g1 both through
# g2 and g4. It should appear just once in the list.
def test_add_group_members_to_groups(self, group1, group2, group3):
""" Add group1 two members: group2 and group3 """
group1.add_member(dict(group=group2.cn))
group2.attrs.update(memberof_group=[group1.cn])
group1.add_member(dict(group=group3.cn))
group3.attrs.update(memberof_group=[group1.cn])
def test_add_user_members_to_groups(self, user1, user2, user3, user4,
group1, group2, group3, group4):
""" Add user1 and user2 to group1, add user3 and group4 to group3,
add user1 and user4 to group4 """
group2.add_member(dict(user=user1.uid))
group2.add_member(dict(user=user2.uid))
group3.add_member(dict(user=user3.uid))
group3.add_member(dict(group=group4.cn))
group4.attrs.update(
memberof_group=[group3.cn],
memberofindirect_group=[group1.cn]
)
group4.add_member(dict(user=user1.uid))
group4.add_member(dict(user=user4.uid))
group1.attrs.update(
memberindirect_user=[user1.uid, user2.uid, user3.uid, user4.uid],
memberindirect_group=[group4.cn]
)
group3.attrs.update(
memberindirect_user=[u'tuser4', u'tuser1']
)
def test_retrieve_group_group(self, group1, group2, group3, group4):
""" Retrieve all test groups (1-4) """
group1.retrieve()
group2.retrieve()
group3.retrieve()
group4.retrieve()
@pytest.mark.tier1
class TestNestingHostGroups(XMLRPC_test):
def test_create_hostgroups(self, host1, hostgroup1, hostgroup2):
""" Create a host and two hostgroups """
host1.ensure_exists()
hostgroup1.ensure_exists()
hostgroup2.ensure_exists()
def test_nest_hostgroups(self, host1, hostgroup1, hostgroup2):
""" Add host1 to hostgroup2, add hostgroup2 to hostgroup1 """
hostgroup2.add_member(dict(host=host1.fqdn))
command = hostgroup1.make_add_member_command(
dict(hostgroup=hostgroup2.cn)
)
hostgroup1.attrs.update(
memberindirect_host=hostgroup2.attrs[u'member_host'],
member_hostgroup=[hostgroup2.cn]
)
result = command()
hostgroup1.check_add_member(result)
host1.attrs.update(
memberof_hostgroup=[hostgroup2.cn],
memberofindirect_hostgroup=[hostgroup1.cn]
)
def test_retrieve_host_hostgroup(self, host1, hostgroup1):
""" Retrieve host1 and hostgroup1 """
hostgroup1.retrieve()
host1.retrieve()
| 7,396
|
Python
|
.py
| 188
| 32.5
| 77
| 0.664808
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,454
|
testcert.py
|
freeipa_freeipa/ipatests/test_xmlrpc/testcert.py
|
#
# Authors:
# Rob Crittenden <rcritten@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/>.
"""
Provide a custom certificate used in the service tests.
The certificate in cached in a global variable so it only has to be created
once per test run.
"""
from __future__ import absolute_import
import os
import tempfile
import shutil
import base64
import re
from ipalib import api, x509
from ipaserver.plugins import rabase
from ipapython import certdb
from ipapython.dn import DN
from ipaplatform.paths import paths
_subject_base = None
def subject_base():
global _subject_base
if _subject_base is None:
config = api.Command['config_show']()['result']
_subject_base = DN(config['ipacertificatesubjectbase'][0])
return _subject_base
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 get_testcert(subject, principal):
"""Get the certificate, creating it if it doesn't exist"""
reqdir = tempfile.mkdtemp(prefix="tmp-")
try:
_testcert = makecert(reqdir, subject,
principal)
finally:
shutil.rmtree(reqdir)
return strip_cert_header(_testcert.decode('utf-8'))
def makecert(reqdir, subject, principal):
"""
Generate a certificate that can be used during unit testing.
"""
ra = rabase.rabase(api)
if (not os.path.exists(ra.client_certfile) and
api.env.xmlrpc_uri == 'http://localhost:8888/ipa/xml'):
raise AssertionError('The self-signed CA is not configured, '
'see ipatests/test_xmlrpc/test_cert.py')
nssdb = certdb.NSSDatabase(nssdir=reqdir)
with open(nssdb.pwd_file, "w") as f:
# Create an empty password file
f.write("\n")
# create db
nssdb.create_db()
# create CSR
csr_file = os.path.join(reqdir, 'req')
nssdb.run_certutil([
"-R", "-s", str(subject),
"-o", csr_file,
"-z", paths.GROUP,
"-a"
])
with open(csr_file, "rb") as f:
csr = f.read().decode('ascii')
res = api.Command['cert_request'](csr, principal=principal, add=True)
cert = x509.load_der_x509_certificate(
base64.b64decode(res['result']['certificate']))
return cert.public_bytes(x509.Encoding.PEM)
| 3,205
|
Python
|
.py
| 92
| 30.043478
| 75
| 0.679703
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,455
|
test_hbacsvcgroup_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_hbacsvcgroup_plugin.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 the `ipalib.plugins.hbacsvcgroup` module.
"""
from ipalib import api, errors
from ipatests.test_xmlrpc.xmlrpc_test import Declarative, fuzzy_uuid
from ipatests.test_xmlrpc import objectclasses
from ipapython.dn import DN
import pytest
hbacsvcgroup1 = u'testhbacsvcgroup1'
dn1 = DN(('cn',hbacsvcgroup1),('cn','hbacservicegroups'),('cn','hbac'),
api.env.basedn)
hbacsvc1 = u'sshd'
hbacsvc_dn1 = DN(('cn',hbacsvc1),('cn','hbacservices'),('cn','hbac'),
api.env.basedn)
@pytest.mark.tier1
class test_hbacsvcgroup(Declarative):
cleanup_commands = [
('hbacsvcgroup_del', [hbacsvcgroup1], {}),
('hbacsvc_del', [hbacsvc1], {}),
]
tests=[
dict(
desc='Try to retrieve non-existent %r' % hbacsvcgroup1,
command=('hbacsvcgroup_show', [hbacsvcgroup1], {}),
expected=errors.NotFound(
reason=u'%s: HBAC service group not found' % hbacsvcgroup1),
),
dict(
desc='Try to update non-existent %r' % hbacsvcgroup1,
command=('hbacsvcgroup_mod', [hbacsvcgroup1],
dict(description=u'Updated hbacsvcgroup 1')
),
expected=errors.NotFound(
reason=u'%s: HBAC service group not found' % hbacsvcgroup1),
),
dict(
desc='Try to delete non-existent %r' % hbacsvcgroup1,
command=('hbacsvcgroup_del', [hbacsvcgroup1], {}),
expected=errors.NotFound(
reason=u'%s: HBAC service group not found' % hbacsvcgroup1),
),
dict(
desc='Create %r' % hbacsvcgroup1,
command=('hbacsvcgroup_add', [hbacsvcgroup1],
dict(description=u'Test hbacsvcgroup 1')
),
expected=dict(
value=hbacsvcgroup1,
summary=u'Added HBAC service group "testhbacsvcgroup1"',
result=dict(
dn=dn1,
cn=[hbacsvcgroup1],
objectclass=objectclasses.hbacsvcgroup,
description=[u'Test hbacsvcgroup 1'],
ipauniqueid=[fuzzy_uuid],
),
),
),
dict(
desc='Try to create duplicate %r' % hbacsvcgroup1,
command=('hbacsvcgroup_add', [hbacsvcgroup1],
dict(description=u'Test hbacsvcgroup 1')
),
expected=errors.DuplicateEntry(
message=u'HBAC service group with name "%s" already exists' %
hbacsvcgroup1),
),
dict(
desc='Create service %r' % hbacsvc1,
command=('hbacsvc_add', [hbacsvc1],
dict(
description=u'Test service 1',
),
),
expected=dict(
value=hbacsvc1,
summary=u'Added HBAC service "%s"' % hbacsvc1,
result=dict(
dn=hbacsvc_dn1,
cn=[hbacsvc1],
description=[u'Test service 1'],
objectclass=objectclasses.hbacsvc,
ipauniqueid=[fuzzy_uuid],
),
),
),
dict(
desc=u'Add service %r to %r' % (hbacsvc1, hbacsvcgroup1),
command=(
'hbacsvcgroup_add_member', [hbacsvcgroup1], dict(hbacsvc=hbacsvc1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
hbacsvc=tuple(),
),
),
result={
'dn': dn1,
'cn': [hbacsvcgroup1],
'description': [u'Test hbacsvcgroup 1'],
'member_hbacsvc': [hbacsvc1],
},
),
),
dict(
desc='Retrieve %r' % hbacsvcgroup1,
command=('hbacsvcgroup_show', [hbacsvcgroup1], {}),
expected=dict(
value=hbacsvcgroup1,
summary=None,
result={
'dn': dn1,
'member_hbacsvc': [hbacsvc1],
'cn': [hbacsvcgroup1],
'description': [u'Test hbacsvcgroup 1'],
},
),
),
dict(
desc='Search for %r with members' % hbacsvcgroup1,
command=('hbacsvcgroup_find', [], dict(
cn=hbacsvcgroup1, no_members=False)),
expected=dict(
count=1,
truncated=False,
summary=u'1 HBAC service group matched',
result=[
{
'dn': dn1,
'member_hbacsvc': [hbacsvc1],
'cn': [hbacsvcgroup1],
'description': [u'Test hbacsvcgroup 1'],
},
],
),
),
dict(
desc='Search for %r' % hbacsvcgroup1,
command=('hbacsvcgroup_find', [], dict(cn=hbacsvcgroup1)),
expected=dict(
count=1,
truncated=False,
summary=u'1 HBAC service group matched',
result=[
{
'dn': dn1,
'cn': [hbacsvcgroup1],
'description': [u'Test hbacsvcgroup 1'],
},
],
),
),
dict(
desc='Update %r' % hbacsvcgroup1,
command=('hbacsvcgroup_mod', [hbacsvcgroup1],
dict(description=u'Updated hbacsvcgroup 1')
),
expected=dict(
value=hbacsvcgroup1,
summary=u'Modified HBAC service group "testhbacsvcgroup1"',
result=dict(
cn=[hbacsvcgroup1],
description=[u'Updated hbacsvcgroup 1'],
member_hbacsvc=[hbacsvc1],
),
),
),
dict(
desc='Retrieve %r to verify update' % hbacsvcgroup1,
command=('hbacsvcgroup_show', [hbacsvcgroup1], {}),
expected=dict(
value=hbacsvcgroup1,
summary=None,
result={
'dn': dn1,
'member_hbacsvc': [hbacsvc1],
'cn': [hbacsvcgroup1],
'description': [u'Updated hbacsvcgroup 1'],
},
),
),
dict(
desc='Remove service %r from %r' % (hbacsvc1, hbacsvcgroup1),
command=('hbacsvcgroup_remove_member', [hbacsvcgroup1],
dict(hbacsvc=hbacsvc1)
),
expected=dict(
failed=dict(
member=dict(
hbacsvc=tuple(),
),
),
completed=1,
result={
'dn': dn1,
'cn': [hbacsvcgroup1],
'description': [u'Updated hbacsvcgroup 1'],
},
),
),
dict(
desc='Delete %r' % hbacsvcgroup1,
command=('hbacsvcgroup_del', [hbacsvcgroup1], {}),
expected=dict(
value=[hbacsvcgroup1],
summary=u'Deleted HBAC service group "testhbacsvcgroup1"',
result=dict(failed=[]),
),
),
dict(
desc='Delete service %r' % hbacsvc1,
command=('hbacsvc_del', [hbacsvc1], {}),
expected=dict(
value=[hbacsvc1],
summary=u'Deleted HBAC service "%s"' % hbacsvc1,
result=dict(failed=[]),
),
)
]
| 8,659
|
Python
|
.py
| 239
| 22.627615
| 82
| 0.485922
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,456
|
test_role_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_role_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Pavel Zuna <pzuna@redhat.com>
# John Dennis <jdennis@redhat.com>
#
# Copyright (C) 2009 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/plugins/role.py` module.
"""
from ipalib import api, errors
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import Declarative, fuzzy_uuid
from ipapython.dn import DN
import pytest
search = u'test-role'
role1 = u'test-role-1'
role1_dn = DN(('cn',role1),api.env.container_rolegroup,
api.env.basedn)
renamedrole1 = u'test-role'
invalidrole1 = u' whitespace '
role2 = u'test-role-2'
role2_dn = DN(('cn',role2),api.env.container_rolegroup,
api.env.basedn)
group1 = u'testgroup1'
group1_dn = DN(('cn',group1),api.env.container_group,
api.env.basedn)
privilege1 = u'r,w privilege 1'
privilege1_dn = DN(('cn', privilege1), DN(api.env.container_privilege),
api.env.basedn)
@pytest.mark.tier1
class test_role(Declarative):
cleanup_commands = [
('role_del', [role1], {}),
('role_del', [role2], {}),
('group_del', [group1], {}),
('privilege_del', [privilege1], {}),
]
tests = [
dict(
desc='Try to retrieve non-existent %r' % role1,
command=('role_show', [role1], {}),
expected=errors.NotFound(reason=u'%s: role not found' % role1),
),
dict(
desc='Try to update non-existent %r' % role1,
command=('role_mod', [role1], dict(description=u'Foo')),
expected=errors.NotFound(reason=u'%s: role not found' % role1),
),
dict(
desc='Try to delete non-existent %r' % role1,
command=('role_del', [role1], {}),
expected=errors.NotFound(reason=u'%s: role not found' % role1),
),
dict(
desc='Try to rename non-existent %r' % role1,
command=('role_mod', [role1], dict(setattr=u'cn=%s' % renamedrole1)),
expected=errors.NotFound(reason=u'%s: role not found' % role1),
),
dict(
desc='Search for non-existent %r' % role1,
command=('role_find', [role1], {}),
expected=dict(
count=0,
truncated=False,
summary=u'0 roles matched',
result=[],
),
),
dict(
desc='Create invalid %r' % invalidrole1,
command=('role_add', [invalidrole1],
dict(description=u'role desc 1')
),
expected=errors.ValidationError(name='name',
error=u'Leading and trailing spaces are not allowed'),
),
dict(
desc='Create %r' % role1,
command=('role_add', [role1],
dict(description=u'role desc 1')
),
expected=dict(
value=role1,
summary=u'Added role "%s"' % role1,
result=dict(
dn=role1_dn,
cn=[role1],
description=[u'role desc 1'],
objectclass=objectclasses.role,
),
),
),
dict(
desc='Retrieve %r' % role1,
command=('role_show', [role1], {}),
expected=dict(
value=role1,
summary=None,
result=dict(
dn=role1_dn,
cn=[role1],
description=[u'role desc 1'],
),
),
),
dict(
desc='Create %r' % group1,
command=(
'group_add', [group1], dict(description=u'group desc 1',
nonposix=True,)
),
expected=dict(
value=group1,
summary=u'Added group "testgroup1"',
result=dict(
dn=group1_dn,
cn=[group1],
description=[u'group desc 1'],
objectclass=objectclasses.group,
ipauniqueid=[fuzzy_uuid],
),
),
),
dict(
desc='Create %r' % privilege1,
command=('privilege_add', [privilege1],
dict(description=u'privilege desc. 1')
),
expected=dict(
value=privilege1,
summary=u'Added privilege "%s"' % privilege1,
result=dict(
dn=privilege1_dn,
cn=[privilege1],
description=[u'privilege desc. 1'],
objectclass=objectclasses.privilege,
),
),
),
dict(
desc='Add privilege %r to role %r' % (privilege1, role1),
command=('role_add_privilege', [role1],
dict(privilege=privilege1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
privilege=[],
),
),
result={
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
'memberof_privilege': [privilege1],
}
),
),
dict(
desc='Add zero privileges to role %r' % role1,
command=('role_add_privilege', [role1], dict(privilege=None)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
privilege=[],
),
),
result={
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
'memberof_privilege': [privilege1],
}
),
),
dict(
desc='Remove zero privileges from role %r' % role1,
command=('role_remove_privilege', [role1], dict(privilege=None)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
privilege=[],
),
),
result={
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
'memberof_privilege': [privilege1],
}
),
),
dict(
desc='Add member %r to %r' % (group1, role1),
command=('role_add_member', [role1], dict(group=group1)),
expected=dict(
completed=1,
failed=dict(
member=dict(
user=[],
group=[],
host=[],
hostgroup=[],
service=[],
idoverrideuser=[],
),
),
result={
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
'member_group': [group1],
'memberof_privilege': [privilege1],
}
),
),
dict(
desc='Retrieve %r to verify member-add' % role1,
command=('role_show', [role1], {}),
expected=dict(
value=role1,
summary=None,
result={
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
'member_group': [group1],
'memberof_privilege': [privilege1],
},
),
),
dict(
desc='Search for %r with members' % role1,
command=('role_find', [role1], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 role matched',
result=[
{
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
'member_group': [group1],
'memberof_privilege': [privilege1],
},
],
),
),
dict(
desc='Search for %r' % role1,
command=('role_find', [role1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 role matched',
result=[
{
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
},
],
),
),
dict(
desc='Search for %r with members' % search,
command=('role_find', [search], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 role matched',
result=[
{
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
'member_group': [group1],
'memberof_privilege': [privilege1],
},
],
),
),
dict(
desc='Search for %r' % search,
command=('role_find', [search], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 role matched',
result=[
{
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
},
],
),
),
dict(
desc='Create %r' % role2,
command=('role_add', [role2],
dict(description=u'role desc 2')
),
expected=dict(
value=role2,
summary=u'Added role "%s"' % role2,
result=dict(
dn=role2_dn,
cn=[role2],
description=[u'role desc 2'],
objectclass=objectclasses.role,
),
),
),
dict(
desc='Search for %r with members' % role1,
command=('role_find', [role1], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 role matched',
result=[
{
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
'member_group': [group1],
'memberof_privilege': [privilege1],
},
],
),
),
dict(
desc='Search for %r' % role1,
command=('role_find', [role1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 role matched',
result=[
{
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
},
],
),
),
dict(
desc='Search for %r with members' % search,
command=('role_find', [search], {'no_members': False}),
expected=dict(
count=2,
truncated=False,
summary=u'2 roles matched',
result=[
{
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
'member_group': [group1],
'memberof_privilege': [privilege1],
},
{
'dn': role2_dn,
'cn': [role2],
'description': [u'role desc 2'],
},
],
),
),
dict(
desc='Search for %r' % search,
command=('role_find', [search], {}),
expected=dict(
count=2,
truncated=False,
summary=u'2 roles matched',
result=[
{
'dn': role1_dn,
'cn': [role1],
'description': [u'role desc 1'],
},
{
'dn': role2_dn,
'cn': [role2],
'description': [u'role desc 2'],
},
],
),
),
dict(
desc='Update %r' % role1,
command=(
'role_mod', [role1], dict(description=u'New desc 1')
),
expected=dict(
value=role1,
summary=u'Modified role "%s"' % role1,
result=dict(
cn=[role1],
description=[u'New desc 1'],
member_group=[group1],
memberof_privilege=[privilege1],
),
),
),
dict(
desc='Retrieve %r to verify update' % role1,
command=('role_show', [role1], {}),
expected=dict(
value=role1,
summary=None,
result={
'dn': role1_dn,
'cn': [role1],
'description': [u'New desc 1'],
'member_group': [group1],
'memberof_privilege': [privilege1],
},
),
),
dict(
desc='Remove member %r from %r' % (group1, role1),
command=('role_remove_member', [role1], dict(group=group1)),
expected=dict(
completed=1,
failed=dict(
member=dict(
user=[],
group=[],
host=[],
hostgroup=[],
service=[],
idoverrideuser=[],
),
),
result={
'dn': role1_dn,
'cn': [role1],
'description': [u'New desc 1'],
'memberof_privilege': [privilege1],
},
),
),
dict(
desc='Retrieve %r to verify member-del' % role1,
command=('role_show', [role1], {}),
expected=dict(
value=role1,
summary=None,
result={
'dn': role1_dn,
'cn': [role1],
'description': [u'New desc 1'],
'memberof_privilege': [privilege1],
},
),
),
dict(
desc='Delete %r' % group1,
command=('group_del', [group1], {}),
expected=dict(
result=dict(failed=[]),
value=[group1],
summary=u'Deleted group "testgroup1"',
)
),
dict(
desc='Rename %r' % role1,
command=('role_mod', [role1], dict(setattr=u'cn=%s' % renamedrole1)),
expected=dict(
value=role1,
result=dict(
cn=[renamedrole1],
description=[u'New desc 1'],
memberof_privilege=[privilege1],
),
summary=u'Modified role "%s"' % role1
)
),
dict(
desc='Rename %r back' % renamedrole1,
command=('role_mod', [renamedrole1], dict(setattr=u'cn=%s' % role1)),
expected=dict(
value=renamedrole1,
result=dict(
cn=[role1],
description=[u'New desc 1'],
memberof_privilege=[privilege1],
),
summary=u'Modified role "%s"' % renamedrole1
)
),
dict(
desc='Remove privilege %r from role %r' % (privilege1, role1),
command=('role_remove_privilege', [role1],
dict(privilege=privilege1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
privilege=[],
),
),
result={
'dn': role1_dn,
'cn': [role1],
'description': [u'New desc 1'],
}
),
),
dict(
desc='Remove privilege %r from role %r again' % (privilege1, role1),
command=('role_remove_privilege', [role1],
dict(privilege=privilege1)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
privilege=[(u'%s' % privilege1, u'This entry is not a member'),],
),
),
result={
'dn': role1_dn,
'cn': [role1],
'description': [u'New desc 1'],
}
),
),
dict(
desc='Delete %r' % role1,
command=('role_del', [role1], {}),
expected=dict(
result=dict(failed=[]),
value=[role1],
summary=u'Deleted role "%s"' % role1,
)
),
dict(
desc='Try to delete non-existent %r' % role1,
command=('role_del', [role1], {}),
expected=errors.NotFound(reason=u'%s: role not found' % role1),
),
dict(
desc='Try to show non-existent %r' % role1,
command=('role_show', [role1], {}),
expected=errors.NotFound(reason=u'%s: role not found' % role1),
),
dict(
desc='Try to update non-existent %r' % role1,
command=('role_mod', [role1], dict(description=u'Foo')),
expected=errors.NotFound(reason=u'%s: role not found' % role1),
),
dict(
desc='Search for %r' % search,
command=('role_find', [search], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 role matched',
result=[
{
'dn': role2_dn,
'cn': [role2],
'description': [u'role desc 2'],
},
],
),
),
dict(
desc='Delete %r' % role2,
command=('role_del', [role2], {}),
expected=dict(
result=dict(failed=[]),
value=[role2],
summary=u'Deleted role "%s"' % role2,
)
),
dict(
desc='Search for %r' % search,
command=('role_find', [search], {}),
expected=dict(
count=0,
truncated=False,
summary=u'0 roles matched',
result=[],
),
),
]
| 20,693
|
Python
|
.py
| 613
| 18.464927
| 89
| 0.398519
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,457
|
test_dns_realmdomains_integration.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_dns_realmdomains_integration.py
|
# Authors:
# Ana Krivokapic <akrivoka@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/>.
"""
Test integration of DNS and realmdomains.
1. dnszone_{add,del} should create/delete appropriate entry in realmdomains.
2. realmdomains_mod should add a _kerberos TXT record in the DNS zone.
"""
import six
from ipalib import api, errors
from ipalib.util import normalize_zone
from ipapython.dn import DN
from ipapython.dnsutil import DNSName
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import Declarative, fuzzy_digits
import pytest
if six.PY3:
unicode = str
cn = u'Realm Domains'
dn = DN(('cn', cn), ('cn', 'ipa'), ('cn', 'etc'), api.env.basedn)
our_domain = api.env.domain
dnszone_1 = u'dnszone.test'
dnszone_1_absolute = u'%s.' % dnszone_1
dnszone_1_dn = DN(('idnsname', dnszone_1_absolute), api.env.container_dns,
api.env.basedn)
idnssoamname = u'ns1.%s.' % dnszone_1
idnssoarname = u'root.%s.' % dnszone_1
dnszone_2 = u'dnszone2.test'
dnszone_2_absolute = "%s." % dnszone_2
dnszone_2_dn = DN(('idnsname', dnszone_2_absolute), api.env.container_dns,
api.env.basedn)
self_server_ns = normalize_zone(api.env.host)
self_server_ns_dnsname = DNSName(self_server_ns)
def assert_realmdomain_and_txt_record_present(response):
zone = response['value']
if isinstance(zone, (tuple, list)):
zone = zone[0]
zone = unicode(zone)
if zone.endswith(u'.'):
#realmdomains are without end dot
zone = zone[:-1]
r = api.Command['realmdomains_show']()
assert zone in r['result']['associateddomain']
r = api.Command['dnsrecord_show'](zone, u'_kerberos')
assert api.env.realm in r['result']['txtrecord']
return True
def assert_realmdomain_and_txt_record_not_present(response):
zone = response['value']
if isinstance(zone, (tuple, list)):
zone = zone[0]
zone = unicode(zone)
if zone.endswith(u'.'):
#realmdomains are without end dot
zone = zone[:-1]
r = api.Command['realmdomains_show']()
assert zone not in r['result']['associateddomain']
try:
api.Command['dnsrecord_show'](zone, u'_kerberos')
except errors.NotFound:
return True
else:
return False
@pytest.mark.tier1
class test_dns_realmdomains_integration(Declarative):
cleanup_commands = [
('realmdomains_mod', [], {'associateddomain': [our_domain]}),
('dnszone_del', [dnszone_1, dnszone_2], {'continue': True}),
]
tests = [
dict(
desc='Check realmdomain and TXT record get created '
'during dnszone_add',
command=(
'dnszone_add', [dnszone_1], {
'idnssoarname': idnssoarname,
}
),
expected={
'value':DNSName(dnszone_1_absolute),
'summary': None,
'result': {
'dn': dnszone_1_dn,
'idnsname': [DNSName(dnszone_1_absolute)],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'nsrecord': lambda x: True,
'idnssoarname': [DNSName(idnssoarname)],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
extra_check=assert_realmdomain_and_txt_record_present,
),
dict(
desc='Check realmdomain and TXT record gets created '
'during dnszone_add for master zone with a forwarder',
command=(
'dnszone_add', [dnszone_2], {
'idnssoarname': idnssoarname,
'idnsforwarders': u'198.18.19.20',
'idnsforwardpolicy': u'only',
}
),
expected={
'value': DNSName(dnszone_2_absolute),
'summary': None,
'messages': (
{
u'message': u'DNS forwarder semantics changed since '
u'IPA 4.0.\nYou may want to use forward zones '
u'(dnsforwardzone-*) instead.\nFor more details read '
u'the docs.',
u'code': 13002,
u'type': u'warning',
u'name': u'ForwardersWarning',
u'data': {}
},),
'result': {
'dn': dnszone_2_dn,
'idnsname': [DNSName(dnszone_2_absolute)],
'idnszoneactive': [True],
'idnssoamname': [self_server_ns_dnsname],
'idnsforwarders': [u'198.18.19.20'],
'idnsforwardpolicy': [u'only'],
'nsrecord': lambda x: True,
'idnssoarname': [DNSName(idnssoarname)],
'idnssoaserial': [fuzzy_digits],
'idnssoarefresh': [fuzzy_digits],
'idnssoaretry': [fuzzy_digits],
'idnssoaexpire': [fuzzy_digits],
'idnssoaminimum': [fuzzy_digits],
'idnsallowdynupdate': [False],
'idnsupdatepolicy': [u'grant %(realm)s krb5-self * A; '
u'grant %(realm)s krb5-self * AAAA; '
u'grant %(realm)s krb5-self * SSHFP;'
% dict(realm=api.env.realm)],
'idnsallowtransfer': [u'none;'],
'idnsallowquery': [u'any;'],
'objectclass': objectclasses.dnszone,
},
},
extra_check=assert_realmdomain_and_txt_record_present,
),
dict(
desc='Check realmdomain and TXT record get deleted '
'during dnszone_del',
command=('dnszone_del', [dnszone_1], {}),
expected={
'value': [DNSName(dnszone_1_absolute)],
'summary': u'Deleted DNS zone "%s"' % dnszone_1_absolute,
'result': {'failed': []},
},
extra_check=assert_realmdomain_and_txt_record_not_present,
),
]
| 7,686
|
Python
|
.py
| 181
| 30.232044
| 78
| 0.542819
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,458
|
test_selinuxusermap_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_selinuxusermap_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@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 `ipaserver/plugins/selinuxusermap.py` module.
"""
from ipalib import api, errors
from ipaplatform.constants import constants as platformconstants
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import (Declarative, fuzzy_digits,
fuzzy_set_optional_oc,
fuzzy_uuid)
from ipapython.dn import DN
from ipatests.util import Fuzzy
from ipatests.test_xmlrpc.test_user_plugin import get_user_result
import pytest
rule1 = u'selinuxrule1'
selinux_users = platformconstants.SELINUX_USERMAP_ORDER.split("$")
selinuxuser1 = selinux_users[0]
selinuxuser2 = selinux_users[1]
INVALID_MCS = "Invalid MCS value, must match {}, where max category {}".format(
platformconstants.SELINUX_MCS_REGEX,
platformconstants.SELINUX_MCS_MAX)
INVALID_MLS = "Invalid MLS value, must match {}, where max level {}".format(
platformconstants.SELINUX_MLS_REGEX,
platformconstants.SELINUX_MLS_MAX)
user1 = u'tuser1'
group1 = u'testgroup1'
host1 = u'testhost1.%s' % api.env.domain
hostdn1 = DN(('fqdn', host1), ('cn', 'computers'), ('cn', 'accounts'),
api.env.basedn)
hbacrule1 = u'testhbacrule1'
hbacrule2 = u'testhbacrule12'
# Note (?i) at the beginning of the regexp is the ingnore case flag
fuzzy_selinuxusermapdn = Fuzzy(
'(?i)ipauniqueid=[0-9a-f]{8}-[0-9a-f]{4}'
'-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12},%s,%s'
% (api.env.container_selinux, api.env.basedn)
)
fuzzy_hbacruledn = Fuzzy(
'(?i)ipauniqueid=[0-9a-f]{8}-[0-9a-f]{4}'
'-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12},%s,%s'
% (api.env.container_hbac, api.env.basedn)
)
allow_all_rule_dn = api.Command['hbacrule_show'](u'allow_all')['result']['dn']
@pytest.mark.tier1
class test_selinuxusermap(Declarative):
cleanup_commands = [
('selinuxusermap_del', [rule1], {}),
('group_del', [group1], {}),
('user_del', [user1], {}),
('host_del', [host1], {}),
('hbacrule_del', [hbacrule1], {}),
('hbacrule_del', [hbacrule2], {}),
]
tests = [
dict(
desc='Try to retrieve non-existent %r' % rule1,
command=('selinuxusermap_show', [rule1], {}),
expected=errors.NotFound(
reason=u'%s: SELinux User Map rule not found' % rule1),
),
dict(
desc='Try to update non-existent %r' % rule1,
command=('selinuxusermap_mod', [rule1], dict(description=u'Foo')),
expected=errors.NotFound(
reason=u'%s: SELinux User Map rule not found' % rule1),
),
dict(
desc='Try to delete non-existent %r' % rule1,
command=('selinuxusermap_del', [rule1], {}),
expected=errors.NotFound(
reason=u'%s: SELinux User Map rule not found' % rule1),
),
dict(
desc='Create rule %r' % rule1,
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=selinuxuser1)
),
expected=dict(
value=rule1,
summary=u'Added SELinux User Map "%s"' % rule1,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser1],
objectclass=objectclasses.selinuxusermap,
ipauniqueid=[fuzzy_uuid],
ipaenabledflag=[True],
dn=fuzzy_selinuxusermapdn,
),
),
),
dict(
desc='Try to create duplicate %r' % rule1,
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=selinuxuser1)
),
expected=errors.DuplicateEntry(message=u'SELinux User Map rule ' +
u'with name "%s" already exists' % rule1),
),
dict(
desc='Retrieve rule %r' % rule1,
command=('selinuxusermap_show', [rule1], {}),
expected=dict(
value=rule1,
summary=None,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser1],
ipaenabledflag=[True],
dn=fuzzy_selinuxusermapdn,
),
),
),
dict(
desc='Update rule %r' % rule1,
command=(
'selinuxusermap_mod', [rule1],
dict(ipaselinuxuser=selinuxuser2)
),
expected=dict(
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser2],
ipaenabledflag=[True],
),
summary=u'Modified SELinux User Map "%s"' % rule1,
value=rule1,
),
),
dict(
desc='Retrieve %r to verify update' % rule1,
command=('selinuxusermap_show', [rule1], {}),
expected=dict(
value=rule1,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser2],
ipaenabledflag=[True],
dn=fuzzy_selinuxusermapdn,
),
summary=None,
),
),
dict(
desc='Search for rule %r' % rule1,
command=('selinuxusermap_find', [], dict(cn=rule1)),
expected=dict(
count=1,
truncated=False,
result=[
dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser2],
ipaenabledflag=[True],
dn=fuzzy_selinuxusermapdn,
),
],
summary=u'1 SELinux User Map matched',
),
),
###############
# Create additional entries needed for testing
dict(
desc='Create %r' % user1,
command=(
'user_add', [], dict(givenname=u'Test', sn=u'User1')
),
expected=dict(
value=user1,
summary=u'Added user "%s"' % user1,
result=get_user_result(user1, u'Test', u'User1', 'add'),
),
),
dict(
desc='Create group %r' % group1,
command=(
'group_add', [group1], dict(description=u'Test desc 1')
),
expected=dict(
value=group1,
summary=u'Added group "%s"' % group1,
result=dict(
cn=[group1],
description=[u'Test desc 1'],
gidnumber=[fuzzy_digits],
objectclass=fuzzy_set_optional_oc(
objectclasses.posixgroup, 'ipantgroupattrs'),
ipauniqueid=[fuzzy_uuid],
dn=DN(('cn', group1), ('cn', 'groups'), ('cn', 'accounts'),
api.env.basedn),
),
),
),
dict(
desc='Add member %r to %r' % (user1, group1),
command=(
'group_add_member', [group1], dict(user=user1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
group=tuple(),
user=tuple(),
service=tuple(),
idoverrideuser=tuple(),
),
),
result={
'dn': DN(('cn', group1), ('cn', 'groups'),
('cn', 'accounts'), api.env.basedn),
'member_user': (user1,),
'gidnumber': [fuzzy_digits],
'cn': [group1],
'description': [u'Test desc 1'],
},
),
),
dict(
desc='Create host %r' % host1,
command=('host_add', [host1],
dict(
description=u'Test host 1',
l=u'Undisclosed location 1',
force=True,
),
),
expected=dict(
value=host1,
summary=u'Added host "%s"' % host1,
result=dict(
dn=hostdn1,
fqdn=[host1],
description=[u'Test host 1'],
l=[u'Undisclosed location 1'],
krbprincipalname=[u'host/%s@%s' % (host1, api.env.realm)],
krbcanonicalname=[u'host/%s@%s' % (host1, api.env.realm)],
objectclass=objectclasses.host,
ipauniqueid=[fuzzy_uuid],
managedby_host=[host1],
has_keytab=False,
has_password=False,
),
),
),
dict(
desc='Create HBAC rule %r' % hbacrule1,
command=(
'hbacrule_add', [hbacrule1], {}
),
expected=dict(
value=hbacrule1,
summary=u'Added HBAC rule "%s"' % hbacrule1,
result=dict(
cn=[hbacrule1],
objectclass=objectclasses.hbacrule,
ipauniqueid=[fuzzy_uuid],
accessruletype=[u'allow'],
ipaenabledflag=[True],
dn=fuzzy_hbacruledn,
),
),
),
dict(
desc='Create HBAC rule %r' % hbacrule2,
command=(
'hbacrule_add', [hbacrule2], {}
),
expected=dict(
value=hbacrule2,
summary=u'Added HBAC rule "%s"' % hbacrule2,
result=dict(
cn=[hbacrule2],
objectclass=objectclasses.hbacrule,
ipauniqueid=[fuzzy_uuid],
accessruletype=[u'allow'],
ipaenabledflag=[True],
dn=fuzzy_hbacruledn,
),
),
),
###############
# Fill out rule with members and/or pointers to HBAC rules
dict(
desc='Add user to %r' % rule1,
command=('selinuxusermap_add_user', [rule1], dict(user=user1)),
expected=dict(
failed=dict(memberuser=dict(group=[], user=[])),
completed=1,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser2],
ipaenabledflag=[True],
memberuser_user=[user1],
dn=fuzzy_selinuxusermapdn,
),
)
),
dict(
desc='Add non-existent user to %r' % rule1,
command=('selinuxusermap_add_user', [rule1],
dict(user=u'notfound')),
expected=dict(
failed=dict(
memberuser=dict(group=[],
user=[(u'notfound', u'no such entry')])
),
completed=0,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser2],
ipaenabledflag=[True],
memberuser_user=[user1],
dn=fuzzy_selinuxusermapdn,
),
)
),
dict(
desc='Remove user from %r' % rule1,
command=('selinuxusermap_remove_user', [rule1], dict(user=user1)),
expected=dict(
failed=dict(memberuser=dict(group=[], user=[])),
completed=1,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser2],
ipaenabledflag=[True],
dn=fuzzy_selinuxusermapdn,
),
)
),
dict(
desc='Remove non-existent user to %r' % rule1,
command=('selinuxusermap_remove_user', [rule1],
dict(user=u'notfound')),
expected=dict(
failed=dict(
memberuser=dict(group=[],
user=[(u'notfound', u'This entry is not a member')]
)
),
completed=0,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser2],
ipaenabledflag=[True],
dn=fuzzy_selinuxusermapdn,
),
)
),
dict(
desc='Add group to %r' % rule1,
command=('selinuxusermap_add_user', [rule1], dict(group=group1)),
expected=dict(
failed=dict(memberuser=dict(group=[], user=[])),
completed=1,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser2],
ipaenabledflag=[True],
memberuser_group=[group1],
dn=fuzzy_selinuxusermapdn,
),
)
),
dict(
desc='Add host to %r' % rule1,
command=('selinuxusermap_add_host', [rule1], dict(host=host1)),
expected=dict(
failed=dict(memberhost=dict(hostgroup=[], host=[])),
completed=1,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser2],
ipaenabledflag=[True],
memberhost_host=[host1],
memberuser_group=[group1],
dn=fuzzy_selinuxusermapdn,
),
)
),
###############
# Test enabling and disabling
dict(
desc='Disable %r' % rule1,
command=('selinuxusermap_disable', [rule1], {}),
expected=dict(
result=True,
value=rule1,
summary=u'Disabled SELinux User Map "%s"' % rule1,
)
),
dict(
desc='Disable %r again' % rule1,
command=('selinuxusermap_disable', [rule1], {}),
expected=errors.AlreadyInactive(),
),
dict(
desc='Enable %r' % rule1,
command=('selinuxusermap_enable', [rule1], {}),
expected=dict(
result=True,
value=rule1,
summary=u'Enabled SELinux User Map "%s"' % rule1,
)
),
dict(
desc='Re-enable %r again' % rule1,
command=('selinuxusermap_enable', [rule1], {}),
expected=errors.AlreadyActive(),
),
# Point to an HBAC Rule
dict(
desc='Add an HBAC rule to %r that has other members' % rule1,
command=(
'selinuxusermap_mod', [rule1], dict(seealso=hbacrule1)
),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Remove host from %r' % rule1,
command=('selinuxusermap_remove_host', [rule1], dict(host=host1)),
expected=dict(
failed=dict(memberhost=dict(hostgroup=[], host=[])),
completed=1,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser2],
ipaenabledflag=[True],
memberuser_group=[group1],
dn=fuzzy_selinuxusermapdn,
),
)
),
dict(
desc='Remove group from %r' % rule1,
command=('selinuxusermap_remove_user', [rule1],
dict(group=group1)),
expected=dict(
failed=dict(memberuser=dict(group=[], user=[])),
completed=1,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser2],
ipaenabledflag=[True],
dn=fuzzy_selinuxusermapdn,
),
)
),
dict(
desc='Add non-existent HBAC rule to %r' % rule1,
command=(
'selinuxusermap_mod', [rule1], dict(seealso=u'notfound')
),
expected=errors.NotFound(
reason=u'HBAC rule notfound not found'),
),
dict(
desc='Add an HBAC rule to %r' % rule1,
command=(
'selinuxusermap_mod', [rule1], dict(seealso=hbacrule1)
),
expected=dict(
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser2],
ipaenabledflag=[True],
seealso=hbacrule1,
),
summary=u'Modified SELinux User Map "%s"' % rule1,
value=rule1,
),
),
dict(
desc='Add user to %r that has HBAC' % rule1,
command=('selinuxusermap_add_user', [rule1], dict(user=user1)),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Add host to %r that has HBAC' % rule1,
command=('selinuxusermap_add_host', [rule1], dict(host=host1)),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Try to delete HBAC rule pointed to by %r' % rule1,
command=('hbacrule_del', [hbacrule1], {}),
expected=errors.DependentEntry(key=hbacrule1,
label=u'SELinux User Map', dependent=rule1)
),
# This tests selinuxusermap-find --hbacrule=<foo> returns an
# exact match
dict(
desc='Try to delete similarly named HBAC rule %r' % hbacrule2,
command=('hbacrule_del', [hbacrule2], {}),
expected=dict(
result=dict(failed=[]),
value=[hbacrule2],
summary=u'Deleted HBAC rule "%s"' % hbacrule2,
)
),
# Test clean up
dict(
desc='Delete %r' % rule1,
command=('selinuxusermap_del', [rule1], {}),
expected=dict(
result=dict(failed=[]),
value=[rule1],
summary=u'Deleted SELinux User Map "%s"' % rule1,
)
),
dict(
desc='Try to delete non-existent %r' % rule1,
command=('selinuxusermap_del', [rule1], {}),
expected=errors.NotFound(
reason=u'%s: SELinux User Map rule not found' % rule1),
),
# Some negative tests
dict(
desc='Create rule with unknown user %r' % rule1,
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=u'notfound:s0:c0')
),
expected=errors.NotFound(reason=u'SELinux user notfound:s0:c0 ' +
u'not found in ordering list (in config)'),
),
dict(
desc='Create rule with invalid user bad+user',
command=(
'selinuxusermap_add', [rule1], dict(ipaselinuxuser=u'bad+user')
),
expected=errors.ValidationError(
name='selinuxuser',
error=u'Invalid SELinux user name, must match {}'.format(
platformconstants.SELINUX_USER_REGEX)
),
),
dict(
desc='Create rule with invalid MLS foo:s{}'.format(
platformconstants.SELINUX_MLS_MAX + 1),
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=u'foo:s{}'.format(
platformconstants.SELINUX_MLS_MAX + 1))
),
expected=errors.ValidationError(name='selinuxuser',
error=INVALID_MLS),
),
dict(
desc='Create rule with invalid MCS foo:s0:p88',
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=u'foo:s0:p88')
),
expected=errors.ValidationError(name='selinuxuser',
error=INVALID_MCS),
),
dict(
desc='Create rule with invalid MCS foo:s0:c0.c{}'.format(
platformconstants.SELINUX_MCS_MAX + 1),
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=u'foo:s0-s0:c0.c{}'.format(
platformconstants.SELINUX_MCS_MAX + 1))
),
expected=errors.ValidationError(name='selinuxuser',
error=INVALID_MCS),
),
dict(
desc='Create rule with invalid user via setattr',
command=(
'selinuxusermap_mod', [rule1],
dict(setattr=u'ipaselinuxuser=deny')
),
expected=errors.ValidationError(name='ipaselinuxuser',
error=INVALID_MLS),
),
dict(
desc='Create rule with both --hbacrule and --usercat set',
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=selinuxuser1,
seealso=hbacrule1,
usercategory=u'all')
),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Create rule with both --hbacrule and --hostcat set',
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=selinuxuser1,
seealso=hbacrule1,
hostcategory=u'all')
),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Create rule with both --hbacrule '
'and --usercat set via setattr',
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=selinuxuser1,
seealso=hbacrule1,
setattr=u'usercategory=all')
),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Create rule with both --hbacrule '
'and --hostcat set via setattr',
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=selinuxuser1,
seealso=hbacrule1,
setattr=u'hostcategory=all')
),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Create rule %r with --hbacrule' % rule1,
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=selinuxuser1, seealso=hbacrule1)
),
expected=dict(
value=rule1,
summary=u'Added SELinux User Map "%s"' % rule1,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser1],
objectclass=objectclasses.selinuxusermap,
ipauniqueid=[fuzzy_uuid],
ipaenabledflag=[True],
dn=fuzzy_selinuxusermapdn,
seealso=hbacrule1
),
),
),
dict(
desc='Add an --usercat to %r that has HBAC set' % rule1,
command=(
'selinuxusermap_mod', [rule1], dict(usercategory=u'all')
),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Add an --hostcat to %r that has HBAC set' % rule1,
command=(
'selinuxusermap_mod', [rule1], dict(hostcategory=u'all')
),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Add an usercat via setattr to %r that has HBAC set' % rule1,
command=(
'selinuxusermap_mod', [rule1],
dict(setattr=u'usercategory=all')
),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Add an hostcat via setattr to %r that has HBAC set' % rule1,
command=(
'selinuxusermap_mod', [rule1],
dict(setattr=u'hostcategory=all')
),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Delete %r' % rule1,
command=('selinuxusermap_del', [rule1], {}),
expected=dict(
result=dict(failed=[]),
value=[rule1],
summary=u'Deleted SELinux User Map "%s"' % rule1,
)
),
dict(
desc='Create rule %r with usercat and hostcat set' % rule1,
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=selinuxuser1,
usercategory=u'all',
hostcategory=u'all')
),
expected=dict(
value=rule1,
summary=u'Added SELinux User Map "%s"' % rule1,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser1],
objectclass=objectclasses.selinuxusermap,
ipauniqueid=[fuzzy_uuid],
ipaenabledflag=[True],
dn=fuzzy_selinuxusermapdn,
usercategory=[u'all'],
hostcategory=[u'all']
),
),
),
dict(
desc='Add HBAC rule to %r that has usercat and hostcat' % rule1,
command=(
'selinuxusermap_mod', [rule1], dict(seealso=hbacrule1)
),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Delete %r' % rule1,
command=('selinuxusermap_del', [rule1], {}),
expected=dict(
result=dict(failed=[]),
value=[rule1],
summary=u'Deleted SELinux User Map "%s"' % rule1,
)
),
dict(
desc='Create rule %r' % rule1,
command=(
'selinuxusermap_add', [rule1],
dict(ipaselinuxuser=selinuxuser1)
),
expected=dict(
value=rule1,
summary=u'Added SELinux User Map "%s"' % rule1,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser1],
objectclass=objectclasses.selinuxusermap,
ipauniqueid=[fuzzy_uuid],
ipaenabledflag=[True],
dn=fuzzy_selinuxusermapdn,
),
),
),
dict(
desc='Add HBAC rule, hostcat and usercat to %r' % rule1,
command=(
'selinuxusermap_mod', [rule1],
dict(seealso=hbacrule1,
usercategory=u'all',
hostcategory=u'all')
),
expected=errors.MutuallyExclusiveError(
reason=u'HBAC rule and local members cannot both be set'),
),
dict(
desc='Delete %r' % rule1,
command=('selinuxusermap_del', [rule1], {}),
expected=dict(
result=dict(failed=[]),
value=[rule1],
summary=u'Deleted SELinux User Map "%s"' % rule1,
)
),
dict(
desc='Create rule %r with '
'--setattr=seealso=<allow_all rule DN>' % rule1,
command=(
'selinuxusermap_add',
[rule1],
dict(ipaselinuxuser=selinuxuser1,
setattr=u'seealso=%s' % allow_all_rule_dn)
),
expected=dict(
value=rule1,
summary=u'Added SELinux User Map "%s"' % rule1,
result=dict(
cn=[rule1],
ipaselinuxuser=[selinuxuser1],
objectclass=objectclasses.selinuxusermap,
ipauniqueid=[fuzzy_uuid],
ipaenabledflag=[True],
dn=fuzzy_selinuxusermapdn,
seealso=u'allow_all',
),
),
),
dict(
desc='Delete %r' % rule1,
command=('selinuxusermap_del', [rule1], {}),
expected=dict(
result=dict(failed=[]),
value=[rule1],
summary=u'Deleted SELinux User Map "%s"' % rule1,
)
),
]
| 30,799
|
Python
|
.py
| 819
| 22.909646
| 79
| 0.471927
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,459
|
test_batch_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_batch_plugin.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/>.
"""
Test the `ipaserver/plugins/batch.py` module.
"""
from ipalib import api
from ipatests.test_xmlrpc import objectclasses
from ipatests.util import Fuzzy, assert_deepequal
from ipatests.test_xmlrpc.xmlrpc_test import (Declarative, fuzzy_digits,
fuzzy_set_optional_oc,
fuzzy_uuid)
from ipapython.dn import DN
import pytest
group1 = u'testgroup1'
first1 = u'John'
def deepequal_list(*expected):
"""Factory for a function that checks a list
The created function asserts items of a list are "deepequal" to the given
argument. Unlike using assert_deepequal directly, the order matters.
"""
def checker(got):
if len(expected) != len(got):
raise AssertionError('Expected %s entries, got %s\n\n%s\n%s' %
(len(expected), len(got), expected, got))
for e, g in zip(expected, got):
assert_deepequal(e, g)
return True
return checker
@pytest.mark.tier1
class test_batch(Declarative):
cleanup_commands = [
('group_del', [group1], {}),
]
tests = [
dict(
desc='Batch ping',
command=('batch', [dict(method=u'ping', params=([], {}))], {}),
expected=dict(
count=1,
results=[
dict(summary=Fuzzy('IPA server version .*'), error=None),
]
),
),
dict(
desc='Batch two pings',
command=('batch', [dict(method=u'ping', params=([], {}))] * 2, {}),
expected=dict(
count=2,
results=[
dict(summary=Fuzzy('IPA server version .*'), error=None),
dict(summary=Fuzzy('IPA server version .*'), error=None),
]
),
),
dict(
desc='Create and deleting a group',
command=('batch', [
dict(method=u'group_add',
params=([group1], dict(description=u'Test desc 1'))),
dict(method=u'group_del', params=([group1], dict())),
], {}),
expected=dict(
count=2,
results=deepequal_list(
dict(
value=group1,
summary=u'Added group "testgroup1"',
result=dict(
cn=[group1],
description=[u'Test desc 1'],
objectclass=fuzzy_set_optional_oc(
objectclasses.posixgroup, 'ipantgroupattrs'),
ipauniqueid=[fuzzy_uuid],
gidnumber=[fuzzy_digits],
dn=DN(('cn', 'testgroup1'),
('cn', 'groups'),
('cn', 'accounts'),
api.env.basedn),
),
error=None),
dict(
summary=u'Deleted group "%s"' % group1,
result=dict(failed=[]),
value=[group1],
error=None),
),
),
),
dict(
desc='Try to delete nonexistent group twice',
command=('batch', [
dict(method=u'group_del', params=([group1], dict())),
dict(method=u'group_del', params=([group1], dict())),
], {}),
expected=dict(
count=2,
results=[
dict(
error=u'%s: group not found' % group1,
error_name=u'NotFound',
error_code=4001,
error_kw=dict(
reason=u'%s: group not found' % group1,
),
),
dict(
error=u'%s: group not found' % group1,
error_name=u'NotFound',
error_code=4001,
error_kw=dict(
reason=u'%s: group not found' % group1,
),
),
],
),
),
dict(
desc='Try to delete non-existent group first, then create it',
command=('batch', [
dict(method=u'group_del', params=([group1], dict())),
dict(method=u'group_add',
params=([group1], dict(description=u'Test desc 1'))),
], {}),
expected=dict(
count=2,
results=deepequal_list(
dict(
error=u'%s: group not found' % group1,
error_name=u'NotFound',
error_code=4001,
error_kw=dict(
reason=u'%s: group not found' % group1,
),
),
dict(
value=group1,
summary=u'Added group "testgroup1"',
result=dict(
cn=[group1],
description=[u'Test desc 1'],
objectclass=fuzzy_set_optional_oc(
objectclasses.posixgroup, 'ipantgroupattrs'),
ipauniqueid=[fuzzy_uuid],
gidnumber=[fuzzy_digits],
dn=DN(('cn', 'testgroup1'),
('cn', 'groups'),
('cn', 'accounts'),
api.env.basedn),
),
error=None),
),
),
),
dict(
desc='Try bad command invocations',
command=('batch', [
# bad command name
dict(method=u'nonexistent_ipa_command', params=([], dict())),
# dash, not underscore, in command name
dict(method=u'user-del', params=([], dict())),
# missing command name
dict(params=([group1], dict())),
# missing params
dict(method=u'user_del'),
# missing required argument
dict(method=u'user_add', params=([], dict())),
# missing required option
dict(method=u'user_add', params=([], dict(givenname=first1))),
# bad type
dict(method=u'group_add', params=([group1], dict(
description=u't', gidnumber=u'bad'))),
], {}),
expected=dict(
count=7,
results=deepequal_list(
dict(
error=u"unknown command 'nonexistent_ipa_command'",
error_name=u'CommandError',
error_code=905,
error_kw=dict(
name=u'nonexistent_ipa_command',
),
),
dict(
error=u"unknown command 'user-del'",
error_name=u'CommandError',
error_code=905,
error_kw=dict(
name=u'user-del',
),
),
dict(
error=u"'method' is required",
error_name=u'RequirementError',
error_code=3007,
error_kw=dict(
name=u'method',
),
),
dict(
error=u"'params' is required",
error_name=u'RequirementError',
error_code=3007,
error_kw=dict(
name=u'params',
),
),
dict(
error=u"'givenname' is required",
error_name=u'RequirementError',
error_code=3007,
error_kw=dict(
name=u'givenname',
),
),
dict(
error=u"'sn' is required",
error_name=u'RequirementError',
error_code=3007,
error_kw=dict(
name=u'sn',
),
),
dict(
error=Fuzzy(u"invalid 'gid'.*"),
error_name=u'ConversionError',
error_code=3008,
error_kw=dict(
name=u'gid',
error=Fuzzy(u'.*'),
),
),
),
),
),
]
| 10,036
|
Python
|
.py
| 253
| 21.667984
| 79
| 0.411427
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,460
|
test_ca_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_ca_plugin.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
"""
Test the `ipalib.plugins.ca` module.
"""
import pytest
from ipalib import errors
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, fuzzy_issuer
from ipatests.test_xmlrpc.tracker.certprofile_plugin import CertprofileTracker
from ipatests.test_xmlrpc.tracker.caacl_plugin import CAACLTracker
from ipatests.test_xmlrpc.tracker.ca_plugin import CATracker
@pytest.fixture(scope='module')
def default_profile(request):
name = 'caIPAserviceCert'
desc = u'Standard profile for network services'
tracker = CertprofileTracker(name, store=True, desc=desc)
tracker.track_create()
return tracker
@pytest.fixture(scope='module')
def default_acl(request):
name = u'hosts_services_caIPAserviceCert'
tracker = CAACLTracker(name, service_category=u'all', host_category=u'all')
tracker.track_create()
tracker.attrs.update(
{u'ipamembercertprofile_certprofile': [u'caIPAserviceCert']})
return tracker
@pytest.fixture(scope='module')
def default_ca(request):
name = u'ipa'
desc = u'IPA CA'
tracker = CATracker(name, fuzzy_issuer, desc=desc)
tracker.track_create()
return tracker
@pytest.fixture(scope='class')
def crud_subca(request, xmlrpc_setup):
name = u'crud-subca'
subject = u'CN=crud subca test,O=crud testing inc'
tracker = CATracker(name, subject, auto_disable_for_delete=False)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def subject_conflict_subca(request, xmlrpc_setup):
name = u'crud-subca-2'
subject = u'CN=crud subca test,O=crud testing inc'
tracker = CATracker(name, subject)
# Should not get created, no need to delete
return tracker
@pytest.fixture(scope='class')
def unrecognised_subject_dn_attrs_subca(request, xmlrpc_setup):
name = u'crud-subca-3'
subject = u'CN=crud subca test,DN=example.com,O=crud testing inc'
tracker = CATracker(name, subject)
# Should not get created, no need to delete
return tracker
@pytest.mark.tier0
class TestDefaultCA(XMLRPC_test):
def test_default_ca_present(self, default_ca):
default_ca.retrieve()
def test_default_ca_disable(self, default_ca):
"""IPA CA cannot be disabled."""
with pytest.raises(errors.ProtectedEntryError):
default_ca.disable()
def test_default_ca_delete(self, default_ca):
"""IPA CA cannot be deleted."""
with pytest.raises(errors.ProtectedEntryError):
default_ca.delete()
@pytest.mark.tier1
class TestCAbasicCRUD(XMLRPC_test):
ATTR_ERROR_MSG = u'attribute is not configurable'
def test_create(self, crud_subca):
crud_subca.create()
def test_retrieve(self, crud_subca):
crud_subca.retrieve()
def test_retrieve_all(self, crud_subca):
crud_subca.retrieve(all=True)
def test_export_ca(self, tmpdir, crud_subca):
exported_ca = tmpdir.join('exported_ca')
command = crud_subca.make_retrieve_command(
certificate_out=u'%s' % exported_ca,
)
command()
def test_delete_while_enabled_fails(self, crud_subca):
with pytest.raises(errors.ProtectedEntryError):
crud_subca.delete()
def test_disable(self, crud_subca):
crud_subca.disable()
def test_delete_after_disable_succeeds(self, crud_subca):
crud_subca.delete()
def test_find(self, crud_subca):
crud_subca.ensure_exists()
crud_subca.find()
def test_modify_description(self, crud_subca):
new_desc = u'updated CA description'
crud_subca.update(
dict(
description=new_desc,
),
expected_updates=dict(
description=[new_desc]
)
)
def test_modify_issuerdn(self, crud_subca):
bogus_issuer = u'ipacaissuerdn="cn=phony issuer,o=phony industries'
cmd = crud_subca.make_update_command(
updates=dict(setattr=bogus_issuer)
)
with pytest.raises(errors.ValidationError) as error:
cmd()
assert self.ATTR_ERROR_MSG in str(error.value)
def test_modify_subjectdn(self, crud_subca):
bogus_subject = u'ipacasubjectdn="cn=phony subject,o=phony industries'
cmd = crud_subca.make_update_command(
updates=dict(setattr=bogus_subject)
)
with pytest.raises(errors.ValidationError) as error:
cmd()
assert self.ATTR_ERROR_MSG in str(error.value)
def test_delete_subjectdn(self, crud_subca):
cmd = crud_subca.make_update_command(
updates=dict(delattr=u'ipacasubjectdn=%s'
% crud_subca.ipasubjectdn)
)
with pytest.raises(errors.ValidationError) as error:
cmd()
assert self.ATTR_ERROR_MSG in str(error.value)
def test_add_bogus_subjectdn(self, crud_subca):
bogus_subject = u'ipacasubjectdn="cn=phony subject,o=phony industries'
cmd = crud_subca.make_update_command(
updates=dict(addattr=bogus_subject)
)
with pytest.raises(errors.ValidationError) as error:
cmd()
assert self.ATTR_ERROR_MSG in str(error.value)
def test_add_bogus_issuerdn(self, crud_subca):
bogus_issuer = u'ipacaissuerdn="cn=phony issuer,o=phony industries'
cmd = crud_subca.make_update_command(
updates=dict(addattr=bogus_issuer)
)
with pytest.raises(errors.ValidationError) as error:
cmd()
assert self.ATTR_ERROR_MSG in str(error.value)
def test_create_subca_with_conflicting_name(self, crud_subca):
crud_subca.ensure_exists()
cmd = crud_subca.make_create_command()
with pytest.raises(errors.DuplicateEntry):
cmd()
def test_create_subca_with_subject_conflict(
self, crud_subca, subject_conflict_subca):
crud_subca.ensure_exists()
with pytest.raises(errors.DuplicateEntry):
subject_conflict_subca.create()
def test_create_subca_with_unrecognised_subject_dn_attrs(
self, unrecognised_subject_dn_attrs_subca):
with pytest.raises(errors.ValidationError):
unrecognised_subject_dn_attrs_subca.create()
def test_pre_cleanup_disable(self, crud_subca):
# crud_subca was initialised with auto_disable_for_delete=False. But
# we already tested disablement and deletion. Then we recreated it for
# subsequent tests. Now we have finished the tests; crud_subca is
# about to be deleted. But we have to explicitly disable it first,
# otherwise deletion will will and raise a test teardown failure.
crud_subca.disable()
| 6,789
|
Python
|
.py
| 162
| 34.432099
| 79
| 0.681327
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,461
|
test_whoami_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_whoami_plugin.py
|
#
# Copyright (C) 2017 FreeIPA Contributors see COPYING for license
#
"""
Test for the `ipaserver/plugins/whoami.py` module.
"""
import pytest
from ipalib import api
from ipatests.util import (unlock_principal_password,
get_entity_keytab,
change_principal,
assert_deepequal,
host_keytab)
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
from ipatests.test_xmlrpc.tracker.host_plugin import HostTracker
from ipatests.test_xmlrpc.tracker.service_plugin import ServiceTracker
@pytest.fixture(scope='function')
def krb_user(request):
tracker = UserTracker(u'krb_user', u'krb', u'test_user')
return tracker.make_fixture(request)
@pytest.fixture
def krb_host(request):
tracker = HostTracker(u'krb-host')
return tracker.make_fixture(request)
@pytest.fixture(scope='function')
def krb_service(request, krb_host):
krb_host.ensure_exists()
tracker = ServiceTracker(name=u'SERVICE', host_fqdn=krb_host.name)
return tracker.make_fixture(request)
@pytest.mark.tier1
class test_whoami(XMLRPC_test):
"""
Test the 'whoami' plugin.
"""
oldpw, newpw = u"Secret1234", u"Secret123"
def test_whoami_users(self, krb_user):
"""
Testing whoami as user
"""
krb_user.ensure_exists()
pwdmod = krb_user.make_update_command({'userpassword': self.oldpw})
pwdmod()
unlock_principal_password(krb_user.name, self.oldpw, self.newpw)
with change_principal(krb_user.name, self.newpw):
result = api.Command.whoami()
expected = {u'object': u'user',
u'command': u'user_show/1',
u'arguments': (krb_user.name,)}
assert_deepequal(expected, result)
def test_whoami_hosts(self, krb_host):
"""
Testing whoami as a host
"""
krb_host.ensure_exists()
with host_keytab(krb_host.name) as keytab_filename:
with change_principal(krb_host.attrs['krbcanonicalname'][0],
keytab=keytab_filename):
result = api.Command.whoami()
expected = {u'object': u'host',
u'command': u'host_show/1',
u'arguments': (krb_host.fqdn,)}
assert_deepequal(expected, result)
def test_whoami_kerberos_services(self, krb_host, krb_service):
"""
Testing whoami as a kerberos service
"""
krb_service.ensure_exists()
with get_entity_keytab(krb_service.name, '-r') as keytab:
with change_principal(krb_service.attrs['krbcanonicalname'][0],
keytab=keytab):
result = api.Command.whoami()
expected = {u'object': u'service',
u'command': u'service_show/1',
u'arguments': (krb_service.name,)}
assert_deepequal(expected, result)
| 3,127
|
Python
|
.py
| 76
| 30.75
| 75
| 0.60416
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,462
|
test_selfservice_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_selfservice_plugin.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 the `ipaserver/plugins/selfservice.py` module.
"""
from ipalib import errors
from ipatests.test_xmlrpc.xmlrpc_test import Declarative
import pytest
selfservice1 = u'testself'
invalid_selfservice1 = u'bad+name'
@pytest.mark.tier1
class test_selfservice(Declarative):
cleanup_commands = [
('selfservice_del', [selfservice1], {}),
]
tests = [
dict(
desc='Try to retrieve non-existent %r' % selfservice1,
command=('selfservice_show', [selfservice1], {}),
expected=errors.NotFound(
reason=u'ACI with name "%s" not found' % selfservice1),
),
dict(
desc='Try to update non-existent %r' % selfservice1,
command=('selfservice_mod', [selfservice1],
dict(permissions=u'write')),
expected=errors.NotFound(
reason=u'ACI with name "%s" not found' % selfservice1),
),
dict(
desc='Try to delete non-existent %r' % selfservice1,
command=('selfservice_del', [selfservice1], {}),
expected=errors.NotFound(
reason=u'ACI with name "%s" not found' % selfservice1),
),
dict(
desc='Search for non-existent %r' % selfservice1,
command=('selfservice_find', [selfservice1], {}),
expected=dict(
count=0,
truncated=False,
summary=u'0 selfservices matched',
result=[],
),
),
# Note that we add postalCode but expect postalcode. This tests
# the attrs normalizer.
dict(
desc='Create %r' % selfservice1,
command=(
'selfservice_add', [selfservice1], dict(
attrs=[u'street', u'c', u'l', u'st', u'postalcode'],
permissions=u'write',
)
),
expected=dict(
value=selfservice1,
summary=u'Added selfservice "%s"' % selfservice1,
result=dict(
attrs=[u'street', u'c', u'l', u'st', u'postalcode'],
permissions=[u'write'],
selfaci=True,
aciname=selfservice1,
),
),
),
dict(
desc='Try to create duplicate %r' % selfservice1,
command=(
'selfservice_add', [selfservice1], dict(
attrs=[u'street', u'c', u'l', u'st', u'postalcode'],
permissions=u'write',
),
),
expected=errors.DuplicateEntry(),
),
dict(
desc='Retrieve %r' % selfservice1,
command=('selfservice_show', [selfservice1], {}),
expected=dict(
value=selfservice1,
summary=None,
result={
'attrs': [u'street', u'c', u'l', u'st', u'postalcode'],
'permissions': [u'write'],
'selfaci': True,
'aciname': selfservice1,
},
),
),
dict(
desc='Retrieve %r with --raw' % selfservice1,
command=('selfservice_show', [selfservice1], {'raw':True}),
expected=dict(
value=selfservice1,
summary=None,
result={
'aci': u'(targetattr = "street || c || l || st || postalcode")(version 3.0;acl "selfservice:testself";allow (write) userdn = "ldap:///self";)',
},
),
),
dict(
desc='Search for %r' % selfservice1,
command=('selfservice_find', [selfservice1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 selfservice matched',
result=[
{
'attrs': [u'street', u'c', u'l', u'st', u'postalcode'],
'permissions': [u'write'],
'selfaci': True,
'aciname': selfservice1,
},
],
),
),
dict(
desc='Search for %r with --pkey-only' % selfservice1,
command=('selfservice_find', [selfservice1], {'pkey_only' : True}),
expected=dict(
count=1,
truncated=False,
summary=u'1 selfservice matched',
result=[
{
'aciname': selfservice1,
},
],
),
),
dict(
desc='Search for %r with empty attrs and permissions' % selfservice1,
command=('selfservice_find', [selfservice1], {'attrs' : None, 'permissions' : None}),
expected=dict(
count=1,
truncated=False,
summary=u'1 selfservice matched',
result=[
{
'attrs': [u'street', u'c', u'l', u'st', u'postalcode'],
'permissions': [u'write'],
'selfaci': True,
'aciname': selfservice1,
},
],
),
),
dict(
desc='Search for %r with --raw' % selfservice1,
command=('selfservice_find', [selfservice1], {'raw':True}),
expected=dict(
count=1,
truncated=False,
summary=u'1 selfservice matched',
result=[
{
'aci': u'(targetattr = "street || c || l || st || postalcode")(version 3.0;acl "selfservice:testself";allow (write) userdn = "ldap:///self";)'
},
],
),
),
dict(
desc='Update %r' % selfservice1,
command=(
'selfservice_mod', [selfservice1], dict(permissions=u'read')
),
expected=dict(
value=selfservice1,
summary=u'Modified selfservice "%s"' % selfservice1,
result=dict(
attrs=[u'street', u'c', u'l', u'st', u'postalcode'],
permissions=[u'read'],
selfaci=True,
aciname=selfservice1,
),
),
),
dict(
desc='Retrieve %r to verify update' % selfservice1,
command=('selfservice_show', [selfservice1], {}),
expected=dict(
value=selfservice1,
summary=None,
result={
'attrs': [u'street', u'c', u'l', u'st', u'postalcode'],
'permissions': [u'read'],
'selfaci': True,
'aciname': selfservice1,
},
),
),
dict(
desc='Try to update %r with empty permissions' % selfservice1,
command=(
'selfservice_mod', [selfservice1], dict(permissions=None)
),
expected=errors.RequirementError(name='permissions'),
),
dict(
desc='Retrieve %r to verify invalid update' % selfservice1,
command=('selfservice_show', [selfservice1], {}),
expected=dict(
value=selfservice1,
summary=None,
result={
'attrs': [u'street', u'c', u'l', u'st', u'postalcode'],
'permissions': [u'read'],
'selfaci': True,
'aciname': selfservice1,
},
),
),
dict(
desc='Delete %r' % selfservice1,
command=('selfservice_del', [selfservice1], {}),
expected=dict(
result=True,
value=selfservice1,
summary=u'Deleted selfservice "%s"' % selfservice1,
)
),
dict(
desc='Create invalid %r' % invalid_selfservice1,
command=(
'selfservice_add', [invalid_selfservice1], dict(
attrs=[u'street', u'c', u'l', u'st', u'postalcode'],
permissions=u'write',
)
),
expected=errors.ValidationError(name='name',
error='May only contain letters, numbers, -, _, and space'),
),
]
| 9,397
|
Python
|
.py
| 251
| 23.621514
| 166
| 0.473915
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,463
|
test_servicedelegation_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_servicedelegation_plugin.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
"""
Test the `ipaserver/plugins/serviceconstraint.py` module.
"""
from ipalib import api, errors
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import Declarative
from ipapython.dn import DN
import pytest
rule1 = u'test1'
rule2 = u'test rule two'
target1 = u'test1-targets'
target2 = u'test2-targets'
princ1 = u'HTTP/%s@%s' % (api.env.host, api.env.realm)
princ2 = u'ldap/%s@%s' % (api.env.host, api.env.realm)
princ3 = u'host/%s@%s' % (api.env.host, api.env.realm)
host3 = api.env.host
def get_servicedelegation_dn(cn):
return DN(('cn', cn), api.env.container_s4u2proxy, api.env.basedn)
@pytest.mark.tier1
class test_servicedelegation(Declarative):
cleanup_commands = [
('servicedelegationrule_del', [rule1], {}),
('servicedelegationrule_del', [rule2], {}),
('servicedelegationtarget_del', [target1], {}),
('servicedelegationtarget_del', [target2], {}),
]
tests = [
################
# create rule1:
dict(
desc='Try to retrieve non-existent %r' % rule1,
command=('servicedelegationrule_show', [rule1], {}),
expected=errors.NotFound(
reason=u'%s: service delegation rule not found' % rule1
),
),
dict(
desc='Try to delete non-existent %r' % rule1,
command=('servicedelegationrule_del', [rule1], {}),
expected=errors.NotFound(
reason=u'%s: service delegation rule not found' % rule1
),
),
dict(
desc='Create %r' % rule1,
command=(
'servicedelegationrule_add', [rule1], {}
),
expected=dict(
value=rule1,
summary=u'Added service delegation rule "%s"' % rule1,
result=dict(
cn=[rule1],
objectclass=objectclasses.servicedelegationrule,
dn=get_servicedelegation_dn(rule1),
),
),
),
dict(
desc='Try to create duplicate %r' % rule1,
command=(
'servicedelegationrule_add', [rule1], {}
),
expected=errors.DuplicateEntry(
message=u'service delegation rule with name "%s" '
'already exists' % rule1),
),
dict(
desc='Retrieve %r' % rule1,
command=('servicedelegationrule_show', [rule1], {}),
expected=dict(
value=rule1,
summary=None,
result=dict(
cn=[rule1],
dn=get_servicedelegation_dn(rule1),
),
),
),
dict(
desc='Search for %r' % rule1,
command=('servicedelegationrule_find', [], dict(cn=rule1)),
expected=dict(
count=1,
truncated=False,
result=[
dict(
dn=get_servicedelegation_dn(rule1),
cn=[rule1],
),
],
summary=u'1 service delegation rule matched',
),
),
################
# create rule2:
dict(
desc='Create %r' % rule2,
command=(
'servicedelegationrule_add', [rule2], {}
),
expected=dict(
value=rule2,
summary=u'Added service delegation rule "%s"' % rule2,
result=dict(
cn=[rule2],
objectclass=objectclasses.servicedelegationrule,
dn=get_servicedelegation_dn(rule2),
),
),
),
dict(
desc='Search for all rules with members',
command=('servicedelegationrule_find', [], {'no_members': False}),
expected=dict(
summary=u'3 service delegation rules matched',
count=3,
truncated=False,
result=[
{
'dn': get_servicedelegation_dn(u'ipa-http-delegation'),
'cn': [u'ipa-http-delegation'],
'memberprincipal': [princ1],
'ipaallowedtarget_servicedelegationtarget':
[u'ipa-ldap-delegation-targets',
u'ipa-cifs-delegation-targets']
},
dict(
dn=get_servicedelegation_dn(rule2),
cn=[rule2],
),
dict(
dn=get_servicedelegation_dn(rule1),
cn=[rule1],
),
],
),
),
dict(
desc='Search for all rules',
command=('servicedelegationrule_find', [], {}),
expected=dict(
summary=u'3 service delegation rules matched',
count=3,
truncated=False,
result=[
{
'dn': get_servicedelegation_dn(u'ipa-http-delegation'),
'cn': [u'ipa-http-delegation'],
'memberprincipal': [princ1],
},
dict(
dn=get_servicedelegation_dn(rule2),
cn=[rule2],
),
dict(
dn=get_servicedelegation_dn(rule1),
cn=[rule1],
),
],
),
),
dict(
desc='Create target %r' % target1,
command=(
'servicedelegationtarget_add', [target1], {}
),
expected=dict(
value=target1,
summary=u'Added service delegation target "%s"' % target1,
result=dict(
cn=[target1],
objectclass=objectclasses.servicedelegationtarget,
dn=get_servicedelegation_dn(target1),
),
),
),
dict(
desc='Create target %r' % target2,
command=(
'servicedelegationtarget_add', [target2], {}
),
expected=dict(
value=target2,
summary=u'Added service delegation target "%s"' % target2,
result=dict(
cn=[target2],
objectclass=objectclasses.servicedelegationtarget,
dn=get_servicedelegation_dn(target2),
),
),
),
dict(
desc='Search for all targets',
command=('servicedelegationtarget_find', [], {}),
expected=dict(
summary=u'4 service delegation targets matched',
count=4,
truncated=False,
result=[
{
'dn': get_servicedelegation_dn(
u'ipa-cifs-delegation-targets'),
'cn': [u'ipa-cifs-delegation-targets'],
},
{
'dn': get_servicedelegation_dn(
u'ipa-ldap-delegation-targets'
),
'cn': [u'ipa-ldap-delegation-targets'],
'memberprincipal': [princ2],
},
dict(
dn=get_servicedelegation_dn(target1),
cn=[target1],
),
dict(
dn=get_servicedelegation_dn(target2),
cn=[target2],
),
],
),
),
###############
# member stuff:
dict(
desc='Add member %r to %r' % (target1, rule1),
command=(
'servicedelegationrule_add_target', [rule1],
dict(servicedelegationtarget=target1)
),
expected=dict(
completed=1,
failed=dict(
ipaallowedtarget=dict(
servicedelegationtarget=tuple(),
),
),
result={
'dn': get_servicedelegation_dn(rule1),
'ipaallowedtarget_servicedelegationtarget': (target1,),
'cn': [rule1],
},
),
),
dict(
desc='Add duplicate target %r to %r' % (target1, rule1),
command=(
'servicedelegationrule_add_target', [rule1],
dict(servicedelegationtarget=target1)
),
expected=dict(
completed=0,
failed=dict(
ipaallowedtarget=dict(
servicedelegationtarget=[
[target1, u'This entry is already a member']
],
),
),
result={
'dn': get_servicedelegation_dn(rule1),
'ipaallowedtarget_servicedelegationtarget': (target1,),
'cn': [rule1],
},
),
),
dict(
desc='Add non-existent target %r to %r' % (u'notfound', rule1),
command=(
'servicedelegationrule_add_target', [rule1],
dict(servicedelegationtarget=u'notfound')
),
expected=dict(
completed=0,
failed=dict(
ipaallowedtarget=dict(
servicedelegationtarget=[
[u'notfound', u'no such entry']
],
),
),
result={
'dn': get_servicedelegation_dn(rule1),
'ipaallowedtarget_servicedelegationtarget': (target1,),
'cn': [rule1],
},
),
),
dict(
desc='Remove a target %r from %r' % (target1, rule1),
command=(
'servicedelegationrule_remove_target', [rule1],
dict(servicedelegationtarget=target1)
),
expected=dict(
completed=1,
failed=dict(
ipaallowedtarget=dict(
servicedelegationtarget=tuple(),
),
),
result={
'dn': get_servicedelegation_dn(rule1),
'cn': [rule1],
},
),
),
dict(
desc='Remove non-existent target %r from %r' % (
u'notfound', rule1
),
command=(
'servicedelegationrule_remove_target', [rule1],
dict(servicedelegationtarget=u'notfound')
),
expected=dict(
completed=0,
failed=dict(
ipaallowedtarget=dict(
servicedelegationtarget=[
[u'notfound', u'This entry is not a member']
],
),
),
result={
'dn': get_servicedelegation_dn(rule1),
'cn': [rule1],
},
),
),
###############
# memberprincipal member stuff:
dict(
desc='Add memberprinc %r to %r' % (princ1, rule1),
command=(
'servicedelegationrule_add_member', [rule1],
dict(principal=princ1)
),
expected=dict(
completed=1,
failed=dict(
failed_memberprincipal=dict(
memberprincipal=tuple(),
),
),
result={
'dn': get_servicedelegation_dn(rule1),
'memberprincipal': (princ1,),
'cn': [rule1],
},
),
),
dict(
desc='Add duplicate member %r to %r' % (princ1, rule1),
command=(
'servicedelegationrule_add_member', [rule1],
dict(principal=princ1)
),
expected=dict(
completed=0,
failed=dict(
failed_memberprincipal=dict(
memberprincipal=[
[princ1, u'This entry is already a member']
],
),
),
result={
'dn': get_servicedelegation_dn(rule1),
'memberprincipal': (princ1,),
'cn': [rule1],
},
),
),
dict(
desc='Add non-existent member %r to %r' % (
u'HTTP/notfound', rule1
),
command=(
'servicedelegationrule_add_member', [rule1],
dict(principal=u'HTTP/notfound@%s' % api.env.realm)
),
expected=dict(
completed=0,
failed=dict(
failed_memberprincipal=dict(
memberprincipal=[
[u'HTTP/notfound@%s' % api.env.realm,
u'no matching entry found']
],
),
),
result={
'dn': get_servicedelegation_dn(rule1),
'memberprincipal': (princ1,),
'cn': [rule1],
},
),
),
dict(
desc='Add host as a member %r to %r' % (host3, rule1),
command=(
'servicedelegationrule_add_member', [rule1],
dict(principal=princ3)
),
expected=dict(
completed=1,
failed=dict(
failed_memberprincipal=dict(
memberprincipal=tuple(),
),
),
result={
'dn': get_servicedelegation_dn(rule1),
'memberprincipal': (princ1, princ3),
'cn': [rule1],
},
),
),
dict(
desc='Remove a host member %r from %r' % (host3, rule1),
command=(
'servicedelegationrule_remove_member', [rule1],
dict(principal=host3)
),
expected=dict(
completed=1,
failed=dict(
failed_memberprincipal=dict(
memberprincipal=tuple(),
),
),
result={
'dn': get_servicedelegation_dn(rule1),
'memberprincipal': (princ1,),
'cn': [rule1],
},
),
),
dict(
desc='Remove a member %r from %r' % (princ1, rule1),
command=(
'servicedelegationrule_remove_member', [rule1],
dict(principal=princ1)
),
expected=dict(
completed=1,
failed=dict(
failed_memberprincipal=dict(
memberprincipal=tuple(),
),
),
result={
'dn': get_servicedelegation_dn(rule1),
'memberprincipal': [],
'cn': [rule1],
},
),
),
dict(
desc='Remove non-existent member %r from %r' % (
u'HTTP/notfound', rule1
),
command=(
'servicedelegationrule_remove_member', [rule1],
dict(principal=u'HTTP/notfound@%s' % api.env.realm)
),
expected=dict(
completed=0,
failed=dict(
failed_memberprincipal=dict(
memberprincipal=[
[u'HTTP/notfound@%s' % api.env.realm,
u'This entry is not a member']
],
),
),
result={
'dn': get_servicedelegation_dn(rule1),
'cn': [rule1],
},
),
),
dict(
desc='Add memberprinc %r to %r' % (princ1, target1),
command=(
'servicedelegationtarget_add_member', [target1],
dict(principal=princ1)
),
expected=dict(
completed=1,
failed=dict(
failed_memberprincipal=dict(
memberprincipal=tuple(),
),
),
result={
'dn': get_servicedelegation_dn(target1),
'memberprincipal': (princ1,),
'cn': [target1],
},
),
),
dict(
desc='Add duplicate member %r to %r' % (princ1, target1),
command=(
'servicedelegationtarget_add_member', [target1],
dict(principal=princ1)
),
expected=dict(
completed=0,
failed=dict(
failed_memberprincipal=dict(
memberprincipal=[
[princ1, u'This entry is already a member']
],
),
),
result={
'dn': get_servicedelegation_dn(target1),
'memberprincipal': (princ1,),
'cn': [target1],
},
),
),
dict(
desc='Add non-existent member %r to %r' % (
u'HTTP/notfound', target1
),
command=(
'servicedelegationtarget_add_member', [target1],
dict(principal=u'HTTP/notfound@%s' % api.env.realm)
),
expected=dict(
completed=0,
failed=dict(
failed_memberprincipal=dict(
memberprincipal=[
[u'HTTP/notfound@%s' % api.env.realm,
u'no matching entry found']
],
),
),
result={
'dn': get_servicedelegation_dn(target1),
'memberprincipal': (princ1,),
'cn': [target1],
},
),
),
dict(
desc='Remove a member %r from %r' % (princ1, target1),
command=(
'servicedelegationtarget_remove_member', [target1],
dict(principal=princ1)
),
expected=dict(
completed=1,
failed=dict(
failed_memberprincipal=dict(
memberprincipal=tuple(),
),
),
result={
'dn': get_servicedelegation_dn(target1),
'memberprincipal': [],
'cn': [target1],
},
),
),
dict(
desc='Remove non-existent member %r from %r' % (
u'HTTP/notfound', target1
),
command=(
'servicedelegationtarget_remove_member', [target1],
dict(principal=u'HTTP/notfound@%s' % api.env.realm)
),
expected=dict(
completed=0,
failed=dict(
failed_memberprincipal=dict(
memberprincipal=[
[u'HTTP/notfound@%s' % api.env.realm,
u'This entry is not a member']
],
),
),
result={
'dn': get_servicedelegation_dn(target1),
'cn': [target1],
},
),
),
]
| 20,783
|
Python
|
.py
| 599
| 18.310518
| 79
| 0.406005
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,464
|
test_permission_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_permission_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Pavel Zuna <pzuna@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 the `ipaserver/plugins/permission.py` module.
"""
from __future__ import print_function
import os
from ipalib import api, errors
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import Declarative
from ipapython.dn import DN
import inspect
import pytest
try:
from ipaserver.plugins.ldap2 import ldap2
except ImportError:
have_ldap2 = False
else:
have_ldap2 = True
permission1 = u'testperm'
permission1_dn = DN(('cn',permission1),
api.env.container_permission,api.env.basedn)
permission1_renamed = u'testperm1_rn'
permission1_renamed_dn = DN(('cn',permission1_renamed),
api.env.container_permission,api.env.basedn)
permission1_renamed_ucase = u'Testperm_RN'
permission1_renamed_ucase_dn = DN(('cn',permission1_renamed_ucase),
api.env.container_permission,api.env.basedn)
permission2 = u'testperm2'
permission2_dn = DN(('cn',permission2),
api.env.container_permission,api.env.basedn)
permission3 = u'testperm3'
permission3_dn = DN(('cn',permission3),
api.env.container_permission,api.env.basedn)
permission3_attributelevelrights = {
'member': u'rscwo',
'seealso': u'rscwo',
'ipapermissiontype': u'rscwo',
'cn': u'rscwo',
'businesscategory': u'rscwo',
'objectclass': u'rscwo',
'memberof': u'rscwo',
'aci': u'rscwo',
'ipapermlocation': u'rscwo',
'o': u'rscwo',
'ipapermincludedattr': u'rscwo',
'ipapermdefaultattr': u'rscwo',
'ipapermexcludedattr': u'rscwo',
'owner': u'rscwo',
'ou': u'rscwo',
'ipapermright': u'rscwo',
'nsaccountlock': u'rscwo',
'description': u'rscwo',
'ipapermtargetfilter': u'rscwo',
'ipapermtargetto': u'rscwo',
'ipapermtargetfrom': u'rscwo',
'ipapermbindruletype': u'rscwo',
'ipapermtarget': u'rscwo',
'type': u'rscwo',
'targetgroup': u'rscwo',
'attrs': u'rscwo',
}
privilege1 = u'testpriv1'
privilege1_dn = DN(('cn',privilege1),
api.env.container_privilege,api.env.basedn)
invalid_permission1 = u'bad;perm'
users_dn = DN(api.env.container_user, api.env.basedn)
groups_dn = DN(api.env.container_group, api.env.basedn)
etc_dn = DN('cn=etc', api.env.basedn)
nonexistent_dn = DN('cn=does not exist', api.env.basedn)
admin_dn = DN('uid=admin', users_dn)
group_filter = u'(|(objectclass=ipausergroup)(objectclass=posixgroup))'
def verify_permission_aci(name, dn, acistring):
"""Return test dict that verifies the ACI at the given location"""
return dict(
desc="Verify ACI of %s #(%s)" % (name, lineinfo(2)),
command=('aci_show', [name], dict(
aciprefix=u'permission', location=dn, raw=True)),
expected=dict(
result=dict(aci=acistring),
summary=None,
value=name,
),
)
def verify_permission_aci_missing(name, dn):
"""Return test dict that checks the ACI at the given location is missing"""
return dict(
desc="Verify ACI of %s is missing #(%s)" % (name, lineinfo(2)),
command=('aci_show', [name], dict(
aciprefix=u'permission', location=dn, raw=True)),
expected=errors.NotFound(
reason='ACI with name "%s" not found' % name),
)
def lineinfo(level):
"""Return "filename:lineno" for `level`-th caller"""
# Declarative tests hide tracebacks.
# Including this info in the test name makes it possible
# to locate failing tests.
frame = inspect.currentframe()
for _i in range(level):
frame = frame.f_back
lineno = frame.f_lineno
filename = os.path.basename(frame.f_code.co_filename)
return '%s:%s' % (filename, lineno)
@pytest.mark.tier1
class test_permission_negative(Declarative):
"""Make sure invalid operations fail"""
cleanup_commands = [
('permission_del', [permission1], {'force': True}),
]
tests = [
dict(
desc='Try to retrieve non-existent %r' % permission1,
command=('permission_show', [permission1], {}),
expected=errors.NotFound(
reason=u'%s: permission not found' % permission1),
),
dict(
desc='Try to update non-existent %r' % permission1,
command=('permission_mod', [permission1], dict(ipapermright=u'all')),
expected=errors.NotFound(
reason=u'%s: permission not found' % permission1),
),
dict(
desc='Try to delete non-existent %r' % permission1,
command=('permission_del', [permission1], {}),
expected=errors.NotFound(
reason=u'%s: permission not found' % permission1),
),
dict(
desc='Search for non-existent %r' % permission1,
command=('permission_find', [permission1], {}),
expected=dict(
count=0,
truncated=False,
summary=u'0 permissions matched',
result=[],
),
),
dict(
desc='Try creating %r with no ipapermright' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
attrs=[u'sn'],
)
),
expected=errors.RequirementError(name='right'),
),
dict(
desc='Try creating %r with no target option' % permission1,
command=(
'permission_add', [permission1], dict(
ipapermright=u'write',
)
),
expected=errors.ValidationError(
name='target',
error='there must be at least one target entry specifier '
'(e.g. target, targetfilter, attrs)'),
),
verify_permission_aci_missing(permission1, api.env.basedn),
dict(
desc='Try to create invalid %r' % invalid_permission1,
command=('permission_add', [invalid_permission1], dict(
type=u'user',
ipapermright=u'write',
)),
expected=errors.ValidationError(name='name',
error='May only contain letters, numbers, -, _, ., and space'),
),
verify_permission_aci_missing(permission1, users_dn),
dict(
desc='Try creating %r with bad attribute name' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
ipapermright=u'write',
attrs=u'bogusattr',
)
),
expected=errors.InvalidSyntax(
attr=r'targetattr "bogusattr" does not exist in schema. '
r'Please add attributeTypes "bogusattr" to '
r'schema if necessary. '
r'ACL Syntax Error(-5):'
r'(targetattr = \22bogusattr\22)'
r'(targetfilter = \22(objectclass=posixaccount)\22)'
r'(version 3.0;acl \22permission:%(name)s\22;'
r'allow (write) groupdn = \22ldap:///%(dn)s\22;)' % dict(
name=permission1,
dn=permission1_dn),
),
),
verify_permission_aci_missing(permission1, users_dn),
dict(
desc='Try to create permission with : in the name',
command=('permission_add', ['bad:' + permission1], dict(
type=u'user',
ipapermright=u'write',
)),
expected=errors.ValidationError(name='name',
error='May only contain letters, numbers, -, _, ., and space'),
),
verify_permission_aci_missing(permission1, users_dn),
dict(
desc='Try to create permission with full and extra target filter',
command=('permission_add', [permission1], dict(
type=u'user',
ipapermright=u'write',
ipapermtargetfilter=u'(cn=*)',
extratargetfilter=u'(sn=*)',
)),
expected=errors.ValidationError(name='ipapermtargetfilter',
error='cannot specify full target filter and extra target '
'filter simultaneously'),
),
verify_permission_aci_missing(permission1, users_dn),
dict(
desc='Create %r so we can try breaking it' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
ipapermright=[u'write'],
attrs=[u'sn'],
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
dict(
desc='Try remove ipapermright from %r' % permission1,
command=(
'permission_mod', [permission1], dict(
ipapermright=None,
)
),
expected=errors.RequirementError(name='right'),
),
dict(
desc='Try to remove type from %r' % permission1,
command=(
'permission_mod', [permission1], dict(
attrs=None,
type=None,
)
),
expected=errors.ValidationError(
name='target',
error='there must be at least one target entry specifier '
'(e.g. target, targetfilter, attrs)'),
),
dict(
desc='Try to "remove" empty memberof from %r' % permission1,
command=(
'permission_mod', [permission1], dict(
memberof=None,
)
),
expected=errors.EmptyModlist(),
),
dict(
desc='Try to remove targetfilter and memberof from %r' % permission1,
command=(
'permission_mod', [permission1], dict(
attrs=None,
ipapermtargetfilter=None,
)
),
expected=errors.ValidationError(
name='target',
error='there must be at least one target entry specifier '
'(e.g. target, targetfilter, attrs)'),
),
dict(
desc='Try to rename %r to invalid %r' % (
permission1, invalid_permission1),
command=('permission_mod', [permission1], dict(
rename=invalid_permission1,
)),
expected=errors.ValidationError(name='rename',
error='May only contain letters, numbers, -, _, ., and space'),
),
dict(
desc='Try setting ipapermexcludedattr on %r' % permission1,
command=(
'permission_mod', [permission1], dict(
ipapermexcludedattr=[u'cn'],
)
),
expected=errors.ValidationError(
name='ipapermexcludedattr',
error='only available on managed permissions'),
),
dict(
desc='Try to setting both full and extra target filter on %s' % permission1,
command=('permission_mod', [permission1], dict(
ipapermtargetfilter=u'(cn=*)',
extratargetfilter=u'(sn=*)',
)),
expected=errors.ValidationError(name='ipapermtargetfilter',
error='cannot specify full target filter and extra target '
'filter simultaneously'),
),
]
@pytest.mark.tier1
class test_permission(Declarative):
"""Misc. tests for the permission plugin"""
cleanup_commands = [
('permission_del', [permission1], {'force': True}),
('permission_del', [permission2], {'force': True}),
('permission_del', [permission3], {'force': True}),
('permission_del', [permission1_renamed], {'force': True}),
('permission_del', [permission1_renamed_ucase], {'force': True}),
('privilege_del', [privilege1], {}),
]
tests = [
dict(
desc='Create %r' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
ipapermright=[u'write'],
attrs=[u'sn'],
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Try to create duplicate %r' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
ipapermright=[u'write'],
attrs=[u'sn'],
),
),
expected=errors.DuplicateEntry(
message='permission with name "%s" already exists' % permission1),
),
dict(
desc='Create %r' % privilege1,
command=('privilege_add', [privilege1],
dict(description=u'privilege desc. 1')
),
expected=dict(
value=privilege1,
summary=u'Added privilege "%s"' % privilege1,
result=dict(
dn=privilege1_dn,
cn=[privilege1],
description=[u'privilege desc. 1'],
objectclass=objectclasses.privilege,
),
),
),
dict(
desc='Add permission %r to privilege %r' % (permission1, privilege1),
command=('privilege_add_permission', [privilege1],
dict(permission=permission1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
permission=[],
),
),
result={
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
'memberof_permission': [permission1],
}
),
),
dict(
desc='Retrieve %r' % permission1,
command=('permission_show', [permission1], {}),
expected=dict(
value=permission1,
summary=None,
result={
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
),
),
dict(
desc='Retrieve %r with --raw' % permission1,
command=('permission_show', [permission1], {'raw': True}),
expected=dict(
value=permission1,
summary=None,
result={
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member': [privilege1_dn],
'ipapermincludedattr': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermright': [u'write'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
'ipapermtargetfilter': [u'(objectclass=posixaccount)'],
'aci': ['(targetattr = "sn")'
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%(name)s";'
'allow (write) groupdn = "ldap:///%(pdn)s";)' %
{'name': permission1,
'pdn': permission1_dn}],
},
),
),
dict(
desc='Search for %r with members' % permission1,
command=('permission_find', [permission1], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
],
),
),
dict(
desc='Search for %r' % permission1,
command=('permission_find', [permission1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
],
),
),
dict(
desc='Search for %r using --name with members' % permission1,
command=('permission_find', [], {
'cn': permission1, 'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
],
),
),
dict(
desc='Search for %r using --name' % permission1,
command=('permission_find', [], {'cn': permission1}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
],
),
),
dict(
desc='Search for non-existent permission using --name',
command=('permission_find', [], {'cn': u'notfound'}),
expected=dict(
count=0,
truncated=False,
summary=u'0 permissions matched',
result=[],
),
),
dict(
desc='Search for %r with members' % privilege1,
command=('permission_find', [privilege1], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
],
),
),
dict(
desc='Search for %r' % privilege1,
command=('permission_find', [privilege1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
],
),
),
dict(
desc='Search for %r with --raw with members' % permission1,
command=('permission_find', [permission1], {
'raw': True, 'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member': [privilege1_dn],
'ipapermincludedattr': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermright': [u'write'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
'ipapermtargetfilter': [u'(objectclass=posixaccount)'],
'aci': ['(targetattr = "sn")'
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%(name)s";'
'allow (write) groupdn = "ldap:///%(pdn)s";)' %
{'name': permission1,
'pdn': permission1_dn}],
},
],
),
),
dict(
desc='Search for %r with --raw' % permission1,
command=('permission_find', [permission1], {'raw': True}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'ipapermincludedattr': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermright': [u'write'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
'ipapermtargetfilter': [u'(objectclass=posixaccount)'],
'aci': ['(targetattr = "sn")'
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%(name)s";'
'allow (write) groupdn = "ldap:///%(pdn)s";)' %
{'name': permission1,
'pdn': permission1_dn}],
},
],
),
),
dict(
desc='Create %r' % permission2,
command=(
'permission_add', [permission2], dict(
type=u'user',
ipapermright=u'write',
setattr=u'owner=cn=test',
addattr=u'owner=cn=test2',
attrs=[u'cn'],
)
),
expected=dict(
value=permission2,
summary=u'Added permission "%s"' % permission2,
result=dict(
dn=permission2_dn,
cn=[permission2],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
owner=[u'cn=test', u'cn=test2'],
attrs=[u'cn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission2, users_dn,
'(targetattr = "cn")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission2 +
'allow (write) groupdn = "ldap:///%s";)' % permission2_dn,
),
dict(
desc='Search for %r with members' % permission1,
command=('permission_find', [permission1], {
'no_members': False}),
expected=dict(
count=2,
truncated=False,
summary=u'2 permissions matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
{
'dn': permission2_dn,
'cn': [permission2],
'objectclass': objectclasses.permission,
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'cn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
],
),
),
dict(
desc='Search for %r' % permission1,
command=('permission_find', [permission1], {}),
expected=dict(
count=2,
truncated=False,
summary=u'2 permissions matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
{
'dn': permission2_dn,
'cn': [permission2],
'objectclass': objectclasses.permission,
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'cn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
],
),
),
dict(
desc='Search for %r with --pkey-only' % permission1,
command=('permission_find', [permission1], {'pkey_only' : True}),
expected=dict(
count=2,
truncated=False,
summary=u'2 permissions matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
},
{
'dn': permission2_dn,
'cn': [permission2],
},
],
),
),
dict(
desc='Search by ACI attribute with --pkey-only',
command=('permission_find', [], {'pkey_only': True,
'attrs': [u'krbminpwdlife']}),
expected=dict(
count=2,
truncated=False,
summary=u'2 permissions matched',
result=[
{
'dn': DN(('cn', 'System: Modify Group Password Policy'),
api.env.container_permission, api.env.basedn),
'cn': [u'System: Modify Group Password Policy'],
},
{
'dn': DN(('cn', 'System: Read Group Password Policy'),
api.env.container_permission, api.env.basedn),
'cn': [u'System: Read Group Password Policy'],
},
],
),
),
dict(
desc='Search for %r with members' % privilege1,
command=('privilege_find', [privilege1], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 privilege matched',
result=[
{
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
'memberof_permission': [permission1],
},
],
),
),
dict(
desc='Search for %r' % privilege1,
command=('privilege_find', [privilege1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 privilege matched',
result=[
{
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
},
],
),
),
dict(
desc=('Search for %r with a limit of 1 (truncated) with members' %
permission1),
command=('permission_find', [permission1],
dict(sizelimit=1, no_members=False)),
expected=dict(
count=1,
truncated=True,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
],
messages=(
{
'message': (u'Search result has been truncated: '
u'Configured size limit exceeded'),
'code': 13017,
'type': u'warning',
'name': u'SearchResultTruncated',
'data': {
'reason': u"Configured size limit exceeded"
}
},
),
),
),
dict(
desc='Search for %r with a limit of 1 (truncated)' % permission1,
command=('permission_find', [permission1], dict(sizelimit=1)),
expected=dict(
count=1,
truncated=True,
summary=u'1 permission matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
],
messages=(
{
'message': (u'Search result has been truncated: '
u'Configured size limit exceeded'),
'code': 13017,
'type': u'warning',
'name': u'SearchResultTruncated',
'data': {
'reason': u"Configured size limit exceeded"
}
},
),
),
),
dict(
desc='Search for %r with a limit of 2' % permission1,
command=('permission_find', [permission1], dict(sizelimit=2)),
expected=dict(
count=2,
truncated=False,
summary=u'2 permissions matched',
result=[
{
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
{
'dn': permission2_dn,
'cn': [permission2],
'objectclass': objectclasses.permission,
'type': [u'user'],
'ipapermright': [u'write'],
'attrs': [u'cn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
],
),
),
# This tests setting truncated to True in the post_callback of
# permission_find(). The return order in LDAP is not guaranteed
# so do not check the actual entry.
dict(
desc='Search for permissions by attr with a limit of 1 (truncated)',
command=('permission_find', [u'Modify'],
dict(attrs=u'ipaenabledflag', sizelimit=1)),
expected=dict(
count=1,
truncated=True,
summary=u'1 permission matched',
result=[lambda res:
DN(res['dn']).endswith(DN(api.env.container_permission,
api.env.basedn)) and
'ipapermission' in res['objectclass']],
messages=(
{
'message': (u'Search result has been truncated: '
u'Configured size limit exceeded'),
'code': 13017,
'type': u'warning',
'name': u'SearchResultTruncated',
'data': {
'reason': u"Configured size limit exceeded"
}
},
),
),
),
dict(
desc='Update %r' % permission1,
command=(
'permission_mod', [permission1], dict(
ipapermright=u'read',
memberof=u'ipausers',
setattr=u'owner=cn=other-test',
addattr=u'owner=cn=other-test2',
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
member_privilege=[privilege1],
type=[u'user'],
ipapermright=[u'read'],
memberof=[u'ipausers'],
owner=[u'cn=other-test', u'cn=other-test2'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(&' +
'(memberOf=%s)' % DN('cn=ipausers', groups_dn) +
'(objectclass=posixaccount))")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (read) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Retrieve %r to verify update' % permission1,
command=('permission_show', [permission1], {}),
expected=dict(
value=permission1,
summary=None,
result={
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': [u'user'],
'ipapermright': [u'read'],
'memberof': [u'ipausers'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
),
),
dict(
desc='Try to rename %r to existing permission %r' % (permission1,
permission2),
command=(
'permission_mod', [permission1], dict(rename=permission2,
ipapermright=u'all',)
),
expected=errors.DuplicateEntry(),
),
dict(
desc='Try to rename %r to empty name' % (permission1),
command=(
'permission_mod', [permission1], dict(rename=u'',
ipapermright=u'all',)
),
expected=errors.ValidationError(name='rename',
error=u'New name can not be empty'),
),
dict(
desc='Check integrity of original permission %r' % permission1,
command=('permission_show', [permission1], {}),
expected=dict(
value=permission1,
summary=None,
result={
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': [u'user'],
'ipapermright': [u'read'],
'memberof': [u'ipausers'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
),
),
dict(
desc='Rename %r to permission %r' % (permission1,
permission1_renamed),
command=(
'permission_mod', [permission1], dict(rename=permission1_renamed,
ipapermright= u'all',)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result={
'dn': permission1_renamed_dn,
'cn': [permission1_renamed],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': [u'user'],
'ipapermright': [u'all'],
'memberof': [u'ipausers'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
),
),
verify_permission_aci_missing(permission1, users_dn),
verify_permission_aci(
permission1_renamed, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(&' +
'(memberOf=%s)' % DN('cn=ipausers', groups_dn) +
'(objectclass=posixaccount))")' +
'(version 3.0;acl "permission:%s";' % permission1_renamed +
'allow (all) groupdn = "ldap:///%s";)' % permission1_renamed_dn,
),
dict(
desc='Rename %r to permission %r' % (permission1_renamed,
permission1_renamed_ucase),
command=(
'permission_mod', [permission1_renamed], dict(rename=permission1_renamed_ucase,
ipapermright= u'write',)
),
expected=dict(
value=permission1_renamed,
summary=u'Modified permission "%s"' % permission1_renamed,
result={
'dn': permission1_renamed_ucase_dn,
'cn': [permission1_renamed_ucase],
'objectclass': objectclasses.permission,
'member_privilege': [privilege1],
'type': [u'user'],
'ipapermright': [u'write'],
'memberof': [u'ipausers'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
},
),
),
verify_permission_aci_missing(permission1_renamed, users_dn),
verify_permission_aci(
permission1_renamed_ucase, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(&' +
'(memberOf=%s)' % DN('cn=ipausers', groups_dn) +
'(objectclass=posixaccount))")' +
'(version 3.0;acl "permission:%s";' % permission1_renamed_ucase +
'allow (write) groupdn = "ldap:///%s";)' %
permission1_renamed_ucase_dn,
),
dict(
desc='Change %r to a subtree type' % permission1_renamed_ucase,
command=(
'permission_mod', [permission1_renamed_ucase],
dict(ipapermlocation=users_dn, type=None)
),
expected=dict(
value=permission1_renamed_ucase,
summary=u'Modified permission "%s"' % permission1_renamed_ucase,
result=dict(
dn=permission1_renamed_ucase_dn,
cn=[permission1_renamed_ucase],
objectclass=objectclasses.permission,
member_privilege=[privilege1],
ipapermlocation=[users_dn],
ipapermright=[u'write'],
memberof=[u'ipausers'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
),
),
),
verify_permission_aci(
permission1_renamed_ucase, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(memberOf=%s)")' % DN('cn=ipausers', groups_dn) +
'(version 3.0;acl "permission:%s";' % permission1_renamed_ucase +
'allow (write) groupdn = "ldap:///%s";)' %
permission1_renamed_ucase_dn,
),
dict(
desc='Reset --subtree of %r' % permission2,
command=(
'permission_mod', [permission2],
dict(ipapermlocation=api.env.basedn)
),
expected=dict(
value=permission2,
summary=u'Modified permission "%s"' % permission2,
result={
'dn': permission2_dn,
'cn': [permission2],
'objectclass': objectclasses.permission,
'ipapermright': [u'write'],
'attrs': [u'cn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'extratargetfilter': [u'(objectclass=posixaccount)'],
'ipapermlocation': [api.env.basedn],
},
),
),
verify_permission_aci(
permission2, api.env.basedn,
'(targetattr = "cn")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission2 +
'allow (write) groupdn = "ldap:///%s";)' % permission2_dn,
),
dict(
desc='Change subtree of %r to admin' % permission1_renamed_ucase,
command=(
'permission_mod', [permission1_renamed_ucase],
dict(ipapermlocation=admin_dn)
),
expected=dict(
value=permission1_renamed_ucase,
summary=u'Modified permission "%s"' % permission1_renamed_ucase,
result=dict(
dn=permission1_renamed_ucase_dn,
cn=[permission1_renamed_ucase],
objectclass=objectclasses.permission,
member_privilege=[privilege1],
ipapermlocation=[admin_dn],
ipapermright=[u'write'],
memberof=[u'ipausers'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
),
),
),
verify_permission_aci(
permission1_renamed_ucase, admin_dn,
'(targetattr = "sn")' +
'(targetfilter = "(memberOf=%s)")' % DN('cn=ipausers', groups_dn) +
'(version 3.0;acl "permission:%s";' % permission1_renamed_ucase +
'allow (write) groupdn = "ldap:///%s";)' %
permission1_renamed_ucase_dn,
),
dict(
desc=('Search for %r using --subtree with membes' %
permission1_renamed_ucase),
command=('permission_find', [],
{'ipapermlocation': u'ldap:///%s' % admin_dn,
'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn':permission1_renamed_ucase_dn,
'cn':[permission1_renamed_ucase],
'objectclass': objectclasses.permission,
'member_privilege':[privilege1],
'ipapermlocation': [admin_dn],
'ipapermright':[u'write'],
'memberof':[u'ipausers'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
},
],
),
),
dict(
desc='Search for %r using --subtree' % permission1_renamed_ucase,
command=('permission_find', [],
{'ipapermlocation': u'ldap:///%s' % admin_dn}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn':permission1_renamed_ucase_dn,
'cn':[permission1_renamed_ucase],
'objectclass': objectclasses.permission,
'ipapermlocation': [admin_dn],
'ipapermright':[u'write'],
'memberof':[u'ipausers'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
},
],
),
),
dict(
desc='Search using nonexistent --subtree',
command=('permission_find', [], {'ipapermlocation': u'foo'}),
expected=errors.ConversionError(
name='subtree', error='malformed RDN string = "foo"'),
),
dict(
desc='Search using --targetgroup with members',
command=('permission_find', [], {
'targetgroup': u'ipausers', 'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': DN(('cn', 'System: Add User to default group'),
api.env.container_permission, api.env.basedn),
'cn': [u'System: Add User to default group'],
'objectclass': objectclasses.permission,
'member_privilege': [u'User Administrators'],
'attrs': [u'member'],
'targetgroup': [u'ipausers'],
'memberindirect_role': [u'User Administrator'],
'ipapermright': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermtarget': [DN(
'cn=ipausers', api.env.container_group,
api.env.basedn)],
'ipapermlocation': [groups_dn],
'ipapermdefaultattr': [u'member'],
'ipapermissiontype': [u'V2', u'MANAGED', u'SYSTEM'],
}
],
),
),
dict(
desc='Search using --targetgroup',
command=('permission_find', [], {'targetgroup': u'ipausers'}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
{
'dn': DN(('cn', 'System: Add User to default group'),
api.env.container_permission, api.env.basedn),
'cn': [u'System: Add User to default group'],
'objectclass': objectclasses.permission,
'attrs': [u'member'],
'targetgroup': [u'ipausers'],
'ipapermright': [u'write'],
'ipapermbindruletype': [u'permission'],
'ipapermtarget': [DN(
'cn=ipausers', api.env.container_group,
api.env.basedn)],
'ipapermlocation': [groups_dn],
'ipapermdefaultattr': [u'member'],
'ipapermissiontype': [u'V2', u'MANAGED', u'SYSTEM'],
}
],
),
),
dict(
desc='Delete %r' % permission1_renamed_ucase,
command=('permission_del', [permission1_renamed_ucase], {}),
expected=dict(
result=dict(failed=[]),
value=[permission1_renamed_ucase],
summary=u'Deleted permission "%s"' % permission1_renamed_ucase,
)
),
verify_permission_aci_missing(permission1_renamed_ucase, users_dn),
dict(
desc='Try to delete non-existent %r' % permission1,
command=('permission_del', [permission1], {}),
expected=errors.NotFound(
reason=u'%s: permission not found' % permission1),
),
dict(
desc='Try to retrieve non-existent %r' % permission1,
command=('permission_show', [permission1], {}),
expected=errors.NotFound(
reason=u'%s: permission not found' % permission1),
),
dict(
desc='Try to update non-existent %r' % permission1,
command=('permission_mod', [permission1], dict(rename=u'Foo')),
expected=errors.NotFound(
reason=u'%s: permission not found' % permission1),
),
dict(
desc='Delete %r' % permission2,
command=('permission_del', [permission2], {}),
expected=dict(
result=dict(failed=[]),
value=[permission2],
summary=u'Deleted permission "%s"' % permission2,
)
),
verify_permission_aci_missing(permission2, users_dn),
dict(
desc='Search for %r' % permission1,
command=('permission_find', [permission1], {}),
expected=dict(
count=0,
truncated=False,
summary=u'0 permissions matched',
result=[],
),
),
dict(
desc='Delete %r' % privilege1,
command=('privilege_del', [privilege1], {}),
expected=dict(
result=dict(failed=[]),
value=[privilege1],
summary=u'Deleted privilege "%s"' % privilege1,
)
),
dict(
desc='Try to create permission %r with non-existing memberof' % permission1,
command=(
'permission_add', [permission1], dict(
memberof=u'nonexisting',
ipapermright=u'write',
attrs=[u'cn'],
)
),
expected=errors.NotFound(reason=u'nonexisting: group not found'),
),
dict(
desc='Create memberof permission %r' % permission1,
command=(
'permission_add', [permission1], dict(
memberof=u'editors',
ipapermright=u'write',
type=u'user',
attrs=[u'sn'],
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
memberof=[u'editors'],
ipapermright=[u'write'],
type=[u'user'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(&(memberOf=%s)' % DN('cn=editors', groups_dn) +
'(objectclass=posixaccount))")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Try to update non-existent memberof of %r' % permission1,
command=('permission_mod', [permission1], dict(
memberof=u'nonexisting')),
expected=errors.NotFound(reason=u'nonexisting: group not found'),
),
dict(
desc='Update memberof permission %r' % permission1,
command=(
'permission_mod', [permission1], dict(
memberof=u'admins',
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
memberof=[u'admins'],
ipapermright=[u'write'],
type=[u'user'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(&' +
'(memberOf=%s)' % DN('cn=admins', groups_dn) +
'(objectclass=posixaccount))")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Unset memberof of permission %r' % permission1,
command=(
'permission_mod', [permission1], dict(
memberof=None,
)
),
expected=dict(
summary=u'Modified permission "%s"' % permission1,
value=permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
type=[u'user'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Delete %r' % permission1,
command=('permission_del', [permission1], {}),
expected=dict(
result=dict(failed=[]),
value=[permission1],
summary=u'Deleted permission "%s"' % permission1,
)
),
verify_permission_aci_missing(permission1, users_dn),
dict(
desc='Create targetgroup permission %r' % permission1,
command=(
'permission_add', [permission1], dict(
targetgroup=u'editors',
ipapermright=u'write',
attrs=[u'sn'],
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
targetgroup=[u'editors'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermtarget=[DN(('cn', 'editors'), groups_dn)],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[api.env.basedn],
),
),
),
verify_permission_aci(
permission1, api.env.basedn,
'(target = "ldap:///%s")' % DN('cn=editors', groups_dn) +
'(targetattr = "sn")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Create %r' % permission3,
command=(
'permission_add', [permission3], dict(
type=u'user',
ipapermright=u'write',
attrs=[u'cn']
)
),
expected=dict(
value=permission3,
summary=u'Added permission "%s"' % permission3,
result=dict(
dn=permission3_dn,
cn=[permission3],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=(u'cn',),
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission3, users_dn,
'(targetattr = "cn")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission3 +
'allow (write) groupdn = "ldap:///%s";)' % permission3_dn,
),
dict(
desc='Retrieve %r with --all --rights' % permission3,
command=('permission_show', [permission3], {'all' : True, 'rights' : True}),
expected=dict(
value=permission3,
summary=None,
result=dict(
dn=permission3_dn,
cn=[permission3],
objectclass=objectclasses.permission,
type=[u'user'],
attrs=[u'cn'],
ipapermincludedattr=[u'cn'],
ipapermright=[u'write'],
attributelevelrights=permission3_attributelevelrights,
ipapermbindruletype=[u'permission'],
ipapermtargetfilter=[u'(objectclass=posixaccount)'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
dict(
desc='Modify %r with --all --rights' % permission3,
command=('permission_mod', [permission3], {
'all': True, 'rights': True,
'attrs': [u'cn', u'uid']}),
expected=dict(
value=permission3,
summary=u'Modified permission "%s"' % permission3,
result=dict(
dn=permission3_dn,
cn=[permission3],
objectclass=objectclasses.permission,
type=[u'user'],
attrs=[u'cn', u'uid'],
ipapermincludedattr=[u'cn', u'uid'],
ipapermright=[u'write'],
attributelevelrights=permission3_attributelevelrights,
ipapermbindruletype=[u'permission'],
ipapermtargetfilter=[u'(objectclass=posixaccount)'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission3, users_dn,
'(targetattr = "cn || uid")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission3 +
'allow (write) groupdn = "ldap:///%s";)' % permission3_dn,
),
dict(
desc='Try to modify %r with naked targetfilter' % permission1,
command=('permission_mod', [permission1],
{'ipapermtargetfilter': u"cn=admin"}),
expected=errors.ValidationError(
name='rawfilter',
error='must be enclosed in parentheses'),
),
dict(
desc='Try to modify %r with invalid targetfilter' % permission1,
command=('permission_mod', [permission1],
{'ipapermtargetfilter': u"(ceci n'est pas un filtre)"}),
expected=errors.ValidationError(
name='ipapermtargetfilter',
error='Bad search filter'),
),
dict(
desc='Try setting nonexisting location on %r' % permission1,
command=(
'permission_mod', [permission1], dict(
ipapermlocation=nonexistent_dn,
)
),
expected=errors.ValidationError(
name='ipapermlocation',
error='Entry %s does not exist' % nonexistent_dn)
),
dict(
desc='Search for nonexisting permission with ":" in the name',
command=(
'permission_find', ['doesnotexist:' + permission1], {}
),
expected=dict(
count=0,
truncated=False,
summary=u'0 permissions matched',
result=[],
),
),
]
class test_permission_rollback(Declarative):
"""Test rolling back changes after failed update"""
cleanup_commands = [
('permission_del', [permission1], {'force': True}),
]
_verifications = [
dict(
desc='Retrieve %r' % permission1,
command=('permission_show', [permission1], {}),
expected=dict(
value=permission1,
summary=None,
result={
'dn': permission1_dn,
'cn': [permission1],
'objectclass': objectclasses.permission,
'ipapermright': [u'write'],
'attrs': [u'sn'],
'ipapermbindruletype': [u'permission'],
'ipapermissiontype': [u'SYSTEM', u'V2'],
'ipapermlocation': [users_dn],
'ipapermtarget': [DN(('uid', 'admin'), users_dn)],
},
),
),
verify_permission_aci(
permission1, users_dn,
'(target = "ldap:///%s")' % DN(('uid', 'admin'), users_dn) +
'(targetattr = "sn")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
verify_permission_aci_missing(permission1, etc_dn)
]
tests = [
dict(
desc='Create %r' % permission1,
command=(
'permission_add', [permission1], dict(
ipapermlocation=users_dn,
ipapermtarget=DN('uid=admin', users_dn),
ipapermright=[u'write'],
attrs=[u'sn'],
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
ipapermtarget=[DN(('uid', 'admin'), users_dn)],
),
),
),
] + _verifications + [
dict(
desc='Move %r to non-existent DN' % permission1,
command=(
'permission_mod', [permission1], dict(
ipapermlocation=DN('foo=bar'),
)
),
expected=errors.ValidationError(
name='ipapermlocation',
error='Entry foo=bar does not exist'),
),
] + _verifications + [
dict(
desc='Move %r to another DN' % permission1,
command=('permission_mod', [permission1],
dict(ipapermlocation=etc_dn)
),
expected=errors.InvalidSyntax(
attr=r'ACL Invalid Target Error(-8): '
r'Target is beyond the scope of the ACL'
r'(SCOPE:%(sdn)s) '
r'(targetattr = \22sn\22)'
r'(target = \22ldap:///%(tdn)s\22)'
r'(version 3.0;acl \22permission:testperm\22;'
r'allow (write) groupdn = \22ldap:///%(pdn)s\22;)' % dict(
sdn=etc_dn,
tdn=DN('uid=admin', users_dn),
pdn=permission1_dn)),
),
] + _verifications + [
dict(
desc='Try adding an invalid attribute on %r with --all --rights' % permission1,
command=(
'permission_mod', [permission1], dict(
attrs=[u'cn', u'bogusattributexyz'],
rights=True,
all=True,
)
),
expected=errors.InvalidSyntax(
attr=r'targetattr "bogusattributexyz" does not exist '
r'in schema. Please add attributeTypes '
r'"bogusattributexyz" to schema if necessary. ACL Syntax '
r'Error(-5):(targetattr = \22bogusattributexyz || cn\22)'
r'(target = \22ldap:///%(tdn)s\22)'
r'(version 3.0;acl \22permission:%(name)s\22;'
r'allow (write) groupdn = \22ldap:///%(dn)s\22;)' % dict(
tdn=DN('uid=admin', users_dn),
name=permission1,
dn=permission1_dn),
),
),
] + _verifications
@pytest.mark.tier1
class test_permission_sync_attributes(Declarative):
"""Test the effects of setting permission attributes"""
cleanup_commands = [
('permission_del', [permission1], {'force': True}),
]
tests = [
dict(
desc='Create %r' % permission1,
command=(
'permission_add', [permission1], dict(
ipapermlocation=users_dn,
ipapermright=u'write',
attrs=u'sn',
ipapermtargetfilter=[
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn),
u'(objectclass=posixaccount)'],
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
memberof=[u'admins'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(&(memberOf=%s)' % DN('cn=admins', groups_dn) +
'(objectclass=posixaccount))")'
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Unset location on %r, verify type is gone' % permission1,
command=(
'permission_mod', [permission1], dict(
ipapermlocation=None,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
extratargetfilter=[
u'(objectclass=posixaccount)'],
memberof=[u'admins'],
ipapermlocation=[api.env.basedn],
),
),
),
verify_permission_aci(
permission1, api.env.basedn,
'(targetattr = "sn")' +
'(targetfilter = "(&(memberOf=%s)' % DN('cn=admins', groups_dn) +
'(objectclass=posixaccount))")'
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
verify_permission_aci_missing(permission1, users_dn),
dict(
desc='Reset location on %r' % permission1,
command=(
'permission_mod', [permission1], dict(
ipapermlocation=users_dn,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
memberof=[u'admins'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(&(memberOf=%s)' % DN('cn=admins', groups_dn) +
'(objectclass=posixaccount))")'
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
verify_permission_aci_missing(permission1, api.env.basedn),
dict(
desc='Unset objectclass filter on %r, verify type is gone' % permission1,
command=(
'permission_mod', [permission1], dict(
ipapermtargetfilter=u'(memberOf=%s)' % DN(('cn', 'admins'),
groups_dn),
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
memberof=[u'admins'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(memberOf=%s)")' % DN('cn=admins', groups_dn) +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Unset targetfilter on %r, verify memberof is gone' % permission1,
command=(
'permission_mod', [permission1], dict(
ipapermtargetfilter=None,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Set type of %r to group' % permission1,
command=(
'permission_mod', [permission1], dict(
type=u'group',
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'group'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[groups_dn],
),
),
),
verify_permission_aci(
permission1, groups_dn,
'(targetattr = "sn")' +
'(targetfilter = "%s")' % group_filter +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Set target on %r, verify targetgroup is set' % permission1,
command=(
'permission_mod', [permission1], dict(
ipapermtarget=DN('cn=editors', groups_dn),
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'group'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermtarget=[DN('cn=editors', groups_dn)],
ipapermlocation=[groups_dn],
targetgroup=[u'editors'],
),
),
),
verify_permission_aci(
permission1, groups_dn,
'(target = "ldap:///%s")' % DN(('cn', 'editors'), groups_dn) +
'(targetattr = "sn")' +
'(targetfilter = "%s")' % group_filter +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Set extra targetfilter on %r' % permission1,
command=(
'permission_mod', [permission1], dict(
extratargetfilter=u'(cn=blabla)',
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'group'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermtarget=[DN('cn=editors', groups_dn)],
ipapermlocation=[groups_dn],
targetgroup=[u'editors'],
extratargetfilter=[u'(cn=blabla)'],
),
),
),
verify_permission_aci(
permission1, groups_dn,
'(target = "ldap:///%s")' % DN(('cn', 'editors'), groups_dn) +
'(targetattr = "sn")' +
'(targetfilter = "(&(cn=blabla)%s)")' % group_filter +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Retrieve %r with --all' % permission1,
command=(
'permission_show', [permission1], dict(all=True)
),
expected=dict(
value=permission1,
summary=None,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'group'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermtarget=[DN('cn=editors', groups_dn)],
ipapermlocation=[groups_dn],
targetgroup=[u'editors'],
extratargetfilter=[u'(cn=blabla)'],
ipapermtargetfilter=[u'(cn=blabla)', group_filter],
),
),
),
dict(
desc='Set type of %r back to user' % permission1,
command=(
'permission_mod', [permission1], dict(
type=u'user', ipapermtarget=None,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
extratargetfilter=[u'(cn=blabla)'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(&(cn=blabla)(objectclass=posixaccount))")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
]
class test_permission_sync_nice(Declarative):
"""Test the effects of setting convenience options on permissions"""
cleanup_commands = [
('permission_del', [permission1], {'force': True}),
]
tests = [
dict(
desc='Create %r' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
ipapermright=u'write',
attrs=u'sn',
memberof=u'admins',
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
memberof=[u'admins'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(&(memberOf=%s)' % DN('cn=admins', groups_dn) +
'(objectclass=posixaccount))")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Unset type on %r, verify target & filter are gone' % permission1,
command=(
'permission_mod', [permission1], dict(
type=None,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
memberof=[u'admins'],
ipapermlocation=[api.env.basedn],
),
),
),
verify_permission_aci(
permission1, api.env.basedn,
'(targetattr = "sn")' +
'(targetfilter = "(memberOf=%s)")' % DN('cn=admins', groups_dn) +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Unset memberof on %r, verify targetfilter is gone' % permission1,
command=(
'permission_mod', [permission1], dict(
memberof=None,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[api.env.basedn],
),
),
),
verify_permission_aci(
permission1, api.env.basedn,
'(targetattr = "sn")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Set type of %r to group' % permission1,
command=(
'permission_mod', [permission1], dict(
type=u'group',
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'group'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[groups_dn],
),
),
),
verify_permission_aci(
permission1, groups_dn,
'(targetattr = "sn")' +
'(targetfilter = "%s")' % group_filter +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Set targetgroup on %r, verify target is set' % permission1,
command=(
'permission_mod', [permission1], dict(
targetgroup=u'editors',
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'group'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermtarget=[DN('cn=editors', groups_dn)],
ipapermlocation=[groups_dn],
targetgroup=[u'editors'],
),
),
),
verify_permission_aci(
permission1, groups_dn,
'(target = "ldap:///%s")' % DN(('cn', 'editors'), groups_dn) +
'(targetattr = "sn")' +
'(targetfilter = "%s")' % group_filter +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
]
@pytest.mark.tier1
class test_permission_targetfilter(Declarative):
"""Test the targetfilter options on permissions"""
cleanup_commands = [
('permission_del', [permission1], {'force': True}),
]
_initial_aci = (
'(targetattr = "sn")' +
'(targetfilter = "(&' +
'(cn=*)' +
'(memberOf=%s)' % DN('cn=admins', groups_dn) +
'(objectclass=posixaccount)' +
'(sn=*)' +
')")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn
)
tests = [
dict(
desc='Create %r' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
ipapermright=u'write',
attrs=u'sn',
memberof=u'admins',
extratargetfilter=[u'(cn=*)', u'(sn=*)'],
all=True,
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
memberof=[u'admins'],
extratargetfilter=[u'(cn=*)', u'(sn=*)'],
ipapermtargetfilter=[
u'(cn=*)', u'(sn=*)',
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn),
u'(objectclass=posixaccount)'],
),
),
),
verify_permission_aci(permission1, users_dn, _initial_aci),
dict(
desc='Retrieve %r' % permission1,
command=(
'permission_show', [permission1], dict()
),
expected=dict(
value=permission1,
summary=None,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
memberof=[u'admins'],
extratargetfilter=[u'(cn=*)', u'(sn=*)'],
),
),
),
dict(
desc='Retrieve %r with --all' % permission1,
command=(
'permission_show', [permission1], dict(all=True)
),
expected=dict(
value=permission1,
summary=None,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
memberof=[u'admins'],
extratargetfilter=[u'(cn=*)', u'(sn=*)'],
ipapermtargetfilter=[
u'(cn=*)', u'(sn=*)',
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn),
u'(objectclass=posixaccount)'],
),
),
),
dict(
desc='Retrieve %r with --raw' % permission1,
command=(
'permission_show', [permission1], dict(raw=True)
),
expected=dict(
value=permission1,
summary=None,
result=dict(
dn=permission1_dn,
cn=[permission1],
aci=[_initial_aci],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
ipapermtargetfilter=[
u'(cn=*)', u'(sn=*)',
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn),
u'(objectclass=posixaccount)'],
),
),
),
dict(
desc='Retrieve %r with --all and --raw' % permission1,
command=(
'permission_show', [permission1], dict(all=True, raw=True)
),
expected=dict(
value=permission1,
summary=None,
result=dict(
dn=permission1_dn,
cn=[permission1],
aci=[_initial_aci],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
ipapermtargetfilter=[
u'(cn=*)', u'(sn=*)',
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn),
u'(objectclass=posixaccount)'],
),
),
),
dict(
desc='Modify extratargetfilter of %r' % permission1,
command=(
'permission_mod', [permission1], dict(
extratargetfilter=[u'(cn=*)', u'(l=*)'],
all=True,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
memberof=[u'admins'],
extratargetfilter=[u'(cn=*)', u'(l=*)'],
ipapermtargetfilter=[
u'(cn=*)', u'(l=*)',
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn),
u'(objectclass=posixaccount)'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(&' +
'(cn=*)' +
'(l=*)' +
'(memberOf=%s)' % DN('cn=admins', groups_dn) +
'(objectclass=posixaccount)' +
')")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn
),
dict(
desc='Remove raw targetfilter of %r' % permission1,
command=(
'permission_mod', [permission1], dict(
ipapermtargetfilter=None,
all=True,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn
),
dict(
desc='Set extra targetfilter on %r to restore' % permission1,
command=(
'permission_mod', [permission1], dict(
extratargetfilter=[
u'(cn=*)',
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn),
u'(objectclass=posixaccount)'],
all=True,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
memberof=[u'admins'],
extratargetfilter=[u'(cn=*)'],
ipapermtargetfilter=[
u'(cn=*)',
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn),
u'(objectclass=posixaccount)'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(&' +
'(cn=*)' +
'(memberOf=%s)' % DN('cn=admins', groups_dn) +
'(objectclass=posixaccount)' +
')")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn
),
] + [
dict(
desc='Search for %r using %s %s' % (permission1, value_name, option_name),
command=(
'permission_find', [permission1],
{option_name: value, 'all': True}
),
expected=dict(
summary=u'1 permission matched' if should_find else u'0 permissions matched',
truncated=False,
count=1 if should_find else 0,
result=[dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
memberof=[u'admins'],
extratargetfilter=[u'(cn=*)'],
ipapermtargetfilter=[
u'(cn=*)',
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn),
u'(objectclass=posixaccount)'],
)] if should_find else [],
),
)
for option_name in (
'extratargetfilter',
'ipapermtargetfilter',
)
for value_name, value, should_find in (
('"extra"', u'(cn=*)', True),
('"non-extra"', u'(objectclass=posixaccount)', True),
('non-existing', u'(sn=insert a very improbable last name)', False),
)
] + [
dict(
desc='Set extra objectclass filter on %r' % permission1,
command=(
'permission_mod', [permission1], dict(
extratargetfilter=[u'(cn=*)', u'(objectclass=top)'],
all=True,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
memberof=[u'admins'],
extratargetfilter=[u'(cn=*)', u'(objectclass=top)'],
ipapermtargetfilter=[
u'(cn=*)',
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn),
u'(objectclass=posixaccount)',
u'(objectclass=top)'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "sn")' +
'(targetfilter = "(&' +
'(cn=*)' +
'(memberOf=%s)' % DN('cn=admins', groups_dn) +
'(objectclass=posixaccount)' +
'(objectclass=top)' +
')")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn
),
dict(
desc='Unset type on %r to verify extra objectclass filter stays' % permission1,
command=(
'permission_mod', [permission1], dict(
type=None,
all=True,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[api.env.basedn],
memberof=[u'admins'],
extratargetfilter=[u'(cn=*)', u'(objectclass=top)'],
ipapermtargetfilter=[
u'(cn=*)',
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn),
u'(objectclass=top)'],
),
),
),
verify_permission_aci(
permission1, api.env.basedn,
'(targetattr = "sn")' +
'(targetfilter = "(&' +
'(cn=*)' +
'(memberOf=%s)' % DN('cn=admins', groups_dn) +
'(objectclass=top)' +
')")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn
),
dict(
desc='Set wildcard memberof filter on %r' % permission1,
command=(
'permission_mod', [permission1], dict(
extratargetfilter=u'(memberof=*)',
all=True,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[api.env.basedn],
memberof=[u'admins'],
extratargetfilter=[u'(memberof=*)'],
ipapermtargetfilter=[
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn),
u'(memberof=*)'],
),
),
),
verify_permission_aci(
permission1, api.env.basedn,
'(targetattr = "sn")' +
'(targetfilter = "(&' +
'(memberOf=%s)' % DN('cn=admins', groups_dn) +
'(memberof=*)' +
')")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn
),
dict(
desc='Remove --memberof on %r to verify wildcard is still there' % permission1,
command=(
'permission_mod', [permission1], dict(
memberof=[],
all=True,
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
attrs=[u'sn'],
ipapermincludedattr=[u'sn'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[api.env.basedn],
extratargetfilter=[u'(memberof=*)'],
ipapermtargetfilter=[u'(memberof=*)'],
),
),
),
verify_permission_aci(
permission1, api.env.basedn,
'(targetattr = "sn")' +
'(targetfilter = "(memberof=*)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn
),
]
def _make_permission_flag_tests(flags, expected_message):
return [
dict(
desc='Create %r with flags %s' % (permission1, flags),
command=(
'permission_add_noaci', [permission1], dict(
ipapermissiontype=flags,
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.system_permission,
ipapermissiontype=flags,
),
),
),
dict(
desc='Try to modify %r' % permission1,
command=('permission_mod', [permission1], {'type': u'user'}),
expected=errors.ACIError(info=expected_message),
),
dict(
desc='Try to delete %r' % permission1,
command=('permission_del', [permission1], {}),
expected=errors.ACIError(info=expected_message),
),
dict(
desc='Add %r to %r' % (permission1, privilege1),
command=('privilege_add_permission', [privilege1],
{'permission': permission1}),
expected=dict(
completed=1,
failed=dict(
member=dict(
permission=[],
),
),
result={
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
'memberof_permission': [permission1],
}
),
),
dict(
desc='Delete %r with --force' % permission1,
command=('permission_del', [permission1], {'force': True}),
expected=dict(
result=dict(failed=[]),
value=[permission1],
summary=u'Deleted permission "%s"' % permission1,
),
),
]
@pytest.mark.tier1
class test_permission_flags(Declarative):
"""Test that permission flags are handled correctly"""
cleanup_commands = [
('permission_del', [permission1], {'force': True}),
('privilege_del', [privilege1], {}),
]
tests = [
dict(
desc='Create %r' % privilege1,
command=('privilege_add', [privilege1],
dict(description=u'privilege desc. 1')
),
expected=dict(
value=privilege1,
summary=u'Added privilege "%s"' % privilege1,
result=dict(
dn=privilege1_dn,
cn=[privilege1],
description=[u'privilege desc. 1'],
objectclass=objectclasses.privilege,
),
),
),
] + (
_make_permission_flag_tests(
[u'SYSTEM'],
'A SYSTEM permission may not be modified or removed') +
_make_permission_flag_tests(
[u'??'],
'Permission with unknown flag ?? may not be modified or removed') +
_make_permission_flag_tests(
[u'SYSTEM', u'??'],
'Permission with unknown flag ?? may not be modified or removed'))
def check_legacy_results(results):
"""Check that the expected number of legacy permissions are in $SUFFIX"""
legacy_permissions = [p for p in results
if not p.get('ipapermissiontype')]
print(legacy_permissions)
assert len(legacy_permissions) == 8, len(legacy_permissions)
return True
@pytest.mark.tier1
class test_permission_legacy(Declarative):
"""Tests for non-upgraded permissions"""
tests = [
dict(
desc='Check that some legacy permission is found in $SUFFIX',
command=('permission_find', [],
{'ipapermlocation': api.env.basedn}),
expected=dict(
count=lambda count: count,
truncated=False,
summary=lambda s: True,
result=check_legacy_results,
),
),
]
@pytest.mark.tier1
class test_permission_bindtype(Declarative):
cleanup_commands = [
('permission_del', [permission1], {'force': True}),
('permission_del', [permission1_renamed], {'force': True}),
('privilege_del', [privilege1], {}),
]
tests = [
dict(
desc='Create anonymous %r' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
ipapermright=u'write',
ipapermbindruletype=u'anonymous',
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'anonymous'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) userdn = "ldap:///anyone";)',
),
dict(
desc='Create %r' % privilege1,
command=('privilege_add', [privilege1],
dict(description=u'privilege desc. 1')
),
expected=dict(
value=privilege1,
summary=u'Added privilege "%s"' % privilege1,
result=dict(
dn=privilege1_dn,
cn=[privilege1],
description=[u'privilege desc. 1'],
objectclass=objectclasses.privilege,
),
),
),
dict(
desc='Try to add %r to %r' % (permission1, privilege1),
command=(
'privilege_add_permission', [privilege1], dict(
permission=[permission1],
)
),
expected=errors.ValidationError(
name='permission',
error=u'cannot add permission "%s" with bindtype "%s" to a '
'privilege' % (permission1, 'anonymous')),
),
dict(
desc='Change binddn of %r to all' % permission1,
command=(
'permission_mod', [permission1], dict(
type=u'user',
ipapermbindruletype=u'all',
)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'all'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) userdn = "ldap:///all";)',
),
dict(
desc='Try to add %r to %r' % (permission1, privilege1),
command=(
'privilege_add_permission', [privilege1], dict(
permission=[permission1],
)
),
expected=errors.ValidationError(
name='permission',
error=u'cannot add permission "%s" with bindtype "%s" to a '
'privilege' % (permission1, 'all')),
),
dict(
desc='Search for %r using --bindtype' % permission1,
command=('permission_find', [permission1],
{'ipapermbindruletype': u'all'}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[
dict(
dn=permission1_dn,
cn=[permission1],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'all'],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
],
),
),
dict(
desc='Search for %r using bad --bindtype' % permission1,
command=('permission_find', [permission1],
{'ipapermbindruletype': u'anonymous'}),
expected=dict(
count=0,
truncated=False,
summary=u'0 permissions matched',
result=[],
),
),
dict(
desc='Add zero permissions to %r' % (privilege1),
command=('privilege_add_permission', [privilege1], {}),
expected=dict(
completed=0,
failed=dict(member=dict(permission=[])),
result=dict(
dn=privilege1_dn,
cn=[privilege1],
description=[u'privilege desc. 1'],
),
),
),
dict(
desc='Rename %r to permission %r' % (permission1,
permission1_renamed),
command=(
'permission_mod', [permission1], dict(rename=permission1_renamed)
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_renamed_dn,
cn=[permission1_renamed],
type=[u'user'],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
ipapermbindruletype=[u'all'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1_renamed, users_dn,
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1_renamed +
'allow (write) userdn = "ldap:///all";)',
),
dict(
desc='Reset binddn of %r to permission' % permission1_renamed,
command=(
'permission_mod', [permission1_renamed], dict(
type=u'user',
ipapermbindruletype=u'permission',
)
),
expected=dict(
value=permission1_renamed,
summary=u'Modified permission "%s"' % permission1_renamed,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_renamed_dn,
cn=[permission1_renamed],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1_renamed, users_dn,
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1_renamed +
'allow (write) groupdn = "ldap:///%s";)' % permission1_renamed_dn,
),
dict(
desc='Rename %r back to %r' % (permission1_renamed, permission1),
command=(
'permission_mod', [permission1_renamed],
dict(rename=permission1)
),
expected=dict(
value=permission1_renamed,
summary=u'Modified permission "%s"' % permission1_renamed,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
type=[u'user'],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Add %r to %r' % (permission1, privilege1),
command=(
'privilege_add_permission', [privilege1], dict(
permission=[permission1],
)
),
expected=dict(
completed=1,
failed=dict(member=dict(permission=[])),
result=dict(
dn=privilege1_dn,
cn=[privilege1],
description=[u'privilege desc. 1'],
memberof_permission=[permission1],
)
),
),
dict(
desc='Try to change binddn of %r to anonymous' % permission1,
command=(
'permission_mod', [permission1], dict(
type=u'user',
ipapermbindruletype=u'anonymous',
)
),
expected=errors.ValidationError(
name='ipapermbindruletype',
error=u'cannot set bindtype for a permission that is '
'assigned to a privilege')
),
]
@pytest.mark.tier1
class test_managed_permissions(Declarative):
cleanup_commands = [
('permission_del', [permission1], {'force': True}),
('permission_del', [permission2], {'force': True}),
]
@pytest.fixture(autouse=True, scope="class")
def managed_perm_setup(self, declarative_setup):
if not have_ldap2:
pytest.skip('server plugin not available')
def add_managed_permission(self):
"""Add a managed permission and the corresponding ACI"""
ldap = ldap2(api)
ldap.connect()
api.Command.permission_add(
permission1, type=u'user', ipapermright=u'write', attrs=[u'cn'])
# TODO: This hack relies on the permission internals.
# Change as necessary.
# Add permission DN
entry = ldap.get_entry(permission1_dn)
entry['ipapermdefaultattr'] = ['l', 'o', 'cn']
ldap.update_entry(entry)
# Update the ACI via the API
api.Command.permission_mod(permission1, attrs=[u'l', u'o', u'cn'])
# Set the permission type to MANAGED
entry = ldap.get_entry(permission1_dn)
entry['ipapermissiontype'].append('MANAGED')
ldap.update_entry(entry)
tests = [
add_managed_permission,
dict(
desc='Show pre-created %r' % permission1,
command=('permission_show', [permission1], {'all': True}),
expected=dict(
value=permission1,
summary=None,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermlocation=[users_dn],
ipapermtargetfilter=[u'(objectclass=posixaccount)'],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o', u'cn'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "cn || l || o")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
] + [
# Verify that most permission attributes can't be changed
dict(
desc='Try to modify %s in %r' % (attr_name, permission1),
command=('permission_mod', [permission1],
{attr_name: value}),
expected=errors.ValidationError(
name=err_attr or attr_name,
error='not modifiable on managed permissions'),
)
for attr_name, err_attr, value in (
('ipapermlocation', None, users_dn),
('ipapermright', None, u'compare'),
('ipapermtarget', None, users_dn),
('ipapermtargetfilter', None, u'(ou=engineering)'),
('memberof', 'ipapermtargetfilter', u'admins'),
('targetgroup', 'ipapermtarget', u'admins'),
('type', 'ipapermlocation', u'group'),
('extratargetfilter', 'extratargetfilter', u'(cn=*)'),
)
] + [
dict(
desc='Try to rename %r' % permission1,
command=('permission_mod', [permission1],
{'rename': permission2}),
expected=errors.ValidationError(
name='rename',
error='cannot rename managed permissions'),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "cn || l || o")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Modify included and excluded attrs in %r' % permission1,
command=('permission_mod', [permission1],
{'ipapermincludedattr': [u'dc'],
'ipapermexcludedattr': [u'cn'],
'all': True}),
expected=dict(
value=permission1,
summary=u'Modified permission "testperm"',
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermlocation=[users_dn],
ipapermtargetfilter=[u'(objectclass=posixaccount)'],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o', u'dc'],
ipapermincludedattr=[u'dc'],
ipapermexcludedattr=[u'cn'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "dc || l || o")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Modify included attrs in %r' % permission1,
command=('permission_mod', [permission1],
{'ipapermincludedattr': [u'cn', u'sn'],
'all': True}),
expected=dict(
value=permission1,
summary=u'Modified permission "testperm"',
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermlocation=[users_dn],
ipapermtargetfilter=[u'(objectclass=posixaccount)'],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o', u'sn'],
ipapermincludedattr=[u'cn', u'sn'],
ipapermexcludedattr=[u'cn'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "l || o || sn")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Add ineffective included attr to %r' % permission1,
command=('permission_mod', [permission1],
{'ipapermincludedattr': [u'cn', u'sn', u'o'],
'all': True}),
expected=dict(
value=permission1,
summary=u'Modified permission "testperm"',
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermlocation=[users_dn],
ipapermtargetfilter=[u'(objectclass=posixaccount)'],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o', u'sn'],
ipapermincludedattr=[u'cn', u'sn', u'o'],
ipapermexcludedattr=[u'cn'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "l || o || sn")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Modify excluded attrs in %r' % permission1,
command=('permission_mod', [permission1],
{'ipapermexcludedattr': [u'cn', u'sn'],
'all': True}),
expected=dict(
value=permission1,
summary=u'Modified permission "testperm"',
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermlocation=[users_dn],
ipapermtargetfilter=[u'(objectclass=posixaccount)'],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o'],
ipapermincludedattr=[u'cn', u'sn', u'o'],
ipapermexcludedattr=[u'cn', u'sn'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "l || o")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Modify bind rule in %r' % permission1,
command=('permission_mod', [permission1],
{'ipapermbindruletype': u'all'}),
expected=dict(
value=permission1,
summary=u'Modified permission "testperm"',
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'all'],
ipapermlocation=[users_dn],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o'],
ipapermincludedattr=[u'cn', u'sn', u'o'],
ipapermexcludedattr=[u'cn', u'sn'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "l || o")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) userdn = "ldap:///all";)',
),
dict(
desc='Show %r with no options' % permission1,
command=('permission_show', [permission1], {}),
expected=dict(
value=permission1,
summary=None,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'all'],
ipapermlocation=[users_dn],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o'],
ipapermincludedattr=[u'cn', u'sn', u'o'],
ipapermexcludedattr=[u'cn', u'sn'],
),
),
),
dict(
desc='Show %r with --all' % permission1,
command=('permission_show', [permission1], {'all': True}),
expected=dict(
value=permission1,
summary=None,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'all'],
ipapermlocation=[users_dn],
ipapermtargetfilter=[u'(objectclass=posixaccount)'],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o'],
ipapermincludedattr=[u'cn', u'sn', u'o'],
ipapermexcludedattr=[u'cn', u'sn'],
),
),
),
dict(
desc='Show %r with --raw' % permission1,
command=('permission_show', [permission1], {'raw': True}),
expected=dict(
value=permission1,
summary=None,
result=dict(
dn=permission1_dn,
cn=[permission1],
aci=['(targetattr = "l || o")'
'(targetfilter = "(objectclass=posixaccount)")'
'(version 3.0;acl "permission:%(name)s";'
'allow (write) userdn = "ldap:///all";)' %
{'name': permission1}],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
ipapermright=[u'write'],
ipapermbindruletype=[u'all'],
ipapermlocation=[users_dn],
ipapermtargetfilter=[u'(objectclass=posixaccount)'],
ipapermdefaultattr=[u'l', u'o', u'cn'],
ipapermincludedattr=[u'cn', u'sn', u'o'],
ipapermexcludedattr=[u'cn', u'sn'],
),
),
),
dict(
desc='Modify attrs of %r to normalize' % permission1,
command=('permission_mod', [permission1],
{'attrs': [u'l', u'o']}),
expected=dict(
value=permission1,
summary=u'Modified permission "testperm"',
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'all'],
ipapermlocation=[users_dn],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o'],
ipapermexcludedattr=[u'cn'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "l || o")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) userdn = "ldap:///all";)',
),
dict(
desc='Modify attrs of %r to add sn' % permission1,
command=('permission_mod', [permission1],
{'attrs': [u'l', u'o', u'sn']}),
expected=dict(
value=permission1,
summary=u'Modified permission "testperm"',
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'all'],
ipapermlocation=[users_dn],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o', u'sn'],
ipapermincludedattr=[u'sn'],
ipapermexcludedattr=[u'cn'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "l || o || sn")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) userdn = "ldap:///all";)',
),
dict(
desc='Try to add invalid attribute to %r' % permission1,
command=('permission_mod', [permission1],
{'attrs': [u'calicense',]}),
expected=errors.InvalidSyntax(
attr=r'targetattr "calicense" does not exist in schema. '
r'Please add attributeTypes "calicense" to '
r'schema if necessary. '
r'ACL Syntax Error(-5):'
r'(targetattr = \22calicense\22)'
r'(targetfilter = \22(objectclass=posixaccount)\22)'
r'(version 3.0;acl \22permission:%(name)s\22;'
r'allow (write) userdn = \22ldap:///all\22;)' %
dict(name=permission1),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "l || o || sn")' \
'(targetfilter = "(objectclass=posixaccount)")' \
'(version 3.0;acl "permission:%s";' \
'allow (write) userdn = "ldap:///all";)' % permission1,
),
dict(
desc='Search for %r using all its --attrs' % permission1,
command=('permission_find', [permission1],
{'cn': permission1, 'attrs': [u'l', u'o', u'sn']}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'all'],
ipapermlocation=[users_dn],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o', u'sn'],
ipapermincludedattr=[u'sn'],
ipapermexcludedattr=[u'cn'],
)],
),
),
dict(
desc='Search for %r using some --attrs' % permission1,
command=('permission_find', [permission1],
{'cn': permission1, 'attrs': [u'l', u'sn']}),
expected=dict(
count=1,
truncated=False,
summary=u'1 permission matched',
result=[dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'all'],
ipapermlocation=[users_dn],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o', u'sn'],
ipapermincludedattr=[u'sn'],
ipapermexcludedattr=[u'cn'],
)],
),
),
dict(
desc='Search for %r using excluded --attrs' % permission1,
command=('permission_find', [permission1],
{'cn': permission1, 'attrs': [u'sn', u'cn']}),
expected=dict(
count=0,
truncated=False,
summary=u'0 permissions matched',
result=[],
),
),
dict(
desc='Modify attrs of %r to allow cn again' % permission1,
command=('permission_mod', [permission1],
{'attrs': [u'l', u'o', u'sn', u'cn']}),
expected=dict(
value=permission1,
summary=u'Modified permission "testperm"',
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermissiontype=[u'SYSTEM', u'V2', u'MANAGED'],
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'all'],
ipapermlocation=[users_dn],
ipapermdefaultattr=[u'l', u'o', u'cn'],
attrs=[u'l', u'o', u'sn', u'cn'],
ipapermincludedattr=[u'sn'],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetattr = "cn || l || o || sn")' +
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) userdn = "ldap:///all";)',
),
dict(
desc='Try to delete %r' % permission1,
command=('permission_del', [permission1], {}),
expected=errors.ACIError(
info='cannot delete managed permissions'),
),
dict(
desc='Delete %r with --force' % permission1,
command=('permission_del', [permission1], {'force': True}),
expected=dict(
result=dict(failed=[]),
value=[permission1],
summary=u'Deleted permission "%s"' % permission1,
),
),
]
@pytest.mark.tier1
class test_permission_filters(Declarative):
"""Test multi-valued filters, type, memberof"""
cleanup_commands = [
('permission_del', [permission1], {'force': True}),
]
tests = [
dict(
desc='Create %r with many filters' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
memberof=u'ipausers',
ipapermright=u'write',
ipapermtargetfilter=[
u'(objectclass=top)',
u'(memberof=%s)' % DN(('cn', 'admins'), groups_dn),
]
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
memberof=[u'admins', u'ipausers'],
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
extratargetfilter=[
u'(objectclass=top)',
],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetfilter = "(&'
'(memberOf=%s)' % DN(('cn', 'ipausers'), groups_dn) +
'(memberof=%s)' % DN(('cn', 'admins'), groups_dn) +
'(objectclass=posixaccount)(objectclass=top)' +
')")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Remove type from %r while setting other filters' % permission1,
command=(
'permission_mod', [permission1],
dict(
type=None,
memberof=u'ipausers',
ipapermtargetfilter=[
u'(objectclass=ipauser)',
u'(memberof=%s)' % DN(('cn', 'admins'), groups_dn),
],
),
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
memberof=[u'admins', u'ipausers'],
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[api.env.basedn],
extratargetfilter=[
u'(objectclass=ipauser)',
],
),
),
),
verify_permission_aci(
permission1, api.env.basedn,
'(targetfilter = "(&'
'(memberOf=%s)' % DN(('cn', 'ipausers'), groups_dn) +
'(memberof=%s)' % DN(('cn', 'admins'), groups_dn) +
'(objectclass=ipauser)' +
')")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Remove memberof from %r while adding a filter' % permission1,
command=(
'permission_mod', [permission1],
dict(
memberof=None,
addattr=u'ipapermtargetfilter=(cn=xyz)',
),
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[api.env.basedn],
extratargetfilter=[
u'(cn=xyz)',
u'(objectclass=ipauser)',
],
),
),
),
verify_permission_aci(
permission1, api.env.basedn,
'(targetfilter = "(&'
'(cn=xyz)' +
'(objectclass=ipauser)' +
')")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Set memberof, type and filter on %r at once' % permission1,
command=(
'permission_mod', [permission1],
dict(
type=u'user',
memberof=u'admins',
ipapermtargetfilter=u'(uid=abc)',
),
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
memberof=[u'admins'],
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
extratargetfilter=[
u'(uid=abc)',
],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetfilter = "(&'
u'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn) +
'(objectclass=posixaccount)' +
'(uid=abc)' +
')")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Remove memberof & type from %r at once' % permission1,
command=(
'permission_mod', [permission1],
dict(
type=None,
memberof=None,
),
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[api.env.basedn],
extratargetfilter=[
u'(uid=abc)',
],
),
),
),
verify_permission_aci(
permission1, api.env.basedn,
'(targetfilter = "(uid=abc)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Add multiple memberof to %r' % permission1,
command=(
'permission_mod', [permission1],
dict(
memberof=[u'admins', u'editors'],
),
),
expected=dict(
value=permission1,
summary=u'Modified permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
ipapermright=[u'write'],
memberof=[u'admins', u'editors'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[api.env.basedn],
extratargetfilter=[u'(uid=abc)'],
),
),
),
verify_permission_aci(
permission1, api.env.basedn,
'(targetfilter = "(&'
'(memberOf=%s)' % DN(('cn', 'admins'), groups_dn) +
'(memberOf=%s)' % DN(('cn', 'editors'), groups_dn) +
'(uid=abc)' +
')")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Delete %r' % permission1,
command=('permission_del', [permission1], {}),
expected=dict(
result=dict(failed=[]),
value=[permission1],
summary=u'Deleted permission "%s"' % permission1,
)
),
verify_permission_aci_missing(permission1, api.env.basedn),
dict(
desc='Create %r with empty filters [#4206]' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
ipapermright=u'write',
ipapermtargetfilter=u'',
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
verify_permission_aci(
permission1, users_dn,
'(targetfilter = "(objectclass=posixaccount)")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (write) groupdn = "ldap:///%s";)' % permission1_dn,
),
]
class test_permission_in_accounts(Declarative):
"""Test managing a permission in cn=accounts"""
tests = [
dict(
desc='Create %r in cn=accounts' % permission1,
command=(
'permission_add', [permission1], dict(
ipapermlocation=DN('cn=accounts', api.env.basedn),
ipapermright=u'add',
attrs=[u'cn'],
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
attrs=[u'cn'],
ipapermright=[u'add'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[DN('cn=accounts', api.env.basedn)],
),
),
),
verify_permission_aci(
permission1, DN('cn=accounts', api.env.basedn),
'(targetattr = "cn")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (add) groupdn = "ldap:///%s";)' % permission1_dn,
),
dict(
desc='Delete %r' % permission1,
command=(
'permission_del', [permission1], {}
),
expected=dict(
result=dict(failed=[]),
value=[permission1],
summary=u'Deleted permission "%s"' % permission1,
)
),
verify_permission_aci_missing(permission1, api.env.basedn),
]
class test_autoadd_operational_attrs(Declarative):
"""Test that read access to operational attributes is automatically added
"""
cleanup_commands = [
('permission_del', [permission1], {'force': True}),
]
tests = [
dict(
desc='Create %r' % permission1,
command=(
'permission_add', [permission1], dict(
ipapermlocation=DN('cn=accounts', api.env.basedn),
ipapermright=u'read',
attrs=[u'ObjectClass'],
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
attrs=[u'ObjectClass', u'entryusn', u'createtimestamp',
u'modifytimestamp'],
ipapermright=[u'read'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[DN('cn=accounts', api.env.basedn)],
),
),
),
verify_permission_aci(
permission1, DN('cn=accounts', api.env.basedn),
'(targetattr = "ObjectClass || createtimestamp || entryusn || ' +
'modifytimestamp")' +
'(version 3.0;acl "permission:%s";' % permission1 +
'allow (read) groupdn = "ldap:///%s";)' % permission1_dn,
),
]
class test_self_bindrule(Declarative):
"""Test creation of permission with bindrule self
"""
cleanup_commands = [
('permission_del', [permission1], {'force': True}),
]
tests = [
dict(
desc='Create %r' % permission1,
command=(
'permission_add', [permission1], dict(
ipapermlocation=DN('cn=accounts', api.env.basedn),
ipapermright=u'read',
ipapermbindruletype='self',
attrs=[u'objectclass'],
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
attrs=[u'objectclass', u'entryusn', u'createtimestamp',
u'modifytimestamp'],
ipapermright=[u'read'],
ipapermbindruletype=[u'self'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[DN('cn=accounts', api.env.basedn)],
),
),
),
verify_permission_aci(
permission1, DN('cn=accounts', api.env.basedn),
'(targetattr = "createtimestamp || entryusn || modifytimestamp '
+ '|| objectclass")'
+ '(version 3.0;acl "permission:%s";' % permission1
+ 'allow (read) userdn = "ldap:///self";)',
),
]
| 171,251
|
Python
|
.py
| 4,211
| 23.937782
| 95
| 0.440566
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,465
|
test_passkey_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_passkey_plugin.py
|
#
# Copyright (C) 2022 FreeIPA Contributors see COPYING for license
#
import pytest
from ipalib import errors
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, raises_exact
from ipatests.test_xmlrpc.tracker.passkey_plugin import PasskeyconfigTracker
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
from ipatests.test_xmlrpc.tracker.stageuser_plugin import StageUserTracker
@pytest.fixture(scope='class')
def passkey_config(request, xmlrpc_setup):
tracker = PasskeyconfigTracker()
return tracker.make_fixture(request)
class TestPasskeyconfig(XMLRPC_test):
@pytest.mark.parametrize("userverification", [False, True])
def test_config_mod(self, passkey_config, userverification):
"""
Test the passkeyconfig-mod CLI with possible values for
--require-user-verification parameter.
"""
passkey_config.update(
{'iparequireuserverification': userverification},
{'iparequireuserverification': [userverification]}
)
def test_config_mod_invalid_requireverif(self, passkey_config):
"""
Test the passkeyconfig-mod CLI with invalid values for
--require-user-verification parameter.
"""
cmd = passkey_config.make_update_command(
updates={'iparequireuserverification': 'Invalid'}
)
with pytest.raises(errors.ConversionError):
cmd()
def test_config_show(self, passkey_config):
"""
Test the passkeyconfig-show command.
"""
passkey_config.retrieve()
PASSKEY_USER = 'passkeyuser'
PASSKEY_KEY = ("passkey:"
"E8Zay6UJm6PG/GcQnej2WMyUrWqijejBCqPWFX6THPrx"
"ab01Z59bUgutipn5MIk8/zMU6RBlp7jSbkNJsZtomw==,"
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEgryfr3YR"
"M9OVdWHEDrbvcSyT5D0b/8Ks+fMp8MM0BXV/FOo436ZP"
"jUqSU+2LOXVGdKkJU1XBiwl+n/X+vGD1vw==")
PASSKEY_DISCOVERABLEKEY = (
"passkey:"
"pP2z07ygq36HkNabd79ki9H6rfYEIVdluSHjY1YykUbVECXJ3ZDZ3n1EZ9G8HhMv,"
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEpP2z07ygq36HkNabd1H9Knqqghjv"
"vhlW0+FcNzOoXP+49tC/Ee2TbjC3x2dIzJEBFi7iDPSc+OCM+WmD1AfPLQ==,"
"P6GjSqAo+RoQRJhGFA3lKcvtpKTGETjCdtVIyLX0KcY=")
@pytest.fixture
def passkeyuser(request):
user = UserTracker(PASSKEY_USER, 'passkey', 'user')
return user.make_fixture(request)
class TestAddRemovePasskey(XMLRPC_test):
@pytest.mark.parametrize("key", [PASSKEY_KEY, PASSKEY_DISCOVERABLEKEY])
def test_add_passkey(self, passkeyuser,key):
passkeyuser.ensure_exists()
passkeyuser.add_passkey(ipapasskey=key)
passkeyuser.ensure_missing()
@pytest.mark.parametrize("key", [PASSKEY_KEY, PASSKEY_DISCOVERABLEKEY])
def test_remove_passkey(self, passkeyuser, key):
passkeyuser.ensure_exists()
passkeyuser.add_passkey(ipapasskey=key)
passkeyuser.remove_passkey(ipapasskey=key)
@pytest.mark.parametrize("key", ['wrongval', 'passkey:123', 'passkey,123'])
def test_add_passkey_invalid(self, passkeyuser, key):
passkeyuser.ensure_exists()
cmd = passkeyuser.make_command('user_add_passkey',
passkeyuser.name)
with raises_exact(errors.ValidationError(
name='passkey',
error='"{}" is not a valid passkey mapping'.format(key))):
cmd(key)
def test_add_passkey_invalidid(self, passkeyuser):
passkeyuser.ensure_exists()
key = ("passkey:123,"
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEgryfr3YRM9OVdWHEDrbvc"
"SyT5D0b/8Ks+fMp8MM0BXV/FOo436ZPjUqSU+2LOXVGdKkJU1XBiwl+n/X"
"+vGD1vw==")
msg = '"{}" is not a valid passkey mapping, invalid id'
cmd = passkeyuser.make_command('user_add_passkey',
passkeyuser.name)
with raises_exact(errors.ValidationError(
name='passkey',
error=msg.format(key))):
cmd(key)
def test_add_passkey_invalidpem(self, passkeyuser):
passkeyuser.ensure_exists()
key = ("passkey:"
"E8Zay6UJm6PG/GcQnej2WMyUrWqijejBCqPWFX6THPrxab01Z59bUguti"
"pn5MIk8/zMU6RBlp7jSbkNJsZtomw==,"
"wrongpem")
msg = '"{}" is not a valid passkey mapping, invalid key'
cmd = passkeyuser.make_command('user_add_passkey',
passkeyuser.name)
with raises_exact(errors.ValidationError(
name='passkey',
error=msg.format(key))):
cmd(key)
def test_add_passkey_invaliduserid(self, passkeyuser):
passkeyuser.ensure_exists()
key = ("passkey:"
"E8Zay6UJm6PG/GcQnej2WMyUrWqijejBCqPWFX6THPrxab01Z59bUguti"
"pn5MIk8/zMU6RBlp7jSbkNJsZtomw==,"
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEgryfr3YRM9OVdWHEDrbvc"
"SyT5D0b/8Ks+fMp8MM0BXV/FOo436ZPjUqSU+2LOXVGdKkJU1XBiwl+n/X"
"+vGD1vw==,"
"wrongid")
msg = '"{}" is not a valid passkey mapping, invalid userid'
cmd = passkeyuser.make_command('user_add_passkey',
passkeyuser.name)
with raises_exact(errors.ValidationError(
name='passkey',
error=msg.format(key))):
cmd(key)
STAGEPASSKEY_USER = 'stagepasskeyuser'
@pytest.fixture
def stagepasskeyuser(request):
user = StageUserTracker(STAGEPASSKEY_USER, 'stagepasskey', 'user')
return user.make_fixture(request)
class TestStageAddRemovePassKey(XMLRPC_test):
def test_add_passkey(self, stagepasskeyuser):
stagepasskeyuser.ensure_exists()
stagepasskeyuser.add_passkey(ipapasskey=PASSKEY_KEY)
stagepasskeyuser.ensure_missing()
def test_remove_passkey(self, stagepasskeyuser):
stagepasskeyuser.ensure_exists()
stagepasskeyuser.add_passkey(ipapasskey=PASSKEY_KEY)
stagepasskeyuser.remove_passkey(ipapasskey=PASSKEY_KEY)
@pytest.mark.parametrize("key", ['wrongval', 'passkey:123', 'passkey,123'])
def test_add_passkey_invalid(self, stagepasskeyuser, key):
stagepasskeyuser.ensure_exists()
cmd = stagepasskeyuser.make_command('user_add_passkey',
stagepasskeyuser.name)
with raises_exact(errors.ValidationError(
name='passkey',
error='"{}" is not a valid passkey mapping'.format(key))):
cmd(key)
| 6,557
|
Python
|
.py
| 141
| 36.546099
| 79
| 0.664371
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,466
|
test_baseldap_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_baseldap_plugin.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/>.
"""
Test the `ipalib.plugins.baseldap` module.
"""
import ldap
from ipapython.dn import DN
from ipapython import ipaldap
from ipalib import errors
from ipalib.frontend import Command
from ipaserver.plugins import baseldap
from ipatests.util import assert_deepequal
import pytest
@pytest.mark.tier0
def test_exc_wrapper():
"""Test the BaseLDAPCommand._exc_wrapper helper method"""
handled_exceptions = []
class test_callback(baseldap.BaseLDAPCommand):
"""Fake IPA method"""
def test_fail(self):
self._exc_wrapper([], {}, self.fail)(1, 2, a=1, b=2)
def fail(self, *args, **kwargs):
assert args == (1, 2)
assert kwargs == dict(a=1, b=2)
raise errors.ExecutionError('failure')
api = 'the api instance'
instance = test_callback(api)
# Test with one callback first
@test_callback.register_exc_callback
def handle_exception(
self, keys, options, e, call_func, *args, **kwargs):
assert args == (1, 2)
assert kwargs == dict(a=1, b=2)
handled_exceptions.append(type(e))
instance.test_fail()
assert handled_exceptions == [errors.ExecutionError]
# Test with another callback added
handled_exceptions = []
def dont_handle(self, keys, options, e, call_func, *args, **kwargs):
assert args == (1, 2)
assert kwargs == dict(a=1, b=2)
handled_exceptions.append(None)
raise e
test_callback.register_exc_callback(dont_handle, first=True)
instance.test_fail()
assert handled_exceptions == [None, errors.ExecutionError]
@pytest.mark.tier0
def test_callback_registration():
class callbacktest_base(Command):
callback_types = Command.callback_types + ('test',)
def test_callback(self, param):
messages.append(('Base test_callback', param))
def registered_callback(self, param):
messages.append(('Base registered callback', param))
callbacktest_base.register_callback('test', registered_callback)
class SomeClass:
def registered_callback(self, command, param):
messages.append(('Registered callback from another class', param))
callbacktest_base.register_callback('test', SomeClass().registered_callback)
class callbacktest_subclass(callbacktest_base):
pass
def subclass_callback(self, param):
messages.append(('Subclass registered callback', param))
callbacktest_subclass.register_callback('test', subclass_callback)
api = 'the api instance'
messages = []
instance = callbacktest_base(api)
for callback in instance.get_callbacks('test'):
callback(instance, 42)
assert messages == [
('Base test_callback', 42),
('Base registered callback', 42),
('Registered callback from another class', 42)]
messages = []
instance = callbacktest_subclass(api)
for callback in instance.get_callbacks('test'):
callback(instance, 42)
assert messages == [
('Base test_callback', 42),
('Subclass registered callback', 42)]
@pytest.mark.tier0
def test_exc_callback_registration():
messages = []
class callbacktest_base(baseldap.BaseLDAPCommand):
"""A method superclass with an exception callback"""
def exc_callback(self, keys, options, exc, call_func, *args, **kwargs):
"""Let the world know we saw the error, but don't handle it"""
messages.append('Base exc_callback')
raise exc
def test_fail(self):
"""Raise a handled exception"""
try:
self._exc_wrapper([], {}, self.fail)(1, 2, a=1, b=2)
except Exception:
pass
def fail(self, *args, **kwargs):
"""Raise an error"""
raise errors.ExecutionError('failure')
api = 'the api instance'
base_instance = callbacktest_base(api)
class callbacktest_subclass(callbacktest_base):
pass
@callbacktest_subclass.register_exc_callback
def exc_callback(
self, keys, options, exc, call_func, *args, **kwargs):
"""Subclass's private exception callback"""
messages.append('Subclass registered callback')
raise exc
subclass_instance = callbacktest_subclass(api)
# Make sure exception in base class is only handled by the base class
base_instance.test_fail()
assert messages == ['Base exc_callback']
@callbacktest_base.register_exc_callback
def exc_callback_2(
self, keys, options, exc, call_func, *args, **kwargs):
"""Callback on super class; doesn't affect the subclass"""
messages.append('Superclass registered callback')
raise exc
# Make sure exception in subclass is only handled by both
messages = []
subclass_instance.test_fail()
assert messages == ['Base exc_callback', 'Subclass registered callback']
@pytest.mark.tier0
def test_entry_to_dict():
class FakeAttributeType:
def __init__(self, name, syntax):
self.names = (name,)
self.syntax = syntax
class FakeSchema:
def get_obj(self, type, name):
if type != ldap.schema.AttributeType:
return None
if name == 'binaryattr':
return FakeAttributeType(name, '1.3.6.1.4.1.1466.115.121.1.40')
elif name == 'textattr':
return FakeAttributeType(name, '1.3.6.1.4.1.1466.115.121.1.15')
elif name == 'dnattr':
return FakeAttributeType(name, '1.3.6.1.4.1.1466.115.121.1.12')
else:
return None
class FakeLDAPClient(ipaldap.LDAPClient):
def __init__(self):
super(FakeLDAPClient, self).__init__('ldap://test',
force_schema_updates=False)
self._has_schema = True
self._schema = FakeSchema()
conn = FakeLDAPClient()
rights = {'nothing': 'is'}
entry = ipaldap.LDAPEntry(
conn,
DN('cn=test'),
textattr=[u'text'],
dnattr=[DN('cn=test')],
binaryattr=[b'\xffabcd'],
attributelevelrights=rights)
the_dict = {
u'dn': u'cn=test',
u'textattr': [u'text'],
u'dnattr': [u'cn=test'],
u'binaryattr': [b'\xffabcd'],
u'attributelevelrights': rights}
assert_deepequal(
baseldap.entry_to_dict(entry, all=True, raw=True),
the_dict)
| 7,290
|
Python
|
.py
| 180
| 32.933333
| 80
| 0.644444
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,467
|
test_hostgroup_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_hostgroup_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Pavel Zuna <pzuna@redhat.com>
#
# Copyright (C) 2008, 2009 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 `ipalib.plugins.hostgroup` module.
"""
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, raises_exact
from ipatests.test_xmlrpc.tracker.hostgroup_plugin import HostGroupTracker
from ipatests.test_xmlrpc.tracker.host_plugin import HostTracker
from ipalib import errors
import pytest
renamedhostgroup1 = u'renamedhostgroup1'
@pytest.fixture(scope='class')
def hostgroup(request, xmlrpc_setup):
tracker = HostGroupTracker(name=u'hostgroup')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def hostgroup_invalid(request, xmlrpc_setup):
tracker = HostGroupTracker(name=u'@invalid')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def hostgroup_single(request, xmlrpc_setup):
tracker = HostGroupTracker(name=u'a')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def host(request, xmlrpc_setup):
tracker = HostTracker(name=u'host')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def ipaservers(request, xmlrpc_setup):
# Track the ipaservers hostgroup
# Since the hostgroup is protected, we cannot use 'make_fixture()' because
# it will try to delete the object when scope is destroyed and that will
# fail. Thus, we only create it here.
tracker = HostGroupTracker(
name=u'ipaservers', description=u'IPA server hosts'
)
tracker.exists = True
tracker.track_create()
return tracker
class TestNonexistentHostGroup(XMLRPC_test):
def test_retrieve_nonexistent(self, hostgroup):
""" Try to retrieve non-existent hostgroup """
hostgroup.ensure_missing()
command = hostgroup.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: host group not found' % hostgroup.cn)):
command()
def test_update_nonexistent(self, hostgroup):
""" Try to update non-existent hostgroup """
hostgroup.ensure_missing()
command = hostgroup.make_update_command(
dict(description=u'Updated hostgroup 1')
)
with raises_exact(errors.NotFound(
reason=u'%s: host group not found' % hostgroup.cn)):
command()
def test_delete_nonexistent(self, hostgroup):
""" Try to delete non-existent hostgroup """
hostgroup.ensure_missing()
command = hostgroup.make_delete_command()
with raises_exact(errors.NotFound(
reason=u'%s: host group not found' % hostgroup.cn)):
command()
class TestHostGroup(XMLRPC_test):
def test_invalid_name(self, hostgroup_invalid):
""" Test an invalid hostgroup name """
hostgroup_invalid.ensure_missing()
command = hostgroup_invalid.make_create_command()
with raises_exact(errors.ValidationError(
name='hostgroup_name',
error=u'may only include letters, numbers, _, -, and .')):
command()
def test_create_hostgroup(self, hostgroup):
""" Create hostgroup """
hostgroup.create()
def test_create_duplicate_hostgroup(self, hostgroup):
""" Try to create duplicate hostgroup """
hostgroup.ensure_exists()
command = hostgroup.make_create_command()
with raises_exact(errors.DuplicateEntry(
message=u'host group with name "%s" already exists' %
hostgroup.cn)):
command()
def test_rename_hostgroup(self, hostgroup):
""" Rename a hostgroup and than rename it back """
origname = hostgroup.cn
command = hostgroup.make_command(
'hostgroup_mod', *[hostgroup.cn],
**dict(setattr=u'cn=%s' % renamedhostgroup1))
result = command()
hostgroup.attrs.update(cn=[renamedhostgroup1])
hostgroup.check_update(result)
hostgroup.cn = renamedhostgroup1
command = hostgroup.make_command(
'hostgroup_mod', *[hostgroup.cn],
**dict(setattr=u'cn=%s' % origname))
result = command()
hostgroup.attrs.update(cn=[origname])
hostgroup.check_update(result)
hostgroup.cn = origname
def test_rename_ipaservers(self, ipaservers):
""" Try to rename the protected ipaservers group """
command = ipaservers.make_command('hostgroup_mod', *[ipaservers.cn],
**dict(rename=renamedhostgroup1))
reason = u'privileged hostgroup'
with raises_exact(errors.ProtectedEntryError(label=u'hostgroup',
key=ipaservers.cn, reason=reason)):
command()
def test_create_host_add_to_hostgroup(self, hostgroup, host):
""" Check that host can be added to hostgroup """
host.create()
hostgroup.add_member(dict(host=host.fqdn))
hostgroup.retrieve()
def test_search_for_hostgroup(self, hostgroup):
""" Search for hostgroup """
hostgroup.ensure_exists()
hostgroup.find()
def test_search_for_hostgroup_with_all(self, hostgroup):
""" Search for hostgroup """
hostgroup.ensure_exists()
hostgroup.find(all=True)
def test_update_hostgroup(self, hostgroup):
""" Update description of hostgroup and verify """
hostgroup.ensure_exists()
hostgroup.update(dict(description=u'Updated hostgroup 1'))
hostgroup.retrieve()
def test_remove_host_from_hostgroup(self, hostgroup, host):
""" Remove host from hostgroup """
hostgroup.ensure_exists()
hostgroup.remove_member(dict(host=host.fqdn))
def test_delete_hostgroup(self, hostgroup):
""" Delete hostgroup """
hostgroup.ensure_exists()
hostgroup.delete()
def test_one_letter_hostgroup(self, hostgroup_single):
""" Create hostgroup with name containing only one letter """
hostgroup_single.create()
hostgroup_single.delete()
| 6,768
|
Python
|
.py
| 155
| 36.367742
| 78
| 0.676949
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,468
|
test_user_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_user_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Pavel Zuna <pzuna@redhat.com>
# Jason Gerard DeRose <jderose@redhat.com>
# Filip Skola <fskola@redhat.com>
#
# Copyright (C) 2008, 2009 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/plugins/user.py` module.
"""
import pytest
import base64
import datetime
import ldap
import re
from ipalib import api, errors
from ipalib.constants import ERRMSG_GROUPUSER_NAME
from ipaplatform.constants import constants as platformconstants
from ipapython import ipautil
from ipatests.test_xmlrpc import objectclasses
from ipatests.util import (
assert_deepequal, assert_equal, assert_not_equal, raises)
from ipatests.test_xmlrpc.xmlrpc_test import (
XMLRPC_test, fuzzy_digits, fuzzy_uuid, fuzzy_password,
fuzzy_user_or_group_sid, fuzzy_set_optional_oc,
Fuzzy, fuzzy_dergeneralizedtime, raises_exact)
from ipapython.dn import DN
from ipapython.ipaldap import ldap_initialize
from ipatests.test_xmlrpc.tracker.base import Tracker
from ipatests.test_xmlrpc.tracker.group_plugin import GroupTracker
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
admin1 = u'admin'
admin_group = u'admins'
invaliduser1 = u'+tuser1'
invaliduser2 = u''.join(['a' for n in range(256)])
invaliduser3 = u'1234'
sshpubkey = (u'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDGAX3xAeLeaJggwTqMjxNwa6X'
'HBUAikXPGMzEpVrlLDCZtv00djsFTBi38PkgxBJVkgRWMrcBsr/35lq7P6w8KGI'
'wA8GI48Z0qBS2NBMJ2u9WQ2hjLN6GdMlo77O0uJY3251p12pCVIS/bHRSq8kHO2'
'No8g7KA9fGGcagPfQH+ee3t7HUkpbQkFTmbPPN++r3V8oVUk5LxbryB3UIIVzNm'
'cSIn3JrXynlvui4MixvrtX6zx+O/bBo68o8/eZD26QrahVbA09fivrn/4h3TM01'
'9Eu/c2jOdckfU3cHUV/3Tno5d6JicibyaoDDK7S/yjdn5jhaz8MSEayQvFkZkiF'
'0L public key test')
sshpubkeyfp = (u'SHA256:cStA9o5TRSARbeketEOooMUMSWRSsArIAXloBZ4vNsE '
'public key test (ssh-rsa)')
validlanguages = {
u'en-US;q=0.987 , en, abcdfgh-abcdefgh;q=1 , a;q=1.000',
u'*'
}
invalidlanguages = {
u'abcdfghji-abcdfghji', u'en-us;q=0,123',
u'en-us;q=0.1234', u'en-us;q=1.1', u'en-us;q=1.0000'
}
now = datetime.datetime.now().replace(microsecond=0)
principal_expiration_date = now + datetime.timedelta(days=365)
principal_expiration_string = principal_expiration_date.strftime(
"%Y-%m-%dT%H:%M:%SZ")
invalid_expiration_string = "2020-12-07 19:54:13"
expired_expiration_string = "1991-12-07T19:54:13Z"
# Date in ISO format (2013-12-10T12:00:00)
isodate_re = re.compile(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$')
nonexistentidp = 'IdPDoesNotExist'
@pytest.fixture(scope='class')
def user_min(request, xmlrpc_setup):
""" User tracker fixture for testing user with uid no specified """
tracker = UserTracker(givenname=u'Testmin', sn=u'Usermin')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user(request, xmlrpc_setup):
tracker = UserTracker(name=u'user1', givenname=u'Test', sn=u'User1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user2(request, xmlrpc_setup):
tracker = UserTracker(name=u'user2', givenname=u'Test2', sn=u'User2')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def renameduser(request, xmlrpc_setup):
tracker = UserTracker(name=u'ruser1', givenname=u'Ruser', sn=u'Ruser1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def admin2(request, xmlrpc_setup):
tracker = UserTracker(name=u'admin2', givenname=u'Second', sn=u'Admin')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user_npg(request, group):
""" User tracker fixture for testing users with no private group """
tracker = UserTracker(name=u'npguser1', givenname=u'Npguser',
sn=u'Npguser1', noprivate=True)
tracker.track_create()
del tracker.attrs['mepmanagedentry']
tracker.attrs.update(
description=[], memberof_group=[group.cn],
objectclass=fuzzy_set_optional_oc(
objectclasses.user_base, 'ipantuserattrs'
),
)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user_npg2(request, group):
""" User tracker fixture for testing users with no private group """
tracker = UserTracker(name=u'npguser2', givenname=u'Npguser',
sn=u'Npguser2', noprivate=True, gidnumber=1000)
tracker.track_create()
del tracker.attrs['mepmanagedentry']
tracker.attrs.update(
gidnumber=[u'1000'], description=[], memberof_group=[group.cn],
objectclass=fuzzy_set_optional_oc(
objectclasses.user_base, 'ipantuserattrs'
),
)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user_radius(request, xmlrpc_setup):
""" User tracker fixture for testing users with radius user name """
tracker = UserTracker(name=u'radiususer', givenname=u'radiususer',
sn=u'radiususer1',
ipatokenradiususername=u'radiususer')
tracker.track_create()
tracker.attrs.update(objectclass=fuzzy_set_optional_oc(
objectclasses.user + [u'ipatokenradiusproxyuser'],
'ipantuserattrs'),
)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user_idp(request, xmlrpc_setup):
""" User tracker fixture for testing users with idp user id """
tracker = UserTracker(name='idpuser', givenname='idp',
sn='user', ipaidpsub='myidpuserid')
tracker.track_create()
tracker.attrs.update(ipaidpsub=['myidpuserid'])
tracker.attrs.update(objectclass=fuzzy_set_optional_oc(
objectclasses.user + [u'ipaidpuser'],
'ipantuserattrs'),
)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def group(request, xmlrpc_setup):
tracker = GroupTracker(name=u'group1')
return tracker.make_fixture(request)
@pytest.mark.tier1
class TestNonexistentUser(XMLRPC_test):
def test_retrieve_nonexistent(self, user):
""" Try to retrieve a non-existent user """
user.ensure_missing()
command = user.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: user not found' % user.uid)):
command()
def test_update_nonexistent(self, user):
""" Try to update a non-existent user """
user.ensure_missing()
command = user.make_update_command(
updates=dict(givenname=u'changed'))
with raises_exact(errors.NotFound(
reason=u'%s: user not found' % user.uid)):
command()
def test_delete_nonexistent(self, user):
""" Try to delete a non-existent user """
user.ensure_missing()
command = user.make_delete_command()
with raises_exact(errors.NotFound(
reason=u'%s: user not found' % user.uid)):
command()
def test_rename_nonexistent(self, user, renameduser):
""" Try to rename a non-existent user """
user.ensure_missing()
command = user.make_update_command(
updates=dict(setattr=u'uid=%s' % renameduser.uid))
with raises_exact(errors.NotFound(
reason=u'%s: user not found' % user.uid)):
command()
@pytest.mark.tier1
class TestUser(XMLRPC_test):
def test_retrieve(self, user):
""" Create user and try to retrieve it """
user.ensure_exists()
user.retrieve()
def test_delete(self, user):
""" Delete user """
user.delete()
def test_query_status(self, user):
""" Query user_status on a user """
user.ensure_exists()
result = user.run_command('user_status', user.uid)
assert_deepequal(dict(
count=1,
result=[dict(
dn=user.dn,
krblastfailedauth=[u'N/A'],
krblastsuccessfulauth=[u'N/A'],
krbloginfailedcount=u'0',
passwordgraceusertime=u'0',
now=isodate_re.match,
server=api.env.host,
), ],
summary=u'Account disabled: False',
truncated=False,
), result)
user.delete()
def test_remove_userclass(self, user):
""" Remove attribute userclass from user entry """
user.ensure_exists()
result = user.run_command(
'user_mod', user.uid, **dict(userclass=u'')
)
user.check_update(result)
user.delete()
def test_find_cert(self, user):
""" Add a usercertificate and perform a user-find --certificate """
user_cert = (
u"MIICszCCAZugAwIBAgICM24wDQYJKoZIhvcNAQELBQAwIzEUMBIGA1UEChML\r\n"
"RVhBTVBMRS5PUkcxCzAJBgNVBAMTAkNBMB4XDTE3MDExOTEwMjUyOVoXDTE3M\r\n"
"DQxOTEwMjUyOVowFjEUMBIGA1UEAxMLc3RhZ2V1c2VyLTEwggEiMA0GCSqGSI\r\n"
"b3DQEBAQUAA4IBDwAwggEKAoIBAQCq03FRQQBvq4HwYMKP8USLZuOkKzuIs2V\r\n"
"Pt8k/+nO1dADrzMogKDiUDjCwYoG2UM/sj6P+PJUUCNDLh5eRRI+aR5VE5y2a\r\n"
"K95iCsj1ByDWrugAUXgr8GUUr+UbaGc0XxHCMnQBkYhzbXY3u91KYRRh5l3lx\r\n"
"RSICcVeJFJ/tiMS14Vsor1DWykHGz1wm0Zjwg1XDV3oea+uwrSz5Pa6RNPlgC\r\n"
"+GGW6B7+8qC2XdSSEwvY7y1SAGgqyOxN/FLwvqqMDNU0uX7fww587uZ57IfYz\r\n"
"b8Xn5DAprRFNk40FDc46rMlkPBT+Tij1I0jedD8h2e6WEa7JRU6SGToYDbRm4\r\n"
"RL9xAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAHqm1jXzYer9oSjYs9qh1jWpM\r\n"
"vTcN+0/z1uuX++Wezh3lG7IzYtypbZNxlXDECyrkUh+9oxzMJqdlZ562ko2br\r\n"
"uK6X5csbbM9uVsUva8NCsPPfZXDhrYaMKFvQGFY4pO3uhFGhccob037VN5Ifm\r\n"
"aKGM8aJ40cw2PQh38QPDdemizyVCThQ9Pcr+WgWKiG+t2Gd9NldJRLEhky0bW\r\n"
"2fc4zWZVbGq5nFXy1k+d/bgkHbVzf255eFZOKKy0NgZwig+uSlhVWPJjS4Z1w\r\n"
"LbpBKxTZp/xD0yEARs0u1ZcCELO/BkgQM50EDKmahIM4mdCs/7j1B/DdWs2i3\r\n"
"5lnbjxYYiUiyA=")
user.ensure_exists()
user.update(dict(usercertificate=user_cert),
expected_updates=dict(
usercertificate=[base64.b64decode(user_cert)])
)
command = user.make_find_command(uid=user.name,
usercertificate=user_cert)
res = command()['result']
assert len(res) == 1
user.delete()
@pytest.mark.tier1
class TestFind(XMLRPC_test):
def test_find(self, user):
""" Basic check of user-find """
user.ensure_exists()
user.find()
def test_find_with_all(self, user):
""" Basic check of user-find with --all """
user.find(all=True)
def test_find_with_pkey_only(self, user):
""" Basic check of user-find with primary keys only """
user.ensure_exists()
command = user.make_find_command(
uid=user.uid, pkey_only=True
)
result = command()
user.check_find(result, pkey_only=True)
def test_find_enabled_user(self, user):
"""Test user-find --disabled=False with enabled user"""
user.ensure_exists()
command = user.make_find_command(
uid=user.uid, pkey_only=True, nsaccountlock=False)
result = command()
user.check_find(result, pkey_only=True)
def test_negative_find_enabled_user(self, user):
"""Test user-find --disabled=True with enabled user, shouldn't
return any result"""
user.ensure_exists()
command = user.make_find_command(
uid=user.uid, pkey_only=True, nsaccountlock=True)
result = command()
user.check_find_nomatch(result)
def test_find_disabled_user(self, user):
"""Test user-find --disabled=True with disabled user"""
user.ensure_exists()
user.disable()
command = user.make_find_command(
uid=user.uid, pkey_only=True, nsaccountlock=True)
result = command()
user.check_find(result, pkey_only=True)
user.enable()
def test_negative_find_disabled_user(self, user):
"""Test user-find --disabled=False with disabled user, shouldn't
return any results"""
user.ensure_exists()
user.disable()
command = user.make_find_command(
uid=user.uid, pkey_only=True, nsaccountlock=False)
result = command()
user.check_find_nomatch(result)
user.enable()
@pytest.mark.tier1
class TestActive(XMLRPC_test):
def test_disable(self, user):
""" Disable user using user-disable """
user.ensure_exists()
user.disable()
command = user.make_retrieve_command()
result = command()
user.check_retrieve(result)
def test_enable(self, user):
""" Enable user using user-enable """
user.ensure_exists()
user.enable()
command = user.make_retrieve_command()
result = command()
user.check_retrieve(result)
def test_disable_using_setattr(self, user):
""" Disable user using setattr """
user.ensure_exists()
# we need to update the track manually
user.attrs['nsaccountlock'] = True
command = user.make_update_command(
updates=dict(setattr=u'nsaccountlock=True')
)
result = command()
user.check_update(result)
def test_enable_using_setattr(self, user):
""" Enable user using setattr """
user.ensure_exists()
user.attrs['nsaccountlock'] = False
command = user.make_update_command(
updates=dict(setattr=u'nsaccountlock=False')
)
result = command()
user.check_update(result)
def test_disable_using_usermod(self, user):
""" Disable user using user-mod """
user.update(dict(nsaccountlock=True), dict(nsaccountlock=True))
def test_enable_using_usermod(self, user):
""" Enable user using user-mod """
user.update(dict(nsaccountlock=False), dict(nsaccountlock=False))
@pytest.mark.tier1
class TestUpdate(XMLRPC_test):
def test_set_virtual_attribute(self, user):
""" Try to assign an invalid virtual attribute """
attr = 'random'
user.ensure_exists()
command = user.make_update_command(
updates=dict(setattr=(u'%s=xyz123' % attr))
)
with raises_exact(errors.ObjectclassViolation(
info=u'attribute "%s" not allowed' % attr)):
command()
def test_update(self, user):
""" Update a user attribute """
user.update(dict(givenname=u'Franta'))
def test_update_krb_ticket_policy(self, user):
""" Try to update krbmaxticketlife """
attr = 'krbmaxticketlife'
user.ensure_exists()
command = user.make_update_command(
updates=dict(setattr=(u'%s=88000' % attr))
)
with raises_exact(errors.ObjectclassViolation(
info=u'attribute "%s" not allowed' % attr)):
command()
def test_rename(self, user, renameduser):
""" Rename user and than rename it back """
user.ensure_exists()
renameduser.ensure_missing()
olduid = user.uid
user.update(updates=dict(rename=renameduser.uid))
# rename the test user back so it gets properly deleted
user.update(updates=dict(rename=olduid))
def test_rename_to_the_same_value(self, user):
""" Try to rename user to the same value """
user.ensure_exists()
command = user.make_update_command(
updates=dict(setattr=(u'uid=%s' % user.uid))
)
with raises_exact(errors.EmptyModlist()):
command()
def test_rename_to_the_same_with_other_mods(self, user):
""" Try to rename user to the same value while
including other modifications that should be done """
user.ensure_exists()
user.attrs.update(loginshell=[u'/bin/false'])
command = user.make_update_command(
updates=dict(setattr=u'uid=%s' % user.uid,
loginshell=u'/bin/false')
)
result = command()
user.check_update(result)
def test_rename_to_too_long_login(self, user):
""" Try to change user login to too long value """
user.ensure_exists()
command = user.make_update_command(
updates=dict(rename=invaliduser2)
# no exception raised, user is renamed
)
with raises_exact(errors.ValidationError(
name='rename',
error=u'can be at most 255 characters')):
command()
def test_update_illegal_ssh_pubkey(self, user):
""" Try to update user with an illegal SSH public key """
user.ensure_exists()
command = user.make_update_command(
updates=dict(ipasshpubkey=[u"anal nathrach orth' bhais's bethad "
"do che'l de'nmha"])
)
with raises_exact(errors.ValidationError(
name='sshpubkey',
error=u'invalid SSH public key')):
command()
def test_set_ipauserauthtype(self, user):
""" Set ipauserauthtype to all valid types and than back to None """
user.ensure_exists()
user.update(dict(ipauserauthtype=[
u'password', u'radius', u'otp', u'pkinit', u'hardened', u'idp',
u'passkey',
]))
user.retrieve()
user.update(dict(ipauserauthtype=None))
user.delete()
def test_set_random_password(self, user):
""" Modify user with random password """
user.ensure_exists()
user.attrs.update(
randompassword=fuzzy_password,
has_keytab=True,
has_password=True
)
user.update(
dict(random=True),
dict(random=None, randompassword=fuzzy_password)
)
user.delete()
def test_rename_to_invalid_login(self, user):
""" Try to change user login to an invalid value """
user.ensure_exists()
command = user.make_update_command(
updates=dict(rename=invaliduser1)
)
with raises_exact(errors.ValidationError(
name='rename',
error=ERRMSG_GROUPUSER_NAME.format('user'),
)):
command()
def test_rename_setattr_to_numeric_only_username(self, user):
""" Try to change name to name with only numeric chars with setattr"""
user.ensure_exists()
command = user.make_update_command(
updates=dict(setattr='uid=%s' % invaliduser3)
)
with raises_exact(errors.ValidationError(
name='uid',
error=ERRMSG_GROUPUSER_NAME.format('user'),
)):
command()
def test_rename_to_numeric_only_username(self, user):
""" Try to change user name to name containing only numeric chars"""
user.ensure_exists()
command = user.make_update_command(
updates=dict(rename=invaliduser3)
)
with raises_exact(errors.ValidationError(
name='rename',
error=ERRMSG_GROUPUSER_NAME.format('user'),
)):
command()
def test_add_radius_username(self, user):
""" Test for ticket 7569: Try to add --radius-username """
user.ensure_exists()
command = user.make_update_command(
updates=dict(ipatokenradiususername=u'radiususer')
)
command()
user.delete()
def test_update_invalid_idp(self, user):
""" Test user-mod --idp with a non-existent idp """
user.ensure_exists()
command = user.make_update_command(
updates=dict(ipaidpconfiglink=nonexistentidp)
)
with raises_exact(errors.NotFound(
reason="External IdP configuration {} not found".format(
nonexistentidp)
)):
command()
def test_update_add_idpsub(self, user):
""" Test user-mod --idp-user-id"""
user.ensure_exists()
command = user.make_update_command(
updates=dict(ipaidpsub=u'myidp_user_id')
)
command()
user.delete()
@pytest.mark.tier1
class TestCreate(XMLRPC_test):
def test_create_user_with_min_values(self, user_min):
""" Create user with uid not specified """
user_min.ensure_missing()
command = user_min.make_create_command()
command()
def test_create_with_krb_ticket_policy(self):
""" Try to create user with krbmaxticketlife set """
testuser = UserTracker(
name=u'tuser1', givenname=u'Test',
sn=u'Tuser1', setattr=u'krbmaxticketlife=88000'
)
command = testuser.make_create_command()
with raises_exact(errors.ObjectclassViolation(
info=u'attribute "%s" not allowed' % 'krbmaxticketlife')):
command()
def test_create_with_ssh_pubkey(self):
""" Create user with an assigned SSH public key """
testuser = UserTracker(
name=u'tuser1', givenname=u'Test',
sn=u'Tuser1', ipasshpubkey=sshpubkey
)
testuser.track_create()
# fingerprint is expected in the tracker attrs
testuser.attrs.update(sshpubkeyfp=[sshpubkeyfp])
command = testuser.make_create_command()
result = command()
testuser.check_create(result)
testuser.delete()
def test_create_with_invalid_login(self):
""" Try to create user with an invalid login string """
testuser = UserTracker(
name=invaliduser1, givenname=u'Test', sn=u'User1'
)
command = testuser.make_create_command()
with raises_exact(errors.ValidationError(
name=u'login',
error=ERRMSG_GROUPUSER_NAME.format('user'),
)):
command()
def test_create_with_too_long_login(self):
""" Try to create user with too long login string """
testuser = UserTracker(
name=invaliduser2, givenname=u'Test', sn=u'User1'
)
command = testuser.make_create_command()
with raises_exact(errors.ValidationError(
name=u'login',
error=u'can be at most 255 characters')):
command()
def test_create_with_full_address(self):
""" Create user with full address set """
testuser = UserTracker(
name=u'tuser1', givenname=u'Test', sn=u'Tuser1',
street=u'123 Maple Rd', l=u'Anytown', st=u'MD',
postalcode=u'01234-5678', mobile=u'410-555-1212'
)
testuser.create()
testuser.delete()
def test_create_with_random_passwd(self):
""" Create user with random password """
testuser = UserTracker(
name=u'tuser1', givenname=u'Test', sn=u'Tuser1', random=True
)
testuser.track_create()
testuser.attrs.update(
randompassword=fuzzy_password,
has_keytab=True, has_password=True,
krbextradata=[Fuzzy(type=bytes)],
krbpasswordexpiration=[fuzzy_dergeneralizedtime],
krblastpwdchange=[fuzzy_dergeneralizedtime]
)
command = testuser.make_create_command()
result = command()
testuser.check_create(result)
testuser.delete()
def test_create_with_different_default_home(self, user):
""" Change default home directory and check that a newly created
user has his home set properly """
user.ensure_missing()
user.run_command('config_mod', **{u'ipahomesrootdir': u'/other-home'})
user.track_create()
user.attrs.update(homedirectory=[u'/other-home/%s' % user.name])
command = user.make_create_command()
result = command()
user.check_create(result)
user.run_command('config_mod', **{u'ipahomesrootdir': u'/home'})
user.delete()
def test_create_with_different_default_shell(self, user):
""" Change default login shell and check that a newly created
user is created with correct login shell value """
user.ensure_missing()
user.run_command(
'config_mod', **{u'ipadefaultloginshell': u'/bin/zsh'}
)
user.track_create()
user.attrs.update(loginshell=[u'/bin/zsh'])
command = user.make_create_command()
result = command()
user.check_create(result)
user.run_command(
'config_mod',
**{u'ipadefaultloginshell': platformconstants.DEFAULT_SHELL}
)
user.delete()
def test_create_without_upg(self):
""" Try to create user without User's Primary GID """
testuser = UserTracker(
name=u'tuser1', givenname=u'Test', sn=u'Tuser1',
noprivate=True
)
command = testuser.make_create_command()
with raises_exact(errors.NotFound(
reason=u'Default group for new users is not POSIX')):
command()
def test_create_without_upg_with_gid_set(self):
""" Create user without User's Primary GID with GID set """
testuser = UserTracker(
name=u'tuser1', givenname=u'Test', sn=u'Tuser1',
noprivate=True, gidnumber=1000
)
testuser.track_create()
del testuser.attrs['mepmanagedentry']
testuser.attrs.update(gidnumber=[u'1000'])
testuser.attrs.update(
description=[],
objectclass=fuzzy_set_optional_oc(
objectclasses.user_base, 'ipantuserattrs'),
)
command = testuser.make_create_command()
result = command()
testuser.check_create(result, [u'description'])
testuser.delete()
def test_create_with_uid_999(self):
""" Check that server return uid and gid 999
when a new client asks for uid 999 """
testuser = UserTracker(
name=u'tuser1', givenname=u'Test', sn=u'Tuser1', uidnumber=999
)
testuser.track_create()
# When uid is outside of IPA id range, no SID is generated
del testuser.attrs['ipantsecurityidentifier']
testuser.attrs.update(
uidnumber=[u'999'],
gidnumber=[u'999'],
objectclass=objectclasses.user_base + ['mepOriginEntry']
)
command = testuser.make_create_command()
result = command()
testuser.check_create(result)
testuser.delete()
def test_create_with_old_DNA_MAGIC_999(self):
""" Check that server picks suitable uid and gid
when an old client asks for the magic uid 999 """
testuser = UserTracker(
name=u'tuser1', givenname=u'Test', sn=u'Tuser1',
uidnumber=999, version=u'2.49'
)
testuser.track_create()
testuser.attrs.update(
uidnumber=[lambda v: int(v) != 999],
gidnumber=[lambda v: int(v) != 999],
)
command = testuser.make_create_command()
result = command()
testuser.check_create(result)
testuser.delete()
def test_create_duplicate(self, user):
""" Try to create second user with the same name """
user.ensure_exists()
command = user.make_create_command()
with raises_exact(errors.DuplicateEntry(
message=u'user with name "%s" already exists' %
user.uid)):
command()
def test_create_where_managed_group_exists(self, user, group):
""" Create a managed group and then try to create user
with the same name the group has """
group.create()
command = user.make_command(
'user_add', group.cn, **dict(givenname=u'Test', sn=u'User1')
)
with raises_exact(errors.ManagedGroupExistsError(group=group.cn)):
command()
def test_create_with_username_starting_with_numeric(self):
"""Successfully create a user with name starting with numeric chars"""
testuser = UserTracker(
name=u'1234user', givenname=u'First1234', sn=u'Surname1234',
)
testuser.create()
testuser.delete()
def test_create_with_numeric_only_username(self):
"""Try to create a user with name only contains numeric chars"""
testuser = UserTracker(
name=invaliduser3, givenname=u'NumFirst1234', sn=u'NumSurname1234',
)
with raises_exact(errors.ValidationError(
name=u'login',
error=ERRMSG_GROUPUSER_NAME.format('user'),
)):
testuser.create()
def test_create_with_radius_username(self, user_radius):
"""Test for issue 7569: try to create a user with --radius-username"""
command = user_radius.make_create_command()
result = command()
user_radius.check_create(result)
user_radius.delete()
def test_create_with_invalididp(self):
testuser = UserTracker(
name='idpuser', givenname='idp', sn='user',
ipaidpconfiglink=nonexistentidp
)
with raises_exact(errors.NotFound(
reason="External IdP configuration {} not found".format(
nonexistentidp)
)):
testuser.create()
def test_create_with_idpsub(self, user_idp):
""" Test creation of a user with --idp-user-id"""
command = user_idp.make_create_command()
result = command()
user_idp.check_create(result, ['ipaidpsub'])
user_idp.delete()
@pytest.mark.tier1
class TestUserWithGroup(XMLRPC_test):
def test_change_default_user_group(self, group):
""" Change default group for TestUserWithGroup class of tests """
group.create()
group.run_command(
'config_mod', **{u'ipadefaultprimarygroup': group.cn}
)
def test_create_without_upg(self, user_npg):
""" Try to create user without User's Primary GID
after default group was changed """
command = user_npg.make_create_command()
# User without private group has some different attrs upon creation
# so we won't use make_create, but do own check instead
# These are set in the fixture
result = command()
user_npg.check_create(result, [u'description', u'memberof_group'])
def test_create_without_upg_with_gid_set(self, user_npg2):
""" Create user without User's Primary GID with GID set
after default group was changed """
command = user_npg2.make_create_command()
result = command()
user_npg2.check_create(result, [u'description', u'memberof_group'])
def test_set_manager(self, user_npg, user_npg2):
""" Update user with own group with manager with own group """
user_npg.update(dict(manager=user_npg2.uid))
def test_check_user_with_renamed_manager(self, user_npg, user_npg2):
""" Rename manager with own group, retrieve user and check
if its manager is also renamed """
renamed_name = u'renamed_npg2'
old_name = user_npg2.uid
user_npg2.update(updates=dict(rename=renamed_name))
user_npg.attrs.update(manager=[renamed_name])
user_npg.retrieve(all=True)
user_npg2.update(updates=dict(rename=old_name))
def test_check_if_manager_gets_removed(self, user_npg, user_npg2):
""" Delete manager and check if it's gone from user's attributes """
user_npg2.delete()
del user_npg.attrs[u'manager']
del user_npg.attrs[u'description']
user_npg.retrieve(all=True)
def test_change_default_user_group_back(self, user_npg, user_npg2):
""" Change default group back to 'ipausers' and clean up members """
user_npg.delete()
user_npg.run_command(
'config_mod', **{u'ipadefaultprimarygroup': u'ipausers'}
)
@pytest.mark.tier1
class TestUserWithUPGDisabled(XMLRPC_test):
""" Tests with UPG plugin disabled """
@classmethod
def managed_entries_upg(cls, action='enable'):
""" Change the UPG plugin state """
assert action in ('enable', 'disable')
ipautil.run(['ipa-managed-entries', '-e', 'UPG Definition', action])
@pytest.fixture(autouse=True, scope="class")
def user_with_upg_disabled_setup(self, request, xmlrpc_setup):
cls = request.cls
cls.managed_entries_upg(action='disable')
def fin():
cls.managed_entries_upg(action='enable')
request.addfinalizer(fin)
def test_create_without_upg(self):
""" Try to create user without User's Primary GID
As the UPG plugin is disabled, the user gets assigned to the Default
Group for new users (ipausers) which is not POSIX and the command
is expected to fail
"""
testuser = UserTracker(
name=u'tuser1', givenname=u'Test', sn=u'Tuser1'
)
command = testuser.make_create_command()
with raises_exact(errors.NotFound(
reason=u'Default group for new users is not POSIX')):
command()
def test_create_without_upg_with_gid_set(self):
""" Create user without User's Primary GID with GID set
The UPG plugin is disabled, but the user is provided with a group
"""
testuser = UserTracker(
name=u'tuser1', givenname=u'Test', sn=u'Tuser1',
gidnumber=1000
)
testuser.track_create()
del testuser.attrs['mepmanagedentry']
testuser.attrs.update(gidnumber=[u'1000'])
testuser.attrs.update(
description=[],
objectclass=objectclasses.user_base + [u'ipantuserattrs'],
)
command = testuser.make_create_command()
result = command()
testuser.check_create(result, [u'description'])
testuser.delete()
def test_create_where_managed_group_exists(self, user, group):
""" Create a managed group and then try to create user
with the same name the group has
As the UPG plugin is disabled, there is no conflict
"""
group.create()
testuser = UserTracker(
name=group.cn, givenname=u'Test', sn=u'Tuser1',
gidnumber=1000
)
testuser.track_create()
del testuser.attrs['mepmanagedentry']
testuser.attrs.update(gidnumber=[u'1000'])
testuser.attrs.update(
description=[],
objectclass=fuzzy_set_optional_oc(
objectclasses.user_base, 'ipantuserattrs'
),
)
command = testuser.make_create_command()
result = command()
testuser.check_create(result, [u'description'])
testuser.delete()
@pytest.mark.tier1
class TestManagers(XMLRPC_test):
def test_create_user_with_manager(self, user):
""" Create user using user-add with manager option set """
user.ensure_exists()
user_w_manager = UserTracker(
name='user_w_manager', givenname=u'Test', sn=u'User1',
manager=user.uid
)
user_w_manager.track_create()
command = user_w_manager.make_create_command()
result = command()
user_w_manager.check_create(result)
user_w_manager.delete()
def test_assign_nonexistent_manager(self, user, user2):
""" Try to assign user a non-existent manager """
user.ensure_exists()
user2.ensure_missing()
command = user.make_update_command(
updates=dict(manager=user2.uid)
)
with raises_exact(errors.NotFound(
reason=u'manager %s not found' % user2.uid)):
command()
def test_assign_manager(self, user, user2):
""" Make user manager of another user """
user.ensure_exists()
user2.ensure_exists()
user.update(dict(manager=user2.uid))
def test_search_by_manager(self, user, user2):
""" Find user by his manager's UID """
command = user.make_find_command(manager=user2.uid)
result = command()
user.check_find(result)
def test_delete_both_user_and_manager(self, user, user2):
""" Delete both user and its manager at once """
result = user.run_command(
'user_del', [user.uid, user2.uid],
preserve=False, no_preserve=True
)
assert_deepequal(dict(
value=[user.uid, user2.uid],
summary=u'Deleted user "%s,%s"' % (user.uid, user2.uid),
result=dict(failed=[]),
), result)
# mark users as deleted
user.exists = False
user2.exists = False
@pytest.mark.tier1
class TestAdmins(XMLRPC_test):
def test_delete_admin(self):
""" Try to delete the protected admin user """
tracker = Tracker()
command = tracker.make_command('user_del', admin1)
with raises_exact(errors.ProtectedEntryError(label=u'user',
key=admin1, reason='privileged user')):
command()
def test_rename_admin(self):
""" Try to rename the admin user """
tracker = Tracker()
command = tracker.make_command('user_mod', admin1,
**dict(rename=u'newadmin'))
with raises_exact(errors.ProtectedEntryError(label=u'user',
key=admin1, reason='privileged user')):
command()
def test_disable_original_admin(self):
""" Try to disable the original admin """
tracker = Tracker()
command = tracker.make_command('user_disable', admin1)
with raises_exact(errors.LastMemberError(label=u'group',
key=admin1, container=admin_group)):
command()
def test_create_admin2(self, admin2):
""" Test whether second admin gets created """
admin2.ensure_exists()
admin2.make_admin()
admin2.delete()
def test_last_admin_preservation(self, admin2):
""" Create a second admin, disable it. Then try to disable and
remove the original one and receive LastMemberError. Last trial
are these ops with second admin removed. """
admin2.ensure_exists()
admin2.make_admin()
admin2.disable()
tracker = Tracker()
with raises_exact(errors.LastMemberError(label=u'group',
key=admin1, container=admin_group)):
tracker.run_command('user_disable', admin1)
admin2.delete()
@pytest.mark.tier1
class TestPreferredLanguages(XMLRPC_test):
def test_invalid_preferred_languages(self, user):
""" Try to assign various invalid preferred languages to user """
user.ensure_exists()
for invalidlanguage in invalidlanguages:
command = user.make_update_command(
dict(preferredlanguage=invalidlanguage)
)
with raises_exact(errors.ValidationError(
name='preferredlanguage',
error=(u'must match RFC 2068 - 14.4, e.g., '
'"da, en-gb;q=0.8, en;q=0.7"')
)):
command()
user.delete()
def test_valid_preferred_languages(self, user):
""" Update user with different preferred languages """
for validlanguage in validlanguages:
user.update(dict(preferredlanguage=validlanguage))
user.delete()
@pytest.mark.tier1
class TestPrincipals(XMLRPC_test):
def test_create_with_bad_realm_in_principal(self):
""" Try to create user with a bad realm in principal """
testuser = UserTracker(
name=u'tuser1', givenname=u'Test', sn=u'Tuser1',
krbprincipalname=u'tuser1@NOTFOUND.ORG'
)
command = testuser.make_create_command()
with raises_exact(errors.RealmMismatch()):
command()
def test_create_with_malformed_principal(self):
""" Try to create user with wrongly formed principal """
testuser = UserTracker(
name=u'tuser1', givenname=u'Test', sn=u'Tuser1',
krbprincipalname=u'tuser1@BAD@NOTFOUND.ORG'
)
command = testuser.make_create_command()
with raises_exact(errors.ConversionError(
name='principal', error="Malformed principal: '{}'".format(
testuser.kwargs['krbprincipalname']))):
command()
def test_set_principal_expiration(self, user):
""" Set principal expiration for user """
user.update(
dict(krbprincipalexpiration=principal_expiration_string),
dict(krbprincipalexpiration=[principal_expiration_date])
)
def test_set_invalid_principal_expiration(self, user):
""" Try to set incorrent principal expiration value for user """
user.ensure_exists()
command = user.make_update_command(
dict(krbprincipalexpiration=invalid_expiration_string)
)
with raises_exact(errors.ConversionError(
name='principal_expiration',
error=(u'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')
)):
command()
def test_create_with_uppercase_principal(self):
""" Create user with upper-case principal """
testuser = UserTracker(
name=u'tuser1', givenname=u'Test', sn=u'Tuser1',
krbprincipalname=u'tuser1'.upper()
)
testuser.create()
testuser.delete()
@pytest.mark.tier1
class TestValidation(XMLRPC_test):
# The assumption for this class of tests is that if we don't
# get a validation error then the request was processed normally.
def test_validation_disabled_on_deletes(self):
""" Test that validation is disabled on user deletes """
tracker = Tracker()
command = tracker.make_command('user_del', invaliduser1)
with raises_exact(errors.NotFound(
reason=u'%s: user not found' % invaliduser1)):
command()
def test_validation_disabled_on_show(self):
""" Test that validation is disabled on user retrieves """
tracker = Tracker()
command = tracker.make_command('user_show', invaliduser1)
with raises_exact(errors.NotFound(
reason=u'%s: user not found' % invaliduser1)):
command()
def test_validation_disabled_on_find(self, user):
""" Test that validation is disabled on user searches """
result = user.run_command('user_find', invaliduser1)
user.check_find_nomatch(result)
@pytest.mark.tier1
class TestDeniedBindWithExpiredPrincipal(XMLRPC_test):
password = u'random'
connection = None
@pytest.fixture(autouse=True, scope="class")
def bind_with_expired_principal_setup(self, request, xmlrpc_setup):
cls = request.cls
cls.connection = ldap_initialize(
'ldap://{host}'.format(host=api.env.host)
)
cls.connection.start_tls_s()
def test_bind_as_test_user(self, user):
""" Bind as user """
self.failsafe_add(
api.Object.user,
user.uid,
givenname=u'Test',
sn=u'User1',
userpassword=self.password,
krbprincipalexpiration=principal_expiration_string
)
self.connection.simple_bind_s(
str(get_user_dn(user.uid)), self.password
)
def test_bind_as_expired_test_user(self, user):
""" Try to bind as expired user """
api.Command['user_mod'](
user.uid,
krbprincipalexpiration=expired_expiration_string
)
raises(ldap.UNWILLING_TO_PERFORM,
self.connection.simple_bind_s,
str(get_user_dn(user.uid)), self.password
)
def test_bind_as_renewed_test_user(self, user):
""" Bind as renewed user """
api.Command['user_mod'](
user.uid,
krbprincipalexpiration=principal_expiration_string
)
self.connection.simple_bind_s(
str(get_user_dn(user.uid)), self.password
)
# This set of functions (get_*, upg_check, not_upg_check)
# is mostly for legacy purposes here, tests using UserTracker
# should not rely on them
def get_user_result(uid, givenname, sn, operation='show', omit=[],
**overrides):
"""Get a user result for a user-{add,mod,find,show} command
This gives the result as from a user_add(uid, givenname=givenname, sn=sn);
modifications to that can be specified in ``omit`` and ``overrides``.
The ``operation`` can be one of:
- add
- show
- show-all ((show with the --all flag)
- find
- mod
Attributes named in ``omit`` are removed from the result; any additional
or non-default values can be specified in ``overrides``.
"""
# sn can be None; this should only be used from `get_admin_result`
cn = overrides.get('cn', ['%s %s' % (givenname, sn or '')])
cn[0] = cn[0].strip()
result = dict(
homedirectory=[u'/home/%s' % uid],
loginshell=[platformconstants.DEFAULT_SHELL],
uid=[uid],
uidnumber=[fuzzy_digits],
gidnumber=[fuzzy_digits],
krbcanonicalname=[u'%s@%s' % (uid, api.env.realm)],
krbprincipalname=[u'%s@%s' % (uid, api.env.realm)],
mail=[u'%s@%s' % (uid, api.env.domain)],
has_keytab=False,
has_password=False,
)
if sn:
result['sn'] = [sn]
if givenname:
result['givenname'] = [givenname]
if operation in ('add', 'show', 'show-all', 'find'):
result.update(
dn=get_user_dn(uid),
)
if operation in ('add', 'show-all'):
result.update(
cn=cn,
displayname=cn,
gecos=cn,
initials=[givenname[0] + (sn or '')[:1]],
ipauniqueid=[fuzzy_uuid],
mepmanagedentry=[get_group_dn(uid)],
objectclass=fuzzy_set_optional_oc(
objectclasses.user, 'ipantuserattrs'),
krbprincipalname=[u'%s@%s' % (uid, api.env.realm)],
krbcanonicalname=[u'%s@%s' % (uid, api.env.realm)],
)
if operation == 'show-all':
result.update(
ipantsecurityidentifier=[fuzzy_user_or_group_sid],
)
if operation in ('show', 'show-all', 'find', 'mod'):
result.update(
nsaccountlock=False,
)
if operation in ('add', 'show', 'show-all', 'mod'):
result.update(
memberof_group=[u'ipausers'],
)
for key in omit:
del result[key]
result.update(overrides)
return result
def get_admin_result(operation='show', **overrides):
"""Give the result for the default admin user
Any additional or non-default values can be given in ``overrides``.
"""
result = get_user_result(
u'admin', None, u'Administrator', operation,
omit=['mail'],
has_keytab=True,
has_password=True,
loginshell=[platformconstants.DEFAULT_ADMIN_SHELL],
**overrides)
return result
def get_user_dn(uid):
""" Get user DN by uid """
return DN(('uid', uid), api.env.container_user, api.env.basedn)
def get_group_dn(cn):
""" Get group DN by CN """
return DN(('cn', cn), api.env.container_group, api.env.basedn)
def upg_check(response):
"""Check that the user was assigned to the corresponding private group."""
assert_equal(response['result']['uidnumber'],
response['result']['gidnumber'])
return True
def not_upg_check(response):
"""
Check that the user was not assigned to the corresponding
private group.
"""
assert_not_equal(response['result']['uidnumber'],
response['result']['gidnumber'])
return True
| 48,603
|
Python
|
.py
| 1,164
| 32.701031
| 79
| 0.625913
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,469
|
test_caacl_profile_enforcement.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_caacl_profile_enforcement.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
from __future__ import absolute_import
import os
import pytest
import tempfile
import six
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from ipalib import api, errors
from ipaplatform.paths import paths
from ipatests.util import (
prepare_config, unlock_principal_password, change_principal,
host_keytab)
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
from ipatests.test_xmlrpc.tracker.certprofile_plugin import CertprofileTracker
from ipatests.test_xmlrpc.tracker.caacl_plugin import CAACLTracker
from ipatests.test_xmlrpc.tracker.ca_plugin import CATracker
from ipatests.test_xmlrpc.tracker.host_plugin import HostTracker
from ipatests.test_xmlrpc.tracker.service_plugin import ServiceTracker
from ipapython.ipautil import run
if six.PY3:
unicode = str
BASE_DIR = os.path.dirname(__file__)
SMIME_PROFILE_TEMPLATE = os.path.join(BASE_DIR, 'data/smime.cfg.tmpl')
SMIME_MOD_CONSTR_PROFILE_TEMPLATE = os.path.join(BASE_DIR, 'data/smime-mod.cfg.tmpl')
CERT_OPENSSL_CONFIG_TEMPLATE = os.path.join(BASE_DIR, 'data/usercert.conf.tmpl')
CERT_RSA_PRIVATE_KEY_PATH = os.path.join(BASE_DIR, 'data/usercert-priv-key.pem')
SMIME_USER_INIT_PW = u'Change123'
SMIME_USER_PW = u'Secret123'
def generate_user_csr(username, domain=None):
csr_values = dict(
ipadomain=domain if domain else api.env.domain,
username=username)
with tempfile.NamedTemporaryFile(mode='w') as csr_file:
run([paths.OPENSSL, 'req', '-new', '-key', CERT_RSA_PRIVATE_KEY_PATH,
'-out', csr_file.name,
'-config', prepare_config(
CERT_OPENSSL_CONFIG_TEMPLATE, csr_values)])
with open(csr_file.name, 'r') as f:
csr = unicode(f.read())
return csr
@pytest.fixture(scope='class')
def smime_profile(request, xmlrpc_setup):
profile_path = prepare_config(
SMIME_PROFILE_TEMPLATE,
dict(ipadomain=api.env.domain, iparealm=api.env.realm))
tracker = CertprofileTracker(u'smime', store=True,
desc=u"S/MIME certificate profile",
profile=profile_path)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def smime_acl(request, xmlrpc_setup):
tracker = CAACLTracker(u'smime_acl')
return tracker.make_fixture(request)
# TODO: rewrite these into Tracker instances
# UserTracker has problems while setting passwords.
# Until fixed, will use this fixture.
@pytest.fixture(scope='class')
def smime_user(request, xmlrpc_setup):
username = u'alice'
api.Command.user_add(uid=username, givenname=u'Alice', sn=u'SMIME',
userpassword=SMIME_USER_INIT_PW)
unlock_principal_password(username, SMIME_USER_INIT_PW, SMIME_USER_PW)
def fin():
api.Command.user_del(username)
request.addfinalizer(fin)
return username
@pytest.fixture(scope='class')
def smime_group(request, xmlrpc_setup):
api.Command.group_add(u'smime_users')
def fin():
api.Command.group_del(u'smime_users')
request.addfinalizer(fin)
return u'smime_users'
@pytest.mark.tier1
class TestCertSignMIME(XMLRPC_test):
def test_cert_import(self, smime_profile):
smime_profile.ensure_exists()
def test_create_acl(self, smime_acl):
smime_acl.ensure_exists()
def test_add_profile_to_acl(self, smime_acl, smime_profile):
smime_acl.add_profile(certprofile=smime_profile.name)
# rewrite to trackers, prepare elsewhere
def test_add_user_to_group(self, smime_group, smime_user):
api.Command.group_add_member(smime_group, user=smime_user)
def test_add_group_to_acl(self, smime_group, smime_acl):
smime_acl.add_user(group=smime_group)
def test_sign_smime_csr(self, smime_profile, smime_user):
csr = generate_user_csr(smime_user)
with change_principal(smime_user, SMIME_USER_PW):
api.Command.cert_request(csr, principal=smime_user,
profile_id=smime_profile.name)
def test_sign_smime_csr_full_principal(self, smime_profile, smime_user):
csr = generate_user_csr(smime_user)
smime_user_principal = '@'.join((smime_user, api.env.realm))
with change_principal(smime_user, SMIME_USER_PW):
api.Command.cert_request(csr, principal=smime_user_principal,
profile_id=smime_profile.name)
@pytest.mark.tier1
class TestSignWithDisabledACL(XMLRPC_test):
def test_import_profile_and_acl(self, smime_profile, smime_acl):
smime_profile.ensure_exists()
smime_acl.ensure_missing()
smime_acl.ensure_exists()
def test_add_profile_to_acl(self, smime_acl, smime_profile):
smime_acl.add_profile(certprofile=smime_profile.name)
# rewrite to trackers, prepare elsewhere
def test_add_user_to_group(self, smime_group, smime_user):
api.Command.group_add_member(smime_group, user=smime_user)
def test_add_group_to_acl(self, smime_group, smime_acl):
smime_acl.add_user(group=smime_group)
def test_disable_acl(self, smime_acl):
smime_acl.disable()
def test_signing_with_disabled_acl(self, smime_acl, smime_profile,
smime_user):
csr = generate_user_csr(smime_user)
with change_principal(smime_user, SMIME_USER_PW):
with pytest.raises(errors.ACIError):
api.Command.cert_request(
csr, profile_id=smime_profile.name,
principal=smime_user)
def test_admin_overrides_disabled_acl(self, smime_acl, smime_profile,
smime_user):
csr = generate_user_csr(smime_user)
api.Command.cert_request(
csr, profile_id=smime_profile.name,
principal=smime_user)
@pytest.mark.tier1
class TestSignWithoutGroupMembership(XMLRPC_test):
def test_import_profile_and_acl(self, smime_profile, smime_acl):
smime_profile.ensure_exists()
smime_acl.ensure_missing()
smime_acl.ensure_exists()
def test_add_profile_to_acl(self, smime_acl, smime_profile):
smime_acl.add_profile(certprofile=smime_profile.name)
def test_add_group_to_acl(self, smime_group, smime_acl, smime_user):
# smime user should not be a member of this group
#
# adding smime_user fixture to ensure it exists
smime_acl.add_user(group=smime_group)
def test_signing_with_non_member_principal(self, smime_acl, smime_profile,
smime_user):
csr = generate_user_csr(smime_user)
with change_principal(smime_user, SMIME_USER_PW):
with pytest.raises(errors.ACIError):
api.Command.cert_request(
csr,
profile_id=smime_profile.name,
principal=smime_user)
def test_admin_overrides_group_membership(self, smime_acl, smime_profile,
smime_user):
csr = generate_user_csr(smime_user)
api.Command.cert_request(
csr, profile_id=smime_profile.name,
principal=smime_user)
@pytest.mark.tier1
class TestSignWithChangedProfile(XMLRPC_test):
""" Test to verify that the updated profile is used.
The profile change requires different CN in CSR
than the one configured. This leads to rejection
based on not meeting the profile constraints.
"""
def test_prepare_env(self, smime_profile, smime_acl):
smime_profile.ensure_exists()
smime_acl.ensure_exists()
smime_acl.add_profile(certprofile=smime_profile.name)
def test_prepare_user_and_group(self, smime_group, smime_user, smime_acl):
api.Command.group_add_member(smime_group, user=smime_user)
smime_acl.add_user(group=smime_group)
def test_modify_smime_profile(self, smime_profile):
updated_profile_path = prepare_config(SMIME_MOD_CONSTR_PROFILE_TEMPLATE,
dict(
ipadomain=api.env.domain,
iparealm=api.env.realm))
with open(updated_profile_path) as f:
updated_profile = unicode(f.read())
updates = {u'file': updated_profile}
update_smime_profile = smime_profile.make_update_command(updates)
update_smime_profile()
def test_sign_smime_csr(self, smime_profile, smime_user):
csr = generate_user_csr(smime_user)
with change_principal(smime_user, SMIME_USER_PW):
with pytest.raises(errors.CertificateOperationError):
api.Command.cert_request(csr, principal=smime_user,
profile_id=smime_profile.name)
@pytest.fixture(scope='class')
def smime_signing_ca(request, xmlrpc_setup):
name = u'smime-signing-ca'
subject = u'CN=SMIME CA,O=test industries Inc.'
return CATracker(name, subject).make_fixture(request)
@pytest.mark.tier1
class TestCertSignMIMEwithSubCA(XMLRPC_test):
""" Test Certificate Signing with Sub CA
The test covers following areas:
* signing a CSR with custom certificate profile
using a designated Sub CA
* Verify that the Issuer of the signed certificate
is the reqested CA
* Verify that when not set, cert-request uses the default CA.
This it verified by violating an ACL
* Verify that when not set, cert-request uses the default
certificate profile.
The latter two test cases are implemented in this module
as not to replicate the fixtures to cert plugin test module.
"""
def test_cert_import(self, smime_profile):
smime_profile.ensure_exists()
def test_create_acl(self, smime_acl):
smime_acl.ensure_exists()
def test_create_subca(self, smime_signing_ca):
smime_signing_ca.ensure_exists()
def test_add_profile_to_acl(self, smime_acl, smime_profile):
smime_acl.add_profile(certprofile=smime_profile.name)
def test_add_subca_to_acl(self, smime_acl, smime_signing_ca):
smime_acl.add_ca(smime_signing_ca.name)
# rewrite to trackers, prepare elsewhere
def test_add_user_to_group(self, smime_group, smime_user):
api.Command.group_add_member(smime_group, user=smime_user)
def test_add_group_to_acl(self, smime_group, smime_acl):
smime_acl.add_user(group=smime_group)
def test_sign_smime_csr(self, smime_profile, smime_user, smime_signing_ca):
csr = generate_user_csr(smime_user)
with change_principal(smime_user, SMIME_USER_PW):
api.Command.cert_request(csr, principal=smime_user,
profile_id=smime_profile.name,
cacn=smime_signing_ca.name)
def test_sign_smime_csr_full_principal(
self, smime_profile, smime_user, smime_signing_ca):
csr = generate_user_csr(smime_user)
smime_user_principal = '@'.join((smime_user, api.env.realm))
with change_principal(smime_user, SMIME_USER_PW):
api.Command.cert_request(csr, principal=smime_user_principal,
profile_id=smime_profile.name,
cacn=smime_signing_ca.name)
def test_verify_cert_issuer_dn_is_subca(
self, smime_profile, smime_user, smime_signing_ca):
csr = generate_user_csr(smime_user)
smime_user_principal = '@'.join((smime_user, api.env.realm))
with change_principal(smime_user, SMIME_USER_PW):
cert_info = api.Command.cert_request(
csr, principal=smime_user_principal,
profile_id=smime_profile.name, cacn=smime_signing_ca.name)
assert cert_info['result']['issuer'] == smime_signing_ca.ipasubjectdn
def test_sign_smime_csr_fallback_to_default_CA(
self, smime_profile, smime_user, smime_signing_ca):
""" Attempt to sign a CSR without CA specified.
The request will satisfy SMIME_ACL via the profile ID,
however not specifying the CA will fallback to the IPA CA
for which SMIME profile isn't enabled, thus violating ACL.
"""
csr = generate_user_csr(smime_user)
smime_user_principal = '@'.join((smime_user, api.env.realm))
with pytest.raises(errors.ACIError):
with change_principal(smime_user, SMIME_USER_PW):
api.Command.cert_request(csr, principal=smime_user_principal,
profile_id=smime_profile.name)
def test_sign_smime_csr_fallback_to_default_cert_profile(
self, smime_profile, smime_user, smime_signing_ca):
""" Attempt to sign a CSR without certificate profile specified.
Similar to previous test case.
By specifying only the CA to use, profile will fallback to
the default caIPAserviceCert profile which is not enabled
via ACL to be used with the CA, thus failing the request.
"""
csr = generate_user_csr(smime_user)
smime_user_principal = '@'.join((smime_user, api.env.realm))
with pytest.raises(errors.ACIError):
with change_principal(smime_user, SMIME_USER_PW):
api.Command.cert_request(csr, principal=smime_user_principal,
cacn=smime_signing_ca.name)
@pytest.fixture(scope='class')
def santest_subca(request, xmlrpc_setup):
name = u'default-profile-subca'
subject = u'CN={},O=test'.format(name)
tr = CATracker(name, subject)
return tr.make_fixture(request)
@pytest.fixture(scope='class')
def santest_subca_acl(request, xmlrpc_setup):
tr = CAACLTracker(u'default_profile_subca')
return tr.make_fixture(request)
@pytest.fixture(scope='class')
def santest_host_1(request, xmlrpc_setup):
tr = HostTracker(u'santest-host-1')
return tr.make_fixture(request)
@pytest.fixture(scope='class')
def santest_host_2(request, xmlrpc_setup):
tr = HostTracker(u'santest-host-2')
return tr.make_fixture(request)
@pytest.fixture(scope='class')
def santest_service_host_1(request, santest_host_1):
tr = ServiceTracker(u'srv', santest_host_1.name)
return tr.make_fixture(request)
@pytest.fixture(scope='class')
def santest_service_host_2(request, santest_host_2):
tr = ServiceTracker(u'srv', santest_host_2.name)
return tr.make_fixture(request)
@pytest.fixture
def santest_csr(request, santest_host_1, santest_host_2):
backend = default_backend()
pkey = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=backend
)
csr = x509.CertificateSigningRequestBuilder().subject_name(x509.Name([
x509.NameAttribute(NameOID.COMMON_NAME, santest_host_1.fqdn),
x509.NameAttribute(NameOID.ORGANIZATION_NAME, api.env.realm)
])).add_extension(x509.SubjectAlternativeName([
x509.DNSName(santest_host_1.name),
x509.DNSName(santest_host_2.name)
]), False
).add_extension(
x509.BasicConstraints(ca=False, path_length=None),
True
).add_extension(
x509.KeyUsage(
digital_signature=True, content_commitment=True,
key_encipherment=True, data_encipherment=False,
key_agreement=False, key_cert_sign=False,
crl_sign=False, encipher_only=False,
decipher_only=False
),
False
).sign(
pkey, hashes.SHA256(), backend
).public_bytes(serialization.Encoding.PEM)
return csr.decode('ascii')
class SubjectAltNameOneServiceBase(XMLRPC_test):
"""Base setup class for tests with SAN in CSR
The class prepares an environment for test cases based
on evaluation of ACLs and fields requested in a CSR.
The class creates following entries:
* host entry
* santest-host-1
* service entry
* srv/santest-host-1
* Sub CA
* default-profile-subca
This one is created in order not to need
to re-import caIPAServiceCert profile
* CA ACL
* default_profile_subca
After executing the methods the CA ACL should contain:
CA ACL:
* santest-host-1 -- host
* srv/santest-host-1 -- service
* default-profile-subca -- CA
* caIPAServiceCert -- profile
"""
def test_prepare_caacl_hosts(self, santest_subca_acl, santest_host_1):
santest_subca_acl.ensure_exists()
santest_host_1.ensure_exists()
santest_subca_acl.add_host(santest_host_1.name)
def test_prepare_caacl_CA(self, santest_subca_acl, santest_subca):
santest_subca.ensure_exists()
santest_subca_acl.add_ca(santest_subca.name)
def test_prepare_caacl_profile(self, santest_subca_acl):
santest_subca_acl.add_profile(u'caIPAserviceCert')
def test_prepare_caacl_services(self, santest_subca_acl,
santest_service_host_1):
santest_service_host_1.ensure_exists()
santest_subca_acl.add_service(santest_service_host_1.name)
class CAACLEnforcementOnCertBase(SubjectAltNameOneServiceBase):
"""
Base setup class for tests with SAN in CSR, where
multiple hosts and services are in play.
In addition to the host and service created in the base class,
this class adds the following entries to the environment:
* host entry
* santest-host-2
* service entry
* srv/santest-host-2
"""
def test_prepare_add_host_2(self, santest_host_2, santest_service_host_2):
santest_host_2.ensure_exists()
santest_service_host_2.ensure_exists()
@pytest.mark.tier1
class TestNoMatchForSubjectAltNameDnsName(SubjectAltNameOneServiceBase):
"""Sign certificate request with an invalid SAN dnsName.
The CSR includes a DNS name that does not correspond to a
principal alias or alternative principal.
"""
def test_request_cert_with_not_allowed_SAN(
self, santest_subca, santest_host_1,
santest_service_host_1, santest_csr):
with host_keytab(santest_host_1.name) as keytab_filename:
with change_principal(santest_host_1.attrs['krbcanonicalname'][0],
keytab=keytab_filename):
with pytest.raises(errors.NotFound):
api.Command.cert_request(
santest_csr,
principal=santest_service_host_1.name,
cacn=santest_subca.name
)
@pytest.mark.tier1
class TestPrincipalAliasForSubjectAltNameDnsName(SubjectAltNameOneServiceBase):
"""Test cert-request with SAN dnsName corresponding to a princpial alias.
Request should succeed.
"""
def test_add_principal_alias(
self, santest_service_host_1, santest_service_host_2):
api.Command.service_add_principal(
santest_service_host_1.name,
santest_service_host_2.name)
def test_request_cert_with_SAN_matching_principal_alias(
self, santest_subca, santest_host_1,
santest_service_host_1, santest_csr):
with host_keytab(santest_host_1.name) as keytab_filename:
with change_principal(
santest_host_1.attrs['krbcanonicalname'][0],
keytab=keytab_filename):
api.Command.cert_request(
santest_csr,
principal=santest_service_host_1.name,
cacn=santest_subca.name
)
@pytest.mark.tier1
class TestSignCertificateWithInvalidSAN(CAACLEnforcementOnCertBase):
"""Sign certificate request witn an invalid SAN entry
Using the environment prepared by the base class, ask to sign
a certificate request for a service managed by one host only.
The CSR contains another domain name in SAN extension that should
be refused as the host does not have rights to manage the service.
"""
def test_request_cert_with_not_allowed_SAN(
self, santest_subca, santest_host_1, santest_host_2,
santest_service_host_1, santest_csr):
with host_keytab(santest_host_1.name) as keytab_filename:
with change_principal(santest_host_1.attrs['krbcanonicalname'][0],
keytab=keytab_filename):
with pytest.raises(errors.ACIError):
api.Command.cert_request(
santest_csr,
principal=santest_service_host_1.name,
cacn=santest_subca.name
)
@pytest.mark.tier1
class TestSignServiceCertManagedByMultipleHosts(CAACLEnforcementOnCertBase):
""" Sign certificate request with multiple subject alternative names
Using the environment of the base class, modify the service to be managed
by the second host. Then request a certificate for the service with SAN
of the second host in CSR. The certificate should be issued.
"""
def test_make_service_managed_by_each_host(self,
santest_host_1,
santest_service_host_1,
santest_host_2,
santest_service_host_2):
api.Command['service_add_host'](
santest_service_host_1.name, host=[santest_host_2.fqdn]
)
api.Command['service_add_host'](
santest_service_host_2.name, host=[santest_host_1.fqdn]
)
def test_extend_the_ca_acl(self, santest_subca_acl, santest_host_2,
santest_service_host_2):
santest_subca_acl.add_host(santest_host_2.name)
santest_subca_acl.add_service(santest_service_host_2.name)
def test_request_cert_with_additional_host(
self, santest_subca, santest_host_1, santest_host_2,
santest_service_host_1, santest_csr):
with host_keytab(santest_host_1.name) as keytab_filename:
with change_principal(santest_host_1.attrs['krbcanonicalname'][0],
keytab=keytab_filename):
api.Command.cert_request(
santest_csr,
principal=santest_service_host_1.name,
cacn=santest_subca.name
)
@pytest.mark.tier1
class TestSignServiceCertWithoutSANServiceInACL(CAACLEnforcementOnCertBase):
""" Sign certificate request with multiple subject alternative names
This test case doesn't have the service hosted on a host in SAN
in the CA ACL. The assumption is that the issuance will fail.
"""
def test_make_service_managed_by_each_host(self,
santest_host_1,
santest_service_host_1,
santest_host_2,
santest_service_host_2):
api.Command['service_add_host'](
santest_service_host_1.name, host=[santest_host_2.fqdn]
)
api.Command['service_add_host'](
santest_service_host_2.name, host=[santest_host_1.fqdn]
)
def test_extend_the_ca_acl(self, santest_subca_acl, santest_host_2,
santest_service_host_2):
santest_subca_acl.add_host(santest_host_2.name)
def test_request_cert_with_additional_host(
self, santest_subca, santest_host_1, santest_host_2,
santest_service_host_1, santest_csr):
with host_keytab(santest_host_1.name) as keytab_filename:
with change_principal(santest_host_1.attrs['krbcanonicalname'][0],
keytab=keytab_filename):
with pytest.raises(errors.ACIError):
api.Command.cert_request(
santest_csr,
principal=santest_service_host_1.name,
cacn=santest_subca.name
)
@pytest.mark.tier1
class TestManagedByACIOnCertRequest(CAACLEnforcementOnCertBase):
"""Test issuence of a certificate by external host
The test verifies that the managed by attribute of a service
is enforced on certificate signing.
The two test cases test the issuance of a service certificate
to a service by a second host.
In one of them the service is not managed by the principal
requesting the certificate, thus the issuance should fail.
The second one makes the service managed, thus the certificate
should be issued.
"""
def test_update_the_caacl(self,
santest_subca_acl,
santest_host_2,
santest_service_host_2):
santest_subca_acl.add_host(santest_host_2.name)
santest_subca_acl.add_service(santest_service_host_2.name)
def test_issuing_service_cert_by_unrelated_host(self,
santest_subca,
santest_host_1,
santest_host_2,
santest_service_host_1,
santest_csr):
with host_keytab(santest_host_2.name) as keytab_filename:
with change_principal(santest_host_2.attrs['krbcanonicalname'][0],
keytab=keytab_filename):
with pytest.raises(errors.ACIError):
api.Command.cert_request(
santest_csr,
principal=santest_service_host_1.name,
cacn=santest_subca.name
)
def test_issuing_service_cert_by_related_host(self,
santest_subca,
santest_host_1,
santest_host_2,
santest_service_host_1,
santest_csr):
# The test case alters the previous state by making
# the service managed by the second host.
# Then it attempts to request the certificate again
api.Command['service_add_host'](
santest_service_host_1.name, host=[santest_host_2.fqdn]
)
with host_keytab(santest_host_2.name) as keytab_filename:
with change_principal(santest_host_2.attrs['krbcanonicalname'][0],
keytab=keytab_filename):
api.Command.cert_request(
santest_csr,
principal=santest_service_host_1.name,
cacn=santest_subca.name
)
| 27,432
|
Python
|
.py
| 560
| 37.532143
| 85
| 0.633662
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,470
|
test_privilege_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_privilege_plugin.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 the `ipaserver/plugins/privilege.py` module.
"""
from ipalib import api, errors
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import Declarative
from ipapython.dn import DN
import pytest
permission1 = u'testperm'
permission1_dn = DN(('cn',permission1),
api.env.container_permission,api.env.basedn)
permission2 = u'testperm2'
permission2_dn = DN(('cn',permission2),
api.env.container_permission,api.env.basedn)
privilege1 = u'testpriv1'
privilege1_dn = DN(('cn',privilege1),
api.env.container_privilege,api.env.basedn)
users_dn = DN(api.env.container_user, api.env.basedn)
@pytest.mark.tier1
class test_privilege(Declarative):
cleanup_commands = [
('permission_del', [permission1], {}),
('permission_del', [permission2], {}),
('privilege_del', [privilege1], {}),
]
tests = [
dict(
desc='Try to retrieve non-existent %r' % privilege1,
command=('privilege_show', [privilege1], {}),
expected=errors.NotFound(
reason=u'%s: privilege not found' % privilege1),
),
dict(
desc='Try to update non-existent %r' % privilege1,
command=('privilege_mod', [privilege1], dict(description=u'Foo')),
expected=errors.NotFound(
reason=u'%s: privilege not found' % privilege1),
),
dict(
desc='Try to delete non-existent %r' % privilege1,
command=('privilege_del', [privilege1], {}),
expected=errors.NotFound(
reason=u'%s: privilege not found' % privilege1),
),
dict(
desc='Search for non-existent %r' % privilege1,
command=('privilege_find', [privilege1], {}),
expected=dict(
count=0,
truncated=False,
summary=u'0 privileges matched',
result=[],
),
),
dict(
desc='Create %r' % permission1,
command=(
'permission_add', [permission1], dict(
type=u'user',
ipapermright=[u'add', u'delete'],
)
),
expected=dict(
value=permission1,
summary=u'Added permission "%s"' % permission1,
result=dict(
dn=permission1_dn,
cn=[permission1],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'add', u'delete'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
dict(
desc='Create %r' % privilege1,
command=('privilege_add', [privilege1],
dict(description=u'privilege desc. 1')
),
expected=dict(
value=privilege1,
summary=u'Added privilege "%s"' % privilege1,
result=dict(
dn=privilege1_dn,
cn=[privilege1],
description=[u'privilege desc. 1'],
objectclass=objectclasses.privilege,
),
),
),
dict(
desc='Add permission %r to privilege %r' % (permission1, privilege1),
command=('privilege_add_permission', [privilege1],
dict(permission=permission1)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
permission=[],
),
),
result={
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
'memberof_permission': [permission1],
}
),
),
dict(
desc='Retrieve %r' % privilege1,
command=('privilege_show', [privilege1], {}),
expected=dict(
value=privilege1,
summary=None,
result={
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
'memberof_permission': [permission1],
},
),
),
dict(
desc='Search for %r with members' % privilege1,
command=('privilege_find', [privilege1], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 privilege matched',
result=[
{
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
'memberof_permission': [permission1],
},
],
),
),
dict(
desc='Search for %r' % privilege1,
command=('privilege_find', [privilege1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 privilege matched',
result=[
{
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
},
],
),
),
dict(
desc='Search for %r with members' % privilege1,
command=('privilege_find', [privilege1], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 privilege matched',
result=[
{
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
'memberof_permission': [permission1],
},
],
),
),
dict(
desc='Search for %r' % privilege1,
command=('privilege_find', [privilege1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 privilege matched',
result=[
{
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
},
],
),
),
dict(
desc='Create %r' % permission2,
command=(
'permission_add', [permission2], dict(
type=u'user',
ipapermright=u'write',
)
),
expected=dict(
value=permission2,
summary=u'Added permission "%s"' % permission2,
messages=(
{
'message': ('The permission has write rights but no '
'attributes are set.'),
'code': 13032,
'type': 'warning',
'name': 'MissingTargetAttributesinPermission',
'data': {
'right': 'write',
}
},
),
result=dict(
dn=permission2_dn,
cn=[permission2],
objectclass=objectclasses.permission,
type=[u'user'],
ipapermright=[u'write'],
ipapermbindruletype=[u'permission'],
ipapermissiontype=[u'SYSTEM', u'V2'],
ipapermlocation=[users_dn],
),
),
),
dict(
desc='Add permission %r to privilege %r' % (permission2, privilege1),
command=('privilege_add_permission', [privilege1],
dict(permission=permission2)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
permission=[],
),
),
result={
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
'memberof_permission': [permission1, permission2],
}
),
),
dict(
desc='Add permission %r to privilege %r again' % (permission2, privilege1),
command=('privilege_add_permission', [privilege1],
dict(permission=permission2)
),
expected=dict(
completed=0,
failed=dict(
member=dict(
permission=[(u'testperm2', u'This entry is already a member'),],
),
),
result={
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
'memberof_permission': [permission1, permission2],
}
),
),
dict(
desc='Search for %r with memebers' % privilege1,
command=('privilege_find', [privilege1], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 privilege matched',
result=[
{
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
'memberof_permission': [permission1, permission2],
},
],
),
),
dict(
desc='Search for %r' % privilege1,
command=('privilege_find', [privilege1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 privilege matched',
result=[
{
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'privilege desc. 1'],
},
],
),
),
dict(
desc='Update %r' % privilege1,
command=(
'privilege_mod', [privilege1], dict(description=u'New desc 1')
),
expected=dict(
value=privilege1,
summary=u'Modified privilege "%s"' % privilege1,
result=dict(
cn=[privilege1],
description=[u'New desc 1'],
memberof_permission=[permission1, permission2],
),
),
),
dict(
desc='Remove permission from %r' % privilege1,
command=('privilege_remove_permission', [privilege1],
dict(permission=permission1),
),
expected=dict(
completed=1,
failed=dict(
member=dict(
permission=[],
),
),
result={
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'New desc 1'],
'memberof_permission': [permission2],
}
),
),
dict(
desc='Remove permission from %r again' % privilege1,
command=('privilege_remove_permission', [privilege1],
dict(permission=permission1),
),
expected=dict(
completed=0,
failed=dict(
member=dict(
permission=[(u'testperm', u'This entry is not a member'),],
),
),
result={
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'New desc 1'],
'memberof_permission': [permission2],
}
),
),
dict(
desc='Add zero permissions to %r' % privilege1,
command=('privilege_add_permission', [privilege1],
dict(permission=None),
),
expected=dict(
completed=0,
failed=dict(
member=dict(
permission=[],
),
),
result={
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'New desc 1'],
'memberof_permission': [permission2],
}
),
),
dict(
desc='Remove zero permissions from %r' % privilege1,
command=('privilege_remove_permission', [privilege1],
dict(permission=None),
),
expected=dict(
completed=0,
failed=dict(
member=dict(
permission=[],
),
),
result={
'dn': privilege1_dn,
'cn': [privilege1],
'description': [u'New desc 1'],
'memberof_permission': [permission2],
}
),
),
dict(
desc='Delete %r' % privilege1,
command=('privilege_del', [privilege1], {}),
expected=dict(
result=dict(failed=[]),
value=[privilege1],
summary=u'Deleted privilege "%s"' % privilege1,
)
),
]
| 15,095
|
Python
|
.py
| 424
| 20.205189
| 88
| 0.43431
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,471
|
test_krbtpolicy.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_krbtpolicy.py
|
# Authors:
# Rob Crittenden <rcritten@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 kerberos ticket policy
"""
from ipalib import api, errors
from ipatests.test_xmlrpc.xmlrpc_test import Declarative
from ipapython.dn import DN
from ipatests.test_xmlrpc.test_user_plugin import get_user_result
import pytest
user1 = u'tuser1'
invalid_values = [(u'abc123', 'must be an integer'),
(u'2147483648', 'can be at most 2147483647'),
(u'0', 'must be at least 1'),
(u'-1', 'must be at least 1')]
parameters = [('krbauthindmaxrenewableage_radius', 'radius_maxrenew'),
('krbauthindmaxticketlife_radius', 'radius_maxlife'),
('krbauthindmaxrenewableage_pkinit', 'pkinit_maxrenew'),
('krbauthindmaxticketlife_pkinit', 'pkinit_maxlife'),
('krbauthindmaxrenewableage_otp', 'otp_maxrenew'),
('krbauthindmaxticketlife_otp', 'otp_maxlife'),
('krbauthindmaxrenewableage_hardened', 'hardened_maxrenew'),
('krbauthindmaxticketlife_hardened', 'hardened_maxlife'),
('krbauthindmaxrenewableage_idp', 'idp_maxrenew'),
('krbauthindmaxticketlife_idp', 'idp_maxlife'),
('krbauthindmaxrenewableage_passkey', 'passkey_maxrenew'),
('krbauthindmaxticketlife_passkey', 'passkey_maxlife'),
]
def create_dict(desc, param, param_name, value, error):
cmd_args = dict()
cmd_args[param] = value
if value != u'abc123':
return dict(desc=desc, command=('krbtpolicy_mod', [user1], cmd_args),
expected=errors.ValidationError(name=param_name,
error=error))
else:
return dict(desc=desc, command=('krbtpolicy_mod', [user1], cmd_args),
expected=errors.ConversionError(name=param_name,
error=error))
@pytest.mark.tier1
class test_krbtpolicy(Declarative):
cleanup_commands = [
('user_del', [user1], {}),
('krbtpolicy_reset', [], {}),
]
tests = [
dict(
desc='Reset global policy',
command=(
'krbtpolicy_reset', [], {}
),
expected=dict(
value=None,
summary=None,
result=dict(
krbmaxticketlife=[u'86400'],
krbmaxrenewableage=[u'604800'],
),
),
),
dict(
desc='Show global policy',
command=(
'krbtpolicy_show', [], {}
),
expected=dict(
value=None,
summary=None,
result=dict(
dn=DN(('cn',api.env.domain),('cn','kerberos'),
api.env.basedn),
krbmaxticketlife=[u'86400'],
krbmaxrenewableage=[u'604800'],
),
),
),
dict(
desc='Update global policy',
command=(
'krbtpolicy_mod', [], dict(krbmaxticketlife=3600)
),
expected=dict(
value=None,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbmaxrenewableage=[u'604800'],
),
),
),
dict(
desc='Create %r' % user1,
command=(
'user_add', [user1], dict(givenname=u'Test', sn=u'User1')
),
expected=dict(
value=user1,
summary=u'Added user "%s"' % user1,
result=get_user_result(user1, u'Test', u'User1', 'add'),
),
),
dict(
desc='Update user ticket policy',
command=(
'krbtpolicy_mod', [user1], dict(krbmaxticketlife=3600)
),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
),
),
),
dict(
desc='Update user ticket policy for auth indicator pkinit',
command=('krbtpolicy_mod', [user1],
dict(krbauthindmaxticketlife_pkinit=3800)),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbauthindmaxticketlife_pkinit=[u'3800'],
),
),
),
dict(
desc='Update user ticket policy for auth indicator otp',
command=('krbtpolicy_mod', [user1],
dict(krbauthindmaxticketlife_otp=3700)),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbauthindmaxticketlife_pkinit=[u'3800'],
krbauthindmaxticketlife_otp=[u'3700'],
),
),
),
dict(
desc='Update user ticket policy for auth indicator radius',
command=('krbtpolicy_mod', [user1],
dict(krbauthindmaxticketlife_radius=1)),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbauthindmaxticketlife_otp=[u'3700'],
krbauthindmaxticketlife_pkinit=[u'3800'],
krbauthindmaxticketlife_radius=[u'1'],
),
),
),
dict(
desc='Update user ticket policy for auth indicator hardened',
command=('krbtpolicy_mod', [user1],
dict(krbauthindmaxticketlife_hardened=2147483647)),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbauthindmaxticketlife_otp=[u'3700'],
krbauthindmaxticketlife_pkinit=[u'3800'],
krbauthindmaxticketlife_radius=[u'1'],
krbauthindmaxticketlife_hardened=[u'2147483647'],
),
),
),
dict(
desc='Update maxrenew user ticket policy for '
'auth indicator hardened',
command=('krbtpolicy_mod', [user1],
dict(krbauthindmaxrenewableage_hardened=2147483647)),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbauthindmaxticketlife_otp=[u'3700'],
krbauthindmaxticketlife_pkinit=[u'3800'],
krbauthindmaxticketlife_radius=[u'1'],
krbauthindmaxticketlife_hardened=[u'2147483647'],
krbauthindmaxrenewableage_hardened=[u'2147483647'],
),
),
),
dict(
desc='Update maxrenew user ticket policy for '
'auth indicator otp',
command=('krbtpolicy_mod', [user1],
dict(krbauthindmaxrenewableage_otp=3700)),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbauthindmaxticketlife_otp=[u'3700'],
krbauthindmaxticketlife_pkinit=[u'3800'],
krbauthindmaxticketlife_radius=[u'1'],
krbauthindmaxticketlife_hardened=[u'2147483647'],
krbauthindmaxrenewableage_hardened=[u'2147483647'],
krbauthindmaxrenewableage_otp=[u'3700'],
),
),
),
dict(
desc='Update maxrenew user ticket policy for '
'auth indicator radius',
command=('krbtpolicy_mod', [user1],
dict(krbauthindmaxrenewableage_radius=1)),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbauthindmaxticketlife_otp=[u'3700'],
krbauthindmaxticketlife_pkinit=[u'3800'],
krbauthindmaxticketlife_radius=[u'1'],
krbauthindmaxticketlife_hardened=[u'2147483647'],
krbauthindmaxrenewableage_hardened=[u'2147483647'],
krbauthindmaxrenewableage_otp=[u'3700'],
krbauthindmaxrenewableage_radius=[u'1'],
),
),
),
dict(
desc='Update maxrenew user ticket policy for '
'auth indicator pkinit',
command=('krbtpolicy_mod', [user1],
dict(krbauthindmaxrenewableage_pkinit=3800)),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbauthindmaxticketlife_otp=[u'3700'],
krbauthindmaxticketlife_pkinit=[u'3800'],
krbauthindmaxticketlife_radius=[u'1'],
krbauthindmaxticketlife_hardened=[u'2147483647'],
krbauthindmaxrenewableage_hardened=[u'2147483647'],
krbauthindmaxrenewableage_otp=[u'3700'],
krbauthindmaxrenewableage_radius=[u'1'],
krbauthindmaxrenewableage_pkinit=[u'3800'],
),
),
),
dict(
desc='Update maxrenew user ticket policy for '
'auth indicator idp',
command=('krbtpolicy_mod', [user1],
dict(krbauthindmaxrenewableage_idp=3900)),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbauthindmaxticketlife_otp=[u'3700'],
krbauthindmaxticketlife_pkinit=[u'3800'],
krbauthindmaxticketlife_radius=[u'1'],
krbauthindmaxticketlife_hardened=[u'2147483647'],
krbauthindmaxrenewableage_hardened=[u'2147483647'],
krbauthindmaxrenewableage_otp=[u'3700'],
krbauthindmaxrenewableage_radius=[u'1'],
krbauthindmaxrenewableage_pkinit=[u'3800'],
krbauthindmaxrenewableage_idp=[u'3900'],
),
),
),
dict(
desc='Update maxlife user ticket policy for '
'auth indicator idp',
command=('krbtpolicy_mod', [user1],
dict(krbauthindmaxticketlife_idp=3900)),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbauthindmaxticketlife_otp=[u'3700'],
krbauthindmaxticketlife_pkinit=[u'3800'],
krbauthindmaxticketlife_radius=[u'1'],
krbauthindmaxticketlife_hardened=[u'2147483647'],
krbauthindmaxrenewableage_hardened=[u'2147483647'],
krbauthindmaxrenewableage_otp=[u'3700'],
krbauthindmaxrenewableage_radius=[u'1'],
krbauthindmaxrenewableage_pkinit=[u'3800'],
krbauthindmaxrenewableage_idp=[u'3900'],
krbauthindmaxticketlife_idp=[u'3900'],
),
),
),
dict(
desc='Update maxrenew user ticket policy for '
'auth indicator passkey',
command=('krbtpolicy_mod', [user1],
dict(krbauthindmaxrenewableage_passkey=4000)),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbauthindmaxticketlife_otp=[u'3700'],
krbauthindmaxticketlife_pkinit=[u'3800'],
krbauthindmaxticketlife_radius=[u'1'],
krbauthindmaxticketlife_hardened=[u'2147483647'],
krbauthindmaxrenewableage_hardened=[u'2147483647'],
krbauthindmaxrenewableage_otp=[u'3700'],
krbauthindmaxrenewableage_radius=[u'1'],
krbauthindmaxrenewableage_pkinit=[u'3800'],
krbauthindmaxrenewableage_idp=[u'3900'],
krbauthindmaxticketlife_idp=[u'3900'],
krbauthindmaxrenewableage_passkey=[u'4000'],
),
),
),
dict(
desc='Update maxlife user ticket policy for '
'auth indicator passkey',
command=('krbtpolicy_mod', [user1],
dict(krbauthindmaxticketlife_passkey=4100)),
expected=dict(
value=user1,
summary=None,
result=dict(
krbmaxticketlife=[u'3600'],
krbauthindmaxticketlife_otp=[u'3700'],
krbauthindmaxticketlife_pkinit=[u'3800'],
krbauthindmaxticketlife_radius=[u'1'],
krbauthindmaxticketlife_hardened=[u'2147483647'],
krbauthindmaxrenewableage_hardened=[u'2147483647'],
krbauthindmaxrenewableage_otp=[u'3700'],
krbauthindmaxrenewableage_radius=[u'1'],
krbauthindmaxrenewableage_pkinit=[u'3800'],
krbauthindmaxrenewableage_idp=[u'3900'],
krbauthindmaxticketlife_idp=[u'3900'],
krbauthindmaxrenewableage_passkey=[u'4000'],
krbauthindmaxticketlife_passkey=[u'4100'],
),
),
),
dict(
desc='Try updating other user attribute',
command=(
'krbtpolicy_mod', [user1], dict(setattr=u'givenname=Pete')
),
expected=errors.ObjectclassViolation(
info='these attributes are not allowed: givenname'),
),
]
for (value, error) in invalid_values:
for (param, param_name) in parameters:
tests.append(create_dict(desc='Try updating invalid {0} with {1}'.
format(param_name, value),
param=param, param_name=param_name,
value=value, error=error))
| 15,628
|
Python
|
.py
| 375
| 26.368
| 78
| 0.51343
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,472
|
test_delegation_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_delegation_plugin.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 the `ipaserver/plugins/delegation.py` module.
"""
from ipalib import api, errors
from ipatests.test_xmlrpc.xmlrpc_test import Declarative
from ipapython.dn import DN
import pytest
delegation1 = u'testdelegation'
member1 = u'admins'
@pytest.mark.tier1
class test_delegation(Declarative):
cleanup_commands = [
('delegation_del', [delegation1], {}),
]
tests = [
dict(
desc='Try to retrieve non-existent %r' % delegation1,
command=('delegation_show', [delegation1], {}),
expected=errors.NotFound(
reason=u'ACI with name "%s" not found' % delegation1),
),
dict(
desc='Try to update non-existent %r' % delegation1,
command=('delegation_mod', [delegation1], dict(group=u'admins')),
expected=errors.NotFound(
reason=u'ACI with name "%s" not found' % delegation1),
),
dict(
desc='Try to delete non-existent %r' % delegation1,
command=('delegation_del', [delegation1], {}),
expected=errors.NotFound(
reason=u'ACI with name "%s" not found' % delegation1),
),
dict(
desc='Search for non-existent %r' % delegation1,
command=('delegation_find', [delegation1], {}),
expected=dict(
count=0,
truncated=False,
summary=u'0 delegations matched',
result=[],
),
),
dict(
desc='Try to create %r for non-existing member group' % delegation1,
command=(
'delegation_add', [delegation1], dict(
attrs=u'street,c,l,st,postalCode',
permissions=u'write',
group=u'editors',
memberof=u'nonexisting',
),
),
expected=errors.NotFound(reason=u'nonexisting: group not found'),
),
# Note that we add postalCode but expect postalcode. This tests
# the attrs normalizer.
dict(
desc='Create %r' % delegation1,
command=(
'delegation_add', [delegation1], dict(
attrs=[u'street', u'c', u'l', u'st', u'postalCode'],
permissions=u'write',
group=u'editors',
memberof=u'admins',
)
),
expected=dict(
value=delegation1,
summary=u'Added delegation "%s"' % delegation1,
result=dict(
attrs=[u'street', u'c', u'l', u'st', u'postalcode'],
permissions=[u'write'],
aciname=delegation1,
group=u'editors',
memberof=member1,
),
),
),
dict(
desc='Try to create duplicate %r' % delegation1,
command=(
'delegation_add', [delegation1], dict(
attrs=[u'street', u'c', u'l', u'st', u'postalCode'],
permissions=u'write',
group=u'editors',
memberof=u'admins',
),
),
expected=errors.DuplicateEntry(),
),
dict(
desc='Retrieve %r' % delegation1,
command=('delegation_show', [delegation1], {}),
expected=dict(
value=delegation1,
summary=None,
result={
'attrs': [u'street', u'c', u'l', u'st', u'postalcode'],
'permissions': [u'write'],
'aciname': delegation1,
'group': u'editors',
'memberof': member1,
},
),
),
dict(
desc='Retrieve %r with --raw' % delegation1,
command=('delegation_show', [delegation1], {'raw' : True}),
expected=dict(
value=delegation1,
summary=None,
result={
'aci': u'(targetattr = "street || c || l || st || postalcode")(targetfilter = "(memberOf=%s)")(version 3.0;acl "delegation:testdelegation";allow (write) groupdn = "ldap:///%s";)' % \
(DN(('cn', 'admins'), ('cn', 'groups'), ('cn', 'accounts'), api.env.basedn),
DN(('cn', 'editors'), ('cn', 'groups'), ('cn', 'accounts'), api.env.basedn))
},
),
),
dict(
desc='Search for %r' % delegation1,
command=('delegation_find', [delegation1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 delegation matched',
result=[
{
'attrs': [u'street', u'c', u'l', u'st', u'postalcode'],
'permissions': [u'write'],
'aciname': delegation1,
'group': u'editors',
'memberof': member1,
},
],
),
),
dict(
desc='Search for %r using --group filter' % delegation1,
command=('delegation_find', [delegation1], {'group': u'editors'}),
expected=dict(
count=1,
truncated=False,
summary=u'1 delegation matched',
result=[
{
'attrs': [u'street', u'c', u'l', u'st', u'postalcode'],
'permissions': [u'write'],
'aciname': delegation1,
'group': u'editors',
'memberof': member1,
},
],
),
),
dict(
desc='Search for %r using --membergroup filter' % delegation1,
command=('delegation_find', [delegation1], {'memberof': member1}),
expected=dict(
count=1,
truncated=False,
summary=u'1 delegation matched',
result=[
{
'attrs': [u'street', u'c', u'l', u'st', u'postalcode'],
'permissions': [u'write'],
'aciname': delegation1,
'group': u'editors',
'memberof': member1,
},
],
),
),
dict(
desc='Search for %r with --pkey-only' % delegation1,
command=('delegation_find', [delegation1], {'pkey_only' : True}),
expected=dict(
count=1,
truncated=False,
summary=u'1 delegation matched',
result=[
{
'aciname': delegation1,
},
],
),
),
dict(
desc='Search for %r with --raw' % delegation1,
command=('delegation_find', [delegation1], {'raw' : True}),
expected=dict(
count=1,
truncated=False,
summary=u'1 delegation matched',
result=[
{
'aci': u'(targetattr = "street || c || l || st || postalcode")(targetfilter = "(memberOf=%s)")(version 3.0;acl "delegation:testdelegation";allow (write) groupdn = "ldap:///%s";)' % \
(DN(('cn', 'admins'), ('cn', 'groups'), ('cn', 'accounts'), api.env.basedn),
DN(('cn', 'editors'), ('cn', 'groups'), ('cn', 'accounts'), api.env.basedn)),
},
],
),
),
dict(
desc='Update %r' % delegation1,
command=(
'delegation_mod', [delegation1], dict(permissions=u'read')
),
expected=dict(
value=delegation1,
summary=u'Modified delegation "%s"' % delegation1,
result=dict(
attrs=[u'street', u'c', u'l', u'st', u'postalcode'],
permissions=[u'read'],
aciname=delegation1,
group=u'editors',
memberof=member1,
),
),
),
dict(
desc='Retrieve %r to verify update' % delegation1,
command=('delegation_show', [delegation1], {}),
expected=dict(
value=delegation1,
summary=None,
result={
'attrs': [u'street', u'c', u'l', u'st', u'postalcode'],
'permissions': [u'read'],
'aciname': delegation1,
'group': u'editors',
'memberof': member1,
},
),
),
dict(
desc='Delete %r' % delegation1,
command=('delegation_del', [delegation1], {}),
expected=dict(
result=True,
value=delegation1,
summary=u'Deleted delegation "%s"' % delegation1,
)
),
dict(
desc='Create %r with duplicate attrs & perms' % delegation1,
command=(
'delegation_add', [delegation1], dict(
attrs=[u'street', u'street'],
permissions=[u'write', u'write'],
group=u'editors',
memberof=u'admins',
)
),
expected=dict(
value=delegation1,
summary=u'Added delegation "%s"' % delegation1,
result=dict(
attrs=[u'street'],
permissions=[u'write'],
aciname=delegation1,
group=u'editors',
memberof=member1,
),
),
),
dict(
desc='Delete %r' % delegation1,
command=('delegation_del', [delegation1], {}),
expected=dict(
result=True,
value=delegation1,
summary=u'Deleted delegation "%s"' % delegation1,
)
),
]
| 11,117
|
Python
|
.py
| 294
| 23.465986
| 202
| 0.458306
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,473
|
test_pwpolicy_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_pwpolicy_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Pavel Zuna <pzuna@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 the `ipaserver/plugins/pwpolicy.py` module.
"""
import pytest
from ipalib import api
from ipalib import errors
from ipalib.parameters import Int
from ipapython.dn import DN
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import (XMLRPC_test, assert_attr_equal,
Declarative)
def pwpolicy_cmd(
cmd, minlife, maxlife, cospriority=None,
pwpolicy_group=None):
"""Helper method to add or modify the password policy
:param cmd: Either pwpolicy_add or pwpolicy_mod
:param minlife: The minimum amount of time (in hours) that must pass
between two password change operations.
:param maxlife: The maximum amount of time(in days) that must pass
between two password change operations.
:param cospriority: priority
:param pwpolicy_group: password policy group
"""
if cmd == 'pwpolicy_add':
if 0 <= minlife <= 24:
entry = api.Command[cmd](pwpolicy_group,
cospriority=cospriority,
krbminpwdlife=minlife,
krbmaxpwdlife=maxlife)['result']
assert_attr_equal(entry, 'krbminpwdlife', str(minlife))
elif minlife < 0:
with pytest.raises(errors.ValidationError) as e:
entry = api.Command[cmd](pwpolicy_group,
cospriority=cospriority,
krbminpwdlife=minlife,
krbmaxpwdlife=maxlife)['result']
assert "invalid 'minlife': must be at least 0" in str(e)
else:
with pytest.raises(errors.ValidationError) as e:
entry = api.Command[cmd](pwpolicy_group,
cospriority=cospriority,
krbminpwdlife=minlife,
krbmaxpwdlife=maxlife)['result']
assert ("Maximum password life must be equal to "
"or greater than the minimum.") in str(e)
else:
if 0 <= minlife <= 24:
entry = api.Command[cmd](krbminpwdlife=minlife,
krbmaxpwdlife=maxlife)['result']
assert_attr_equal(entry, 'krbminpwdlife', str(minlife))
elif minlife < 0:
with pytest.raises(errors.ValidationError) as e:
entry = api.Command[cmd](krbminpwdlife=minlife,
krbmaxpwdlife=maxlife)['result']
assert "invalid 'minlife': must be at least 0" in str(e)
else:
with pytest.raises(errors.ValidationError) as e:
entry = api.Command[cmd](krbminpwdlife=minlife,
krbmaxpwdlife=maxlife)['result']
assert ("Maximum password life must be equal to "
"or greater than the minimum.") in str(e)
@pytest.mark.tier1
class test_pwpolicy(XMLRPC_test):
"""
Test the `pwpolicy` plugin.
"""
group = u'testgroup12'
group2 = u'testgroup22'
group3 = u'testgroup32'
user = u'testuser12'
kw = {'cospriority': 1, 'krbminpwdlife': 30, 'krbmaxpwdlife': 40,
'krbpwdhistorylength': 5, 'krbpwdminlength': 6}
kw2 = {'cospriority': 2, 'krbminpwdlife': 40, 'krbmaxpwdlife': 60,
'krbpwdhistorylength': 8, 'krbpwdminlength': 9}
kw3 = {'cospriority': 10, 'krbminpwdlife': 50, 'krbmaxpwdlife': 30,
'krbpwdhistorylength': 3, 'krbpwdminlength': 4}
global_policy = u'global_policy'
def test_1_pwpolicy_add(self):
"""
Test adding a per-group policy using the `xmlrpc.pwpolicy_add` method.
"""
# First set up a group and user that will use this policy
self.failsafe_add(
api.Object.group, self.group, description=u'pwpolicy test group',
)
self.failsafe_add(
api.Object.user, self.user, givenname=u'Test', sn=u'User'
)
api.Command.group_add_member(self.group, user=self.user)
entry = api.Command['pwpolicy_add'](self.group, **self.kw)['result']
assert_attr_equal(entry, 'krbminpwdlife', '30')
assert_attr_equal(entry, 'krbmaxpwdlife', '40')
assert_attr_equal(entry, 'krbpwdhistorylength', '5')
assert_attr_equal(entry, 'krbpwdminlength', '6')
assert_attr_equal(entry, 'cospriority', '1')
def test_2_pwpolicy_add(self):
"""
Add a policy with a already used priority.
The priority validation is done first, so it's OK that the group
is the same here.
"""
try:
api.Command['pwpolicy_add'](self.group, **self.kw)
except errors.ValidationError:
pass
else:
assert False
def test_3_pwpolicy_add(self):
"""
Add a policy that already exists.
"""
try:
# cospriority needs to be unique
self.kw['cospriority'] = 3
api.Command['pwpolicy_add'](self.group, **self.kw)
except errors.DuplicateEntry:
pass
else:
assert False
def test_4_pwpolicy_add(self):
"""
Test adding another per-group policy using the
`xmlrpc.pwpolicy_add` method.
"""
self.failsafe_add(
api.Object.group,
self.group2,
description=u'pwpolicy test group 2'
)
entry = api.Command['pwpolicy_add'](self.group2, **self.kw2)['result']
assert_attr_equal(entry, 'krbminpwdlife', '40')
assert_attr_equal(entry, 'krbmaxpwdlife', '60')
assert_attr_equal(entry, 'krbpwdhistorylength', '8')
assert_attr_equal(entry, 'krbpwdminlength', '9')
assert_attr_equal(entry, 'cospriority', '2')
def test_5_pwpolicy_add(self):
"""
Add a pwpolicy for a non-existent group
"""
try:
api.Command['pwpolicy_add'](u'nopwpolicy',
cospriority=1,
krbminpwdlife=1)
except errors.NotFound:
pass
else:
assert False
def test_6_pwpolicy_show(self):
"""
Test the `xmlrpc.pwpolicy_show` method with global policy.
"""
entry = api.Command['pwpolicy_show']()['result']
# Note that this assumes an unchanged global policy
assert_attr_equal(entry, 'krbminpwdlife', '1')
assert_attr_equal(entry, 'krbmaxpwdlife', '90')
assert_attr_equal(entry, 'krbpwdhistorylength', '0')
assert_attr_equal(entry, 'krbpwdminlength', '8')
def test_7_pwpolicy_show(self):
"""
Test the `xmlrpc.pwpolicy_show` method.
"""
entry = api.Command['pwpolicy_show'](self.group)['result']
assert_attr_equal(entry, 'krbminpwdlife', '30')
assert_attr_equal(entry, 'krbmaxpwdlife', '40')
assert_attr_equal(entry, 'krbpwdhistorylength', '5')
assert_attr_equal(entry, 'krbpwdminlength', '6')
assert_attr_equal(entry, 'cospriority', '1')
def test_8_pwpolicy_mod(self):
"""
Test the `xmlrpc.pwpolicy_mod` method for global policy.
"""
entry = api.Command['pwpolicy_mod'](krbminpwdlife=50)['result']
assert_attr_equal(entry, 'krbminpwdlife', '50')
# Great, now change it back
entry = api.Command['pwpolicy_mod'](krbminpwdlife=1)['result']
assert_attr_equal(entry, 'krbminpwdlife', '1')
def test_9_pwpolicy_mod(self):
"""
Test the `xmlrpc.pwpolicy_mod` method.
"""
entry = api.Command['pwpolicy_mod'](self.group,
krbminpwdlife=50)['result']
assert_attr_equal(entry, 'krbminpwdlife', '50')
# Test upper bound
entry = api.Command['pwpolicy_mod'](
self.group, passwordgracelimit=Int.MAXINT)['result']
assert_attr_equal(entry, 'passwordgracelimit', str(Int.MAXINT))
# Test bad values
for value in (Int.MAXINT + 1, -2):
with pytest.raises(errors.ValidationError):
entry = api.Command['pwpolicy_mod'](
self.group, passwordgracelimit=value)['result']
def test_maxlife_pwpolicy(self):
"""Check maxlife error message where minlife > maxlife specified
When minlife > maxlife specified on commandline, it says:
"ipa: ERROR: invalid 'maxlife': Maximum password life must be
greater than minimum."
But when minlife == maxlife specfied, It works.
This test check that error message says what exactly it does.
related: https://pagure.io/freeipa/issue/9038
"""
# test pwpolicy_mod
# create a test group
test_group101 = 'testgroup101'
test_group102 = 'testgroup102'
self.failsafe_add(
api.Object.group,
test_group101,
description=u'pwpolicy test group',
)
self.failsafe_add(
api.Object.group,
test_group102,
description=u'pwpolicy test group',
)
# when minlife(specified in hours) == maxlife(specified in days)
pwpolicy_cmd('pwpolicy_mod', 24, 1)
pwpolicy_cmd('pwpolicy_add', 24, 1, 5, test_group101)
# when minlife(specified in hours) < maxlife(specified in days)
pwpolicy_cmd('pwpolicy_mod', 20, 1)
pwpolicy_cmd('pwpolicy_add', 20, 1, 6, test_group102)
# when minlife(specified in hours) > maxlife(specified in days)
pwpolicy_cmd('pwpolicy_mod', 25, 1)
pwpolicy_cmd('pwpolicy_add', 25, 1, 7, test_group101)
# when minlife is -1
pwpolicy_cmd('pwpolicy_mod', -1, 1)
pwpolicy_cmd('pwpolicy_add', -1, 1, 8, test_group101)
# delete test group
api.Command['group_del'](test_group101)
api.Command['group_del'](test_group102)
def test_a_pwpolicy_managed(self):
"""
Test adding password policy to a managed group.
"""
try:
api.Command['pwpolicy_add'](
self.user, krbminpwdlife=50, cospriority=2)
except errors.ManagedPolicyError:
pass
else:
assert False
def test_b_pwpolicy_add(self):
"""
Test adding a third per-group policy using the
`xmlrpc.pwpolicy_add` method.
"""
self.failsafe_add(
api.Object.group, self.group3, description=u'pwpolicy test group 3'
)
entry = api.Command['pwpolicy_add'](self.group3, **self.kw3)['result']
assert_attr_equal(entry, 'krbminpwdlife', '50')
assert_attr_equal(entry, 'krbmaxpwdlife', '30')
assert_attr_equal(entry, 'krbpwdhistorylength', '3')
assert_attr_equal(entry, 'krbpwdminlength', '4')
assert_attr_equal(entry, 'cospriority', '10')
def test_c_pwpolicy_find(self):
"""Test that password policies are sorted and reported properly"""
result = api.Command['pwpolicy_find']()['result']
assert len(result) == 4
# Test that policies are sorted in numerical order
assert result[0]['cn'] == (self.group,)
assert result[1]['cn'] == (self.group2,)
assert result[2]['cn'] == (self.group3,)
assert result[3]['cn'] == ('global_policy',)
# Test that returned values match the arguments
# Only test the second and third results; the first one was modified
for entry, expected in (result[1], self.kw2), (result[2], self.kw3):
for name, value in expected.items():
assert_attr_equal(entry, name, str(value))
def test_c_pwpolicy_find_pkey_only(self):
"""Test that password policies are sorted properly with --pkey-only"""
result = api.Command['pwpolicy_find'](pkey_only=True)['result']
assert len(result) == 4
assert result[0]['cn'] == (self.group,)
assert result[1]['cn'] == (self.group2,)
assert result[2]['cn'] == (self.group3,)
assert result[3]['cn'] == ('global_policy',)
def test_d_pwpolicy_show(self):
"""Test that deleting a group removes its pwpolicy"""
api.Command['group_del'](self.group3)
with pytest.raises(errors.NotFound):
api.Command['pwpolicy_show'](self.group3)
def test_e_pwpolicy_del(self):
"""
Test the `xmlrpc.pwpolicy_del` method.
"""
api.Command['pwpolicy_del'](self.group)
# Verify that it is gone
try:
api.Command['pwpolicy_show'](self.group)
except errors.NotFound:
pass
else:
assert False
# Verify that global policy cannot be deleted
try:
api.Command['pwpolicy_del'](self.global_policy)
except errors.ValidationError:
pass
else:
assert False
try:
api.Command['pwpolicy_show'](self.global_policy)
except errors.NotFound:
assert False
# Remove the groups we created
api.Command['group_del'](self.group)
api.Command['group_del'](self.group2)
# Remove the user we created
api.Command['user_del'](self.user)
@pytest.mark.tier1
class test_pwpolicy_mod_cospriority(Declarative):
"""Tests for cospriority modifications"""
cleanup_commands = [
('pwpolicy_del', [u'ipausers'], {}),
]
tests = [
dict(
desc='Create a password policy',
command=('pwpolicy_add', [u'ipausers'], dict(
krbmaxpwdlife=90,
krbminpwdlife=1,
krbpwdhistorylength=10,
krbpwdmindiffchars=3,
krbpwdminlength=8,
cospriority=10,
)),
expected=dict(
result=dict(
cn=[u'ipausers'],
cospriority=[u'10'],
dn=DN('cn=ipausers', ('cn', api.env.realm),
'cn=kerberos', api.env.basedn),
krbmaxpwdlife=[u'90'],
krbminpwdlife=[u'1'],
krbpwdhistorylength=[u'10'],
krbpwdmindiffchars=[u'3'],
krbpwdminlength=[u'8'],
passwordgracelimit=[u'-1'],
objectclass=objectclasses.pwpolicy,
),
summary=None,
value=u'ipausers',
),
),
dict(
# https://fedorahosted.org/freeipa/ticket/4309
desc="Try no-op modification of password policy's cospriority",
command=('pwpolicy_mod', [u'ipausers'], dict(
cospriority=10,
)),
expected=errors.EmptyModlist(),
),
dict(
desc="Modify the password policy's cospriority",
command=('pwpolicy_mod', [u'ipausers'], dict(
cospriority=20,
)),
expected=dict(
result=dict(
cn=[u'ipausers'],
cospriority=[u'20'],
krbmaxpwdlife=[u'90'],
krbminpwdlife=[u'1'],
krbpwdhistorylength=[u'10'],
krbpwdmindiffchars=[u'3'],
krbpwdminlength=[u'8'],
passwordgracelimit=[u'-1'],
),
summary=None,
value=u'ipausers',
),
),
]
| 16,526
|
Python
|
.py
| 393
| 30.765903
| 79
| 0.574812
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,474
|
__init__.py
|
freeipa_freeipa/ipatests/test_xmlrpc/__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 `xmlrpc` package.
"""
import ipatests.util
ipatests.util.check_ipaclient_unittests()
ipatests.util.check_no_ipaapi() # also ignore in make fasttest
| 972
|
Python
|
.py
| 24
| 39.375
| 71
| 0.777778
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,475
|
test_sudocmdgroup_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_sudocmdgroup_plugin.py
|
# Authors:
# Jr Aquino <jr.aquino@citrixonline.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 the `ipaserver/plugins/sudocmdgroup.py` module.
"""
from ipalib import errors
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, raises_exact
from ipatests.test_xmlrpc.tracker.sudocmd_plugin import SudoCmdTracker
from ipatests.test_xmlrpc.tracker.sudocmdgroup_plugin import (
SudoCmdGroupTracker
)
import pytest
@pytest.fixture(scope='class')
def sudocmd1(request, xmlrpc_setup):
tracker = SudoCmdTracker(command=u'/usr/bin/sudotestcmd1',
description=u'Test sudo command 1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def sudocmd2(request, xmlrpc_setup):
tracker = SudoCmdTracker(command=u'/usr/bin/sudoTestCmd1',
description=u'Test sudo command 2')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def sudocmd_plus(request, xmlrpc_setup):
tracker = SudoCmdTracker(command=u'/bin/ls -l /lost+found/*',
description=u'Test sudo command 3')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def sudocmdgroup1(request, xmlrpc_setup):
tracker = SudoCmdGroupTracker(u'testsudocmdgroup1', u'Test desc1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def sudocmdgroup2(request, xmlrpc_setup):
tracker = SudoCmdGroupTracker(u'testsudocmdgroup2', u'Test desc2')
return tracker.make_fixture(request)
@pytest.mark.tier1
class TestSudoCmdGroupNonexistent(XMLRPC_test):
def test_retrieve_nonexistent(self, sudocmdgroup1, sudocmdgroup2):
""" Try to retrieve non-existent sudocmdgroups """
sudocmdgroup1.ensure_missing()
command = sudocmdgroup1.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: sudo command group not found' %
sudocmdgroup1.cn)):
command()
sudocmdgroup2.ensure_missing()
command = sudocmdgroup2.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: sudo command group not found' %
sudocmdgroup2.cn)):
command()
def test_update_nonexistent(self, sudocmdgroup1, sudocmdgroup2):
""" Try to update non-existent sudocmdgroups """
sudocmdgroup1.ensure_missing()
command = sudocmdgroup1.make_update_command(dict(description=u'Foo'))
with raises_exact(errors.NotFound(
reason=u'%s: sudo command group not found' %
sudocmdgroup1.cn)):
command()
sudocmdgroup2.ensure_missing()
command = sudocmdgroup2.make_update_command(dict(description=u'Foo2'))
with raises_exact(errors.NotFound(
reason=u'%s: sudo command group not found' %
sudocmdgroup2.cn)):
command()
def test_delete_nonexistent(self, sudocmdgroup1, sudocmdgroup2):
""" Try to delete non-existent sudocmdgroups """
sudocmdgroup1.ensure_missing()
command = sudocmdgroup1.make_delete_command()
with raises_exact(errors.NotFound(
reason=u'%s: sudo command group not found' %
sudocmdgroup1.cn)):
command()
sudocmdgroup2.ensure_missing()
command = sudocmdgroup2.make_delete_command()
with raises_exact(errors.NotFound(
reason=u'%s: sudo command group not found' %
sudocmdgroup2.cn)):
command()
@pytest.mark.tier1
class TestSudoCmdGroupSCRUD(XMLRPC_test):
def test_create_sudocmds_and_verify(self, sudocmd1, sudocmd2):
""" Create sudocmd and sudocmd with camelcase'd command
and verify the managed sudo command sudocmds were created """
sudocmd1.ensure_exists()
sudocmd2.ensure_exists()
sudocmd1.retrieve()
sudocmd2.retrieve()
def test_create(self, sudocmdgroup1):
""" Create sudocmdgroup """
sudocmdgroup1.create()
def test_create_duplicate(self, sudocmdgroup1):
""" Try to create duplicate sudocmdgroup """
sudocmdgroup1.ensure_exists()
command = sudocmdgroup1.make_create_command()
with raises_exact(errors.DuplicateEntry(
message=u'sudo command group ' +
u'with name "%s" already exists' % sudocmdgroup1.cn)):
command()
def test_retrieve(self, sudocmdgroup1):
""" Retrieve sudocmdgroup """
sudocmdgroup1.ensure_exists()
sudocmdgroup1.retrieve()
def test_update(self, sudocmdgroup1):
""" Update sudocmdgroup and retrieve to verify update """
sudocmdgroup1.ensure_exists()
sudocmdgroup1.update(dict(description=u'New desc 1'))
sudocmdgroup1.retrieve()
def test_search(self, sudocmdgroup1):
""" Search for sudocmdgroup """
sudocmdgroup1.ensure_exists()
sudocmdgroup1.find()
def test_search_all(self, sudocmdgroup1):
""" Search for sudocmdgroup """
sudocmdgroup1.ensure_exists()
sudocmdgroup1.find(all=True)
def test_create_another(self, sudocmdgroup2):
""" Create a second sudocmdgroup """
sudocmdgroup2.create()
def test_search_for_both(self, sudocmdgroup1, sudocmdgroup2):
""" Search for all sudocmdgroups, find two """
sudocmdgroup1.ensure_exists()
sudocmdgroup2.ensure_exists()
sudocmdgroup1.find(all=True)
@pytest.mark.tier1
class TestSudoCmdGroupMembers(XMLRPC_test):
def test_add_sudocmd_to_sudocmdgroup(self, sudocmd1, sudocmdgroup1):
""" Add member sudocmd to sudocmdgroup """
sudocmdgroup1.ensure_exists()
sudocmd1.ensure_exists()
sudocmdgroup1.add_member(dict(sudocmd=sudocmd1.cmd))
def test_retrieve_sudocmd_show_membership(self, sudocmd1, sudocmdgroup1):
""" Retrieve sudocmd to show membership """
sudocmd1.ensure_exists()
sudocmd1.attrs.update(memberof_sudocmdgroup=[sudocmdgroup1.cn])
sudocmd1.retrieve()
def test_add_nonexistent_member_to_sudocmdgroup(self, sudocmdgroup1):
""" Try to add non-existent member to sudocmdgroup """
options = dict(sudocmd=u'notfound')
sudocmdgroup1.ensure_exists()
command = sudocmdgroup1.make_add_member_command(options)
result = command()
sudocmdgroup1.check_add_member_negative(result, options)
def test_add_member_sudocmd_to_sudocmdgroup(self, sudocmdgroup1, sudocmd2):
""" Add member sudocmdgroup to sudocmdgroup """
sudocmdgroup1.ensure_exists()
sudocmd2.ensure_exists()
sudocmdgroup1.add_member(dict(sudocmd=sudocmd2.cmd))
def test_remove_member_sudocmd_from_sudocmdgroup(self, sudocmdgroup1,
sudocmd1):
""" Remove member sudocmd from sudocmdgroup """
sudocmdgroup1.ensure_exists()
sudocmdgroup1.remove_member(dict(sudocmd=sudocmd1.cmd))
def test_remove_nonexistent_member_from_sudocmdgroup(self, sudocmdgroup1):
""" Try to remove non-existent member from sudocmdgroup """
options = dict(sudocmd=u'notfound')
sudocmdgroup1.ensure_exists()
command = sudocmdgroup1.make_remove_member_command(options)
result = command()
sudocmdgroup1.check_remove_member_negative(result, options)
def test_special_member_sudocmd_with_sudocmdgroup(self, sudocmdgroup1,
sudocmd_plus):
""" Test add and remove sudocmd with special
characters as sudocmdgroup member """
sudocmdgroup1.ensure_exists()
sudocmd_plus.ensure_exists()
sudocmdgroup1.add_member(dict(sudocmd=sudocmd_plus.cmd))
sudocmdgroup1.remove_member(dict(sudocmd=sudocmd_plus.cmd))
| 8,586
|
Python
|
.py
| 184
| 38.326087
| 79
| 0.681807
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,476
|
test_stageuser_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_stageuser_plugin.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
"""
Test the `ipaserver/plugins/stageuser.py` module.
"""
import pytest
import six
from collections import OrderedDict
from ipalib import api, errors
from ipalib.constants import ERRMSG_GROUPUSER_NAME
from ipaplatform.constants import constants as platformconstants
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, raises_exact
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
from ipatests.test_xmlrpc.tracker.group_plugin import GroupTracker
from ipatests.test_xmlrpc.tracker.stageuser_plugin import StageUserTracker
try:
from ipaserver.plugins.ldap2 import ldap2
except ImportError:
have_ldap2 = False
else:
have_ldap2 = True
if six.PY3:
unicode = str
validuser1 = u'tuser1'
validuser2 = u'tuser2'
uid = u'123'
gid = u'456'
invalidrealm1 = u'suser1@NOTFOUND.ORG'
invalidrealm2 = u'suser1@BAD@NOTFOUND.ORG'
nonexistentidp = 'IdPDoesNotExist'
invaliduser1 = u'+tuser1'
invaliduser2 = u'tuser1234567890123456789012345678901234567890'
invaliduser3 = u'1234'
sshpubkey = (u'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDGAX3xAeLeaJggwTqMjxNwa6X'
'HBUAikXPGMzEpVrlLDCZtv00djsFTBi38PkgxBJVkgRWMrcBsr/35lq7P6w8KGI'
'wA8GI48Z0qBS2NBMJ2u9WQ2hjLN6GdMlo77O0uJY3251p12pCVIS/bHRSq8kHO2'
'No8g7KA9fGGcagPfQH+ee3t7HUkpbQkFTmbPPN++r3V8oVUk5LxbryB3UIIVzNm'
'cSIn3JrXynlvui4MixvrtX6zx+O/bBo68o8/eZD26QrahVbA09fivrn/4h3TM01'
'9Eu/c2jOdckfU3cHUV/3Tno5d6JicibyaoDDK7S/yjdn5jhaz8MSEayQvFkZkiF'
'0L public key test')
sshpubkeyfp = (u'SHA256:cStA9o5TRSARbeketEOooMUMSWRSsArIAXloBZ4vNsE '
'public key test (ssh-rsa)')
options_def = OrderedDict([
('full name', {u'cn': u'name'}),
('initials', {u'initials': u'in'}),
('display name', {u'displayname': u'display'}),
('home directory', {u'homedirectory': u'/home/homedir'}),
('GECOS', {u'gecos': u'gecos'}),
('shell', {u'loginshell': platformconstants.DEFAULT_SHELL}),
('email address', {u'mail': u'email@email.email'}),
('job title', {u'title': u'newbie'}),
('kerberos principal', {
u'krbprincipalname': u'kerberos@%s' % api.env.realm}),
('uppercase kerberos principal', {
u'krbprincipalname': u'KERBEROS@%s' % api.env.realm}),
('street address', {u'street': u'first street'}),
('city', {u'l': u'prague'}),
('state', {u'st': u'czech'}),
('zip code', {u'postalcode': u'12345'}),
('telephone number', {u'telephonenumber': u'123456789'}),
('fax number', {u'facsimiletelephonenumber': u'123456789'}),
('mobile tel. number', {u'mobile': u'123456789'}),
('pager number', {u'pager': u'123456789'}),
('organizational unit', {u'ou': u'engineering'}),
('car license', {u'carlicense': u'abc1234'}),
('SSH key', {u'ipasshpubkey': sshpubkey}),
('manager', {u'manager': u'auser1'}),
('user ID number', {u'uidnumber': uid}),
('group ID number', {u'gidnumber': gid}),
('UID and GID numbers', {u'uidnumber': uid, u'gidnumber': gid}),
('password', {u'userpassword': u'Secret123'}),
('random password', {u'random': True}),
])
options_ok = list(options_def.values())
options_ids = list(options_def.keys())
@pytest.fixture(scope='class')
def stageduser(request, xmlrpc_setup):
tracker = StageUserTracker(name=u'suser1', givenname=u'staged', sn=u'user')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def stageduser_min(request, xmlrpc_setup):
tracker = StageUserTracker(givenname=u'stagedmin', sn=u'usermin')
return tracker.make_fixture(request)
@pytest.fixture(scope='class', params=options_ok, ids=options_ids)
def stageduser2(request, xmlrpc_setup):
tracker = StageUserTracker(u'suser2', u'staged', u'user', **request.param)
return tracker.make_fixture_activate(request)
@pytest.fixture(scope='class')
def user_activated(request, xmlrpc_setup):
tracker = UserTracker(u'suser2', u'staged', u'user')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def stageduser3(request, xmlrpc_setup):
tracker = StageUserTracker(name=u'suser3', givenname=u'staged', sn=u'user')
return tracker.make_fixture_activate(request)
@pytest.fixture(scope='class')
def stageduser_notposix(request, xmlrpc_setup):
tracker = StageUserTracker(u'notposix', u'notposix', u'notposix')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def stageduser_customattr(request, xmlrpc_setup):
tracker = StageUserTracker(u'customattr', u'customattr', u'customattr',
setattr=u'businesscategory=BusinessCat')
tracker.track_create()
tracker.attrs.update(
businesscategory=[u'BusinessCat']
)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user(request, xmlrpc_setup):
tracker = UserTracker(u'auser1', u'active', u'user')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user2(request, xmlrpc_setup):
tracker = UserTracker(u'suser3', u'staged', u'user')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user3(request, xmlrpc_setup):
tracker = UserTracker(u'auser2', u'active', u'user')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user6(request, xmlrpc_setup):
tracker = UserTracker(u'suser2', u'staged', u'user')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user7(request, xmlrpc_setup):
tracker = UserTracker(u'puser1', u'preserved', u'user')
return tracker.make_fixture_restore(request)
@pytest.mark.tier1
class TestNonexistentStagedUser(XMLRPC_test):
def test_retrieve_nonexistent(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: stage user not found' % stageduser.uid)):
command()
def test_delete_nonexistent(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_delete_command()
with raises_exact(errors.NotFound(
reason=u'%s: stage user not found' % stageduser.uid)):
command()
def test_update_nonexistent(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_update_command(
updates=dict(givenname=u'changed'))
with raises_exact(errors.NotFound(
reason=u'%s: stage user not found' % stageduser.uid)):
command()
def test_find_nonexistent(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_find_command(uid=stageduser.uid)
result = command()
stageduser.check_find_nomatch(result)
def test_activate_nonexistent(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_activate_command()
with raises_exact(errors.NotFound(
reason=u'%s: stage user not found' % stageduser.uid)):
command()
@pytest.mark.tier1
class TestStagedUser(XMLRPC_test):
def test_create_with_min_values(self, stageduser_min):
""" Create user with uid not specified """
stageduser_min.ensure_missing()
command = stageduser_min.make_create_command()
command()
def test_create_duplicate(self, stageduser):
stageduser.ensure_exists()
command = stageduser.make_create_command()
with raises_exact(errors.DuplicateEntry(
message=u'stage user with name "%s" already exists' %
stageduser.uid)):
command()
def test_activate(self, stageduser3, user2):
stageduser3.ensure_exists()
user2.ensure_missing()
user2 = UserTracker(
stageduser3.uid, stageduser3.givenname, stageduser3.sn)
user2.create_from_staged(stageduser3)
command = stageduser3.make_activate_command()
result = command()
user2.check_activate(result)
command = stageduser3.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: stage user not found' % stageduser3.uid)):
command()
user2.delete()
def test_show_stageduser(self, stageduser):
stageduser.retrieve()
def test_showall_stageduser(self, stageduser):
stageduser.retrieve(all=True)
def test_create_with_attr(self, stageduser2, user, user_activated):
""" Tests creating a user with various valid attributes listed
in 'options_ok' list"""
# create staged user with specified parameters
user.ensure_exists() # necessary for manager test
stageduser2.ensure_missing()
command = stageduser2.make_create_command()
result = command()
stageduser2.track_create()
stageduser2.check_create(result)
# activate user, verify that specified values were preserved
# after activation
user_activated.ensure_missing()
user_activated = UserTracker(
stageduser2.uid, stageduser2.givenname,
stageduser2.sn, **stageduser2.kwargs)
user_activated.create_from_staged(stageduser2)
command = stageduser2.make_activate_command()
result = command()
user_activated.check_activate(result)
# verify the staged user does not exist after activation
command = stageduser2.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: stage user not found' % stageduser2.uid)):
command()
user_activated.delete()
def test_delete_stageduser(self, stageduser):
stageduser.delete()
def test_find_stageduser(self, stageduser):
stageduser.ensure_exists()
stageduser.find()
def test_findall_stageduser(self, stageduser):
stageduser.find(all=True)
def test_update_stageduser(self, stageduser):
stageduser.update(updates=dict(givenname=u'changed',),
expected_updates=dict(givenname=[u'changed'],))
stageduser.retrieve()
def test_update_uid(self, stageduser):
stageduser.update(updates=dict(uidnumber=uid),
expected_updates=dict(uidnumber=[uid]))
stageduser.retrieve()
def test_update_gid(self, stageduser):
stageduser.update(updates=dict(uidnumber=gid),
expected_updates=dict(uidnumber=[gid]))
stageduser.retrieve()
def test_update_uid_gid(self, stageduser):
stageduser.update(updates=dict(uidnumber=uid, gidnumber=gid),
expected_updates=dict(
uidnumber=[uid], gidnumber=[gid]))
stageduser.retrieve()
def test_without_posixaccount(self, stageduser_notposix):
"""Test stageuser-find when the staged user is not a posixaccount.
"""
stageduser_notposix.ensure_missing()
# Directly create the user using ldapmod
# without the posixaccount objectclass
if not have_ldap2:
pytest.skip('server plugin not available')
ldap = ldap2(api)
ldap.connect()
ldap.create(
dn=stageduser_notposix.dn,
objectclass=[u'inetorgperson', u'organizationalperson', u'person'],
uid=stageduser_notposix.uid,
sn=stageduser_notposix.sn,
givenname=stageduser_notposix.givenname,
cn=stageduser_notposix.uid
)
# Check that stageuser-find correctly finds the user
command = stageduser_notposix.make_find_command(
uid=stageduser_notposix.uid)
result = command()
assert result['count'] == 1
def test_create_withuserauthtype(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_create_command(
options={u'ipauserauthtype': u'password'})
command()
@pytest.mark.tier1
class TestCreateInvalidAttributes(XMLRPC_test):
def test_create_invalid_uid(self):
invalid = StageUserTracker(invaliduser1, u'invalid', u'user')
command = invalid.make_create_command()
with raises_exact(errors.ValidationError(
name='login',
error=ERRMSG_GROUPUSER_NAME.format('user'),
)):
command()
def test_create_numeric_only_uid(self):
invalid = StageUserTracker(invaliduser3, u'NumFirst1234',
u'NumSurname1234')
command = invalid.make_create_command()
with raises_exact(errors.ValidationError(
name='login',
error=ERRMSG_GROUPUSER_NAME.format('user'),
)):
command()
def test_create_long_uid(self):
invalid = StageUserTracker(invaliduser2, u'invalid', u'user')
command = invalid.make_create_command()
with raises_exact(errors.ValidationError(
name='login',
error=u"can be at most 32 characters")):
command()
def test_create_uid_string(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_create_command(
options={u'uidnumber': u'text'})
with raises_exact(errors.ConversionError(
message=u'invalid \'uid\': must be an integer')):
command()
def test_create_gid_string(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_create_command(
options={u'gidnumber': u'text'})
with raises_exact(errors.ConversionError(
message=u'invalid \'gidnumber\': must be an integer')):
command()
def test_create_uid_negative(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_create_command(
options={u'uidnumber': u'-123'})
with raises_exact(errors.ValidationError(
message=u'invalid \'uid\': must be at least 1')):
command()
def test_create_gid_negative(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_create_command(
options={u'gidnumber': u'-123'})
with raises_exact(errors.ValidationError(
message=u'invalid \'gidnumber\': must be at least 1')):
command()
def test_create_krbprincipal_bad_realm(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_create_command(
options={u'krbprincipalname': invalidrealm1})
with raises_exact(errors.RealmMismatch(
message=u'The realm for the principal does not match '
'the realm for this IPA server')):
command()
def test_create_krbprincipal_malformed(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_create_command(
options={u'krbprincipalname': invalidrealm2})
with raises_exact(errors.ConversionError(
name='principal', error="Malformed principal: '{}'".format(
invalidrealm2))):
command()
def test_create_invalid_idp(self, stageduser):
stageduser.ensure_missing()
command = stageduser.make_create_command(
options={u'ipaidpconfiglink': nonexistentidp})
with raises_exact(errors.NotFound(
reason="External IdP configuration {} not found".format(
nonexistentidp))):
command()
@pytest.mark.tier1
class TestUpdateInvalidAttributes(XMLRPC_test):
def test_update_uid_string(self, stageduser):
stageduser.ensure_exists()
command = stageduser.make_update_command(
updates={u'uidnumber': u'text'})
with raises_exact(errors.ConversionError(
message=u'invalid \'uid\': must be an integer')):
command()
def test_update_gid_string(self, stageduser):
stageduser.ensure_exists()
command = stageduser.make_update_command(
updates={u'gidnumber': u'text'})
with raises_exact(errors.ConversionError(
message=u'invalid \'gidnumber\': must be an integer')):
command()
def test_update_uid_negative(self, stageduser):
stageduser.ensure_exists()
command = stageduser.make_update_command(
updates={u'uidnumber': u'-123'})
with raises_exact(errors.ValidationError(
message=u'invalid \'uid\': must be at least 1')):
command()
def test_update_gid_negative(self, stageduser):
stageduser.ensure_exists()
command = stageduser.make_update_command(
updates={u'gidnumber': u'-123'})
with raises_exact(errors.ValidationError(
message=u'invalid \'gidnumber\': must be at least 1')):
command()
def test_update_invalididp(self, stageduser):
stageduser.ensure_exists()
command = stageduser.make_update_command(
updates={u'ipaidpconfiglink': nonexistentidp})
with raises_exact(errors.NotFound(
reason="External IdP configuration {} not found".format(
nonexistentidp))):
command()
@pytest.mark.tier1
class TestActive(XMLRPC_test):
def test_delete(self, user):
user.ensure_exists()
user.track_delete()
command = user.make_delete_command()
result = command()
user.check_delete(result)
def test_delete_nopreserve(self, user):
user.ensure_exists()
user.track_delete()
command = user.make_delete_command(no_preserve=True)
result = command()
user.check_delete(result)
def test_delete_preserve_nopreserve(self, user):
user.ensure_exists()
command = user.make_delete_command(no_preserve=True, preserve=True)
with raises_exact(errors.MutuallyExclusiveError(
message=u'preserve and no-preserve cannot be both set')):
command()
def test_delete_preserve(self, user):
user.ensure_exists()
user.track_delete(preserve=True)
command = user.make_delete_command(no_preserve=False, preserve=True)
result = command()
user.check_delete(result)
user.track_delete(preserve=False)
command = user.make_delete_command()
result = command()
user.check_delete(result)
command = user.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: user not found' % user.uid)):
command()
@pytest.mark.tier1
class TestPreserved(XMLRPC_test):
def test_search_preserved_invalid(self, user):
user.make_preserved_user()
command = user.make_find_command(uid=user.uid)
result = command()
user.check_find_nomatch(result)
user.delete()
def test_search_preserved_valid(self, user):
user.make_preserved_user()
command = user.make_find_command(
uid=user.uid, preserved=True, all=False)
result = command()
user.check_find(result, all=False,
expected_override=dict(preserved=True))
user.delete()
def test_search_preserved_valid_all(self, user):
user.make_preserved_user()
command = user.make_find_command(
uid=user.uid, preserved=True, all=True)
result = command()
user.check_find(result, all=True,
expected_override=dict(preserved=True))
user.delete()
def test_retrieve_preserved(self, user):
user.make_preserved_user()
command = user.make_retrieve_command()
result = command()
user.check_retrieve(result)
user.delete()
def test_permanently_delete_preserved_user(self, user):
user.make_preserved_user()
user.delete()
command = user.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: user not found' % user.uid)):
command()
def test_enable_preserved(self, user):
user.make_preserved_user()
command = user.make_enable_command()
with raises_exact(errors.MidairCollision(
message=u'change collided with another change')):
command()
user.delete()
def test_reactivate_preserved(self, user):
user.make_preserved_user()
command = user.make_retrieve_command(all=True)
result = command()
attr_check = {
u'ipauniqueid': result[u'result'][u'ipauniqueid'],
u'uidnumber': result[u'result'][u'uidnumber'],
u'gidnumber': result[u'result'][u'gidnumber']
}
command = user.make_undelete_command()
result = command()
user.check_undel(result)
user.check_attr_preservation(attr_check)
user.delete()
def test_staged_from_preserved(self, user7, stageduser):
user7.make_preserved_user()
stageduser.ensure_missing()
stageduser = StageUserTracker(user7.uid, user7.givenname, user7.sn)
stageduser.create_from_preserved(user7)
command = user7.make_stage_command()
result = command()
stageduser.check_restore_preserved(result)
stageduser.exists = True
command = user7.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: user not found' % stageduser.uid)):
command()
command = stageduser.make_retrieve_command()
result = command()
stageduser.check_retrieve(result)
stageduser.delete()
@pytest.mark.tier1
class TestCustomAttr(XMLRPC_test):
"""Test for pagure ticket 7597
When a staged user is activated, preserved and finally staged again,
the custom attributes are lost.
"""
def test_stageduser_customattr(self, stageduser_customattr):
# Create a staged user with attributes not accessible
# through the options
# --setattr is needed here
command = stageduser_customattr.make_create_command()
result = command()
stageduser_customattr.check_create(result, [u'businesscategory'])
# Activate the staged user
user_customattr = UserTracker(
stageduser_customattr.uid, stageduser_customattr.givenname,
stageduser_customattr.sn)
user_customattr.create_from_staged(stageduser_customattr)
user_customattr.attrs[u'businesscategory'] = [u'BusinessCat']
command = stageduser_customattr.make_activate_command()
result = command()
user_customattr.check_activate(result)
# Check that the user contains businesscategory
command = user_customattr.make_retrieve_command(all=True)
result = command()
assert 'BusinessCat' in result['result'][u'businesscategory']
# delete the user with --preserve
user_customattr.track_delete(preserve=True)
command = user_customattr.make_delete_command(no_preserve=False,
preserve=True)
result = command()
user_customattr.check_delete(result)
# Check that the preserved user contains businesscategory
command = user_customattr.make_retrieve_command(all=True)
result = command()
assert 'BusinessCat' in result['result'][u'businesscategory']
# Move the user from preserved to stage
command = user_customattr.make_stage_command()
result = command()
stageduser_customattr.check_restore_preserved(result)
# Check that the stage user contains businesscategory
command = stageduser_customattr.make_retrieve_command(all=True)
result = command()
assert 'BusinessCat' in result['result'][u'businesscategory']
@pytest.mark.tier1
class TestManagers(XMLRPC_test):
def test_staged_manager(self, user, stageduser):
user.ensure_exists()
stageduser.ensure_exists()
command = user.make_update_command(
updates=dict(manager=stageduser.uid))
with raises_exact(errors.NotFound(
reason=u'manager %s not found' % stageduser.uid)):
command()
user.delete()
stageduser.delete()
def test_preserved_manager(self, user, user3):
user.ensure_exists()
user3.make_preserved_user()
command = user.make_update_command(updates=dict(manager=user3.uid))
with raises_exact(errors.NotFound(
reason=u'manager %s not found' % user3.uid)):
command()
user3.delete()
def test_delete_manager_preserved(self, user, user3):
user3.ensure_exists()
user.update(
updates=dict(manager=user3.uid),
expected_updates=dict(manager=[user3.uid], nsaccountlock=False))
user3.make_preserved_user()
del user.attrs[u'manager']
command = user.make_retrieve_command(all=True)
result = command()
user.check_retrieve(result, all=True)
# verify whether user has a manager attribute
if u'manager' in result['result']:
assert False
@pytest.mark.tier1
class TestDuplicates(XMLRPC_test):
@pytest.fixture
def user(self, request, xmlrpc_setup):
tracker = UserTracker("tuser", "test", "user")
return tracker.make_fixture(request)
@pytest.fixture
def stageduser(self, request, xmlrpc_setup):
tracker = StageUserTracker("tuser", "test", "user")
return tracker.make_fixture(request)
def test_active_same_as_preserved(self, user):
user.make_preserved_user()
command = user.make_create_command()
with raises_exact(errors.DuplicateEntry(
message=u'user with name "%s" already exists' % user.uid)):
command()
def test_staged_same_as_active(self, user, stageduser):
user.create()
stageduser.create() # can be created
command = stageduser.make_activate_command()
with raises_exact(errors.DuplicateEntry(
message=u'active user with name "%s" already exists' %
user.uid)):
command() # cannot be activated
def test_staged_same_as_preserved(self, user, stageduser):
user.make_preserved_user()
stageduser.create() # can be created
command = stageduser.make_activate_command()
with raises_exact(errors.DuplicateEntry(
message=u'This entry already exists')):
command() # cannot be activated
def test_active_same_as_staged(self, user, stageduser):
stageduser.create()
user.create() # can be created
command = stageduser.make_activate_command()
with raises_exact(errors.DuplicateEntry(
message=u'active user with name "%s" already exists' %
user.uid)):
command() # cannot be activated
@pytest.fixture(scope='class')
def group(request, xmlrpc_setup):
tracker = GroupTracker(u'testgroup')
return tracker.make_fixture(request)
@pytest.mark.tier1
class TestGroups(XMLRPC_test):
def test_stageduser_membership(self, stageduser, group):
stageduser.ensure_exists()
group.ensure_exists()
command = group.make_add_member_command(
options={u'user': stageduser.uid})
result = command()
group.check_add_member_negative(result)
def test_remove_preserved_from_group(self, user, group):
user.ensure_exists()
group.ensure_exists()
command = group.add_member(options={u'user': user.uid})
command = group.make_retrieve_command()
result = command()
group.check_retrieve(result)
user.track_delete(preserve=True)
command = user.make_delete_command(no_preserve=False, preserve=True)
result = command()
user.check_delete(result)
command = group.make_retrieve_command()
result = command()
if (u'member_user' in result[u'result'] and
user.uid in result['result']['member_user']):
assert False
user.delete()
group.delete()
def test_preserveduser_membership(self, user, group):
user.make_preserved_user()
group.ensure_exists()
command = group.make_add_member_command(options={u'user': user.uid})
result = command()
group.check_add_member_negative(result)
| 28,543
|
Python
|
.py
| 649
| 35.14792
| 79
| 0.654711
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,477
|
test_certprofile_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_certprofile_plugin.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
"""
Test the `ipalib.plugins.certprofile` module.
"""
import os
import pytest
import six
from ipalib import api, errors
from ipatests.util import prepare_config
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, raises_exact
from ipatests.test_xmlrpc.tracker.certprofile_plugin import CertprofileTracker
if six.PY3:
unicode = str
IPA_CERT_SUBJ_BASE = (
api.Command.config_show()
['result']['ipacertificatesubjectbase'][0]
)
BASE_DIR = os.path.dirname(__file__)
CA_IPA_SERVICE_MODIFIED_TEMPLATE = os.path.join(
BASE_DIR, 'data/caIPAserviceCert_mod.cfg.tmpl')
CA_IPA_SERVICE_MODIFIED_MALFORMED_TEMPLATE = os.path.join(
BASE_DIR, 'data/caIPAserviceCert_mod_mal.cfg.tmpl')
CA_IPA_SERVICE_MALFORMED_TEMPLATE = os.path.join(
BASE_DIR, 'data/caIPAserviceCert_mal.cfg.tmpl')
CA_IPA_SERVICE_XML_TEMPLATE = os.path.join(
BASE_DIR, 'data/caIPAserviceCert.xml.tmpl')
RENAME_ERR_TEMPL = (
u'certprofile {} cannot be deleted/modified: '
'Certificate profiles cannot be renamed')
@pytest.fixture(scope='class')
def default_profile(request, xmlrpc_setup):
name = 'caIPAserviceCert'
desc = u'Standard profile for network services'
tracker = CertprofileTracker(name, store=True, desc=desc)
tracker.track_create()
return tracker
@pytest.fixture(scope='class')
def user_profile(request, xmlrpc_setup):
name = 'caIPAserviceCert_mod'
profile_path = prepare_config(
CA_IPA_SERVICE_MODIFIED_TEMPLATE,
dict(
ipadomain=api.env.domain,
ipacertbase=IPA_CERT_SUBJ_BASE))
tracker = CertprofileTracker(
name, store=True, desc=u'Storing copy of a profile',
profile=profile_path
)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def malformed(request, xmlrpc_setup):
name = u'caIPAserviceCert_mal'
profile_path = prepare_config(
CA_IPA_SERVICE_MALFORMED_TEMPLATE,
dict(
ipadomain=api.env.domain,
ipacertbase=IPA_CERT_SUBJ_BASE))
tracker = CertprofileTracker(name, store=True, desc=u'malformed profile',
profile=profile_path)
# Do not return with finalizer. There should be nothing to delete
return tracker
@pytest.fixture(scope='class')
def xmlprofile(request, xmlrpc_setup):
name = u'caIPAserviceCert_xml'
profile_path = prepare_config(
CA_IPA_SERVICE_XML_TEMPLATE,
dict(
ipadomain=api.env.domain,
ipacertbase=IPA_CERT_SUBJ_BASE))
tracker = CertprofileTracker(name, store=True, desc=u'xml format profile',
profile=profile_path)
return tracker
@pytest.mark.tier0
class TestDefaultProfile(XMLRPC_test):
def test_default_profile_present(self, default_profile):
default_profile.retrieve()
def test_deleting_default_profile(self, default_profile):
with pytest.raises(errors.ValidationError):
default_profile.delete()
def test_try_rename_by_setattr(self, default_profile):
command = default_profile.make_update_command(
updates=dict(setattr=u'cn=bogus'))
errmsg = RENAME_ERR_TEMPL.format(default_profile.name)
with raises_exact(errors.ProtectedEntryError(message=errmsg)):
command()
def test_try_rename_by_rename_option(self, default_profile):
command = default_profile.make_update_command(dict(rename=u'bogus_id'))
with pytest.raises(errors.OptionError):
command()
@pytest.mark.tier1
class TestProfileCRUD(XMLRPC_test):
def test_create_duplicate(self, user_profile):
msg = u'Certificate Profile with name "{}" already exists'
user_profile.ensure_exists()
command = user_profile.make_create_command()
with raises_exact(errors.DuplicateEntry(
message=msg.format(user_profile.name))):
command()
def test_retrieve_simple(self, user_profile):
user_profile.retrieve()
def test_retrieve_all(self, user_profile):
user_profile.retrieve(all=True)
def test_export_profile(self, tmpdir, user_profile):
profile = tmpdir.join('{}.cfg'.format(user_profile.name))
command = user_profile.make_retrieve_command(out=unicode(profile))
command()
content = profile.read()
assert user_profile.name in content
def test_search_simple(self, user_profile):
user_profile.find()
def test_search_all(self, user_profile):
user_profile.find(all=True)
def test_update_store(self, user_profile):
user_profile.update(
dict(
ipacertprofilestoreissued=False
),
expected_updates=dict(
ipacertprofilestoreissued=[False]
)
)
def test_update_description(self, user_profile):
new_desc = u'new description'
user_profile.update(
dict(
description=new_desc
),
expected_updates=dict(
description=[new_desc]
)
)
def test_update_by_malformed_profile(self, user_profile):
profile_path = prepare_config(
CA_IPA_SERVICE_MODIFIED_MALFORMED_TEMPLATE,
dict(
ipadomain=api.env.domain,
ipacertbase=IPA_CERT_SUBJ_BASE))
with open(profile_path, ) as f:
profile_content = f.read()
command = user_profile.make_update_command(
dict(file=unicode(profile_content)))
with pytest.raises(errors.ExecutionError):
command()
def test_try_rename_by_setattr(self, user_profile):
user_profile.ensure_exists()
command = user_profile.make_update_command(
updates=dict(setattr=u'cn=bogus'))
errmsg = RENAME_ERR_TEMPL.format(user_profile.name)
with raises_exact(errors.ProtectedEntryError(message=errmsg)):
command()
def test_delete(self, user_profile):
user_profile.ensure_exists()
user_profile.delete()
def test_try_rename_by_rename_option(self, user_profile):
user_profile.ensure_exists()
command = user_profile.make_update_command(dict(rename=u'bogus_id'))
with pytest.raises(errors.OptionError):
command()
@pytest.mark.tier1
class TestMalformedProfile(XMLRPC_test):
def test_malformed_import(self, malformed):
with pytest.raises(errors.ExecutionError):
malformed.create()
@pytest.mark.tier1
class TestImportFromXML(XMLRPC_test):
def test_import_xml(self, xmlprofile):
with pytest.raises(errors.ExecutionError):
xmlprofile.ensure_exists()
# The initial user_profile configuration does not specify profileId.
# This is fine (it gets derived from the profile-id CLI argument),
# but this case was already tested in TestProfileCRUD.
#
# This test case tests various scenarios where the profileId *is*
# specified in the profile configuration. These are:
#
# - mismatched profileId property (should fail)
# - multiple profileId properties (should fail)
# - one profileId property, matching given ID (should succeed)
#
@pytest.mark.tier1
class TestImportProfileIdHandling(XMLRPC_test):
def test_import_with_mismatched_profile_id(self, user_profile):
command = user_profile.make_create_command(
extra_lines=['profileId=bogus']
)
with pytest.raises(errors.ValidationError):
command()
def test_import_with_multiple_profile_id(self, user_profile):
# correct profile id, but two occurrences
prop = u'profileId={}'.format(user_profile.name)
command = user_profile.make_create_command(extra_lines=[prop, prop])
with pytest.raises(errors.ValidationError):
command()
def test_import_with_correct_profile_id(self, user_profile):
prop = u'profileId={}'.format(user_profile.name)
command = user_profile.make_create_command(extra_lines=[prop])
command()
| 8,129
|
Python
|
.py
| 200
| 33.25
| 79
| 0.681021
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,478
|
test_kerberos_principal_aliases.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_kerberos_principal_aliases.py
|
# coding: utf-8
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
from __future__ import absolute_import
import copy
import ldap
import pytest
from ipalib import errors, api
from ipapython import ipautil
from ipaplatform.paths import paths
from ipatests.util import MockLDAP
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
from ipatests.test_xmlrpc.tracker.host_plugin import HostTracker
from ipatests.test_xmlrpc.tracker.service_plugin import ServiceTracker
from ipatests.test_xmlrpc.tracker.stageuser_plugin import StageUserTracker
from ipatests.test_xmlrpc.mock_trust import (
get_trust_dn, get_trusted_dom_dict,
encode_mockldap_value)
from ipatests.util import unlock_principal_password, change_principal
# Shared values for the mocked trusted domain
TRUSTED_DOMAIN_MOCK = dict(
name=u'trusted.domain.net',
sid=u'S-1-5-21-2997650941-1802118864-3094776726'
)
TRUSTED_DOMAIN_MOCK['dn'] = get_trust_dn(TRUSTED_DOMAIN_MOCK['name'])
TRUSTED_DOMAIN_MOCK['ldif'] = get_trusted_dom_dict(
TRUSTED_DOMAIN_MOCK['name'], TRUSTED_DOMAIN_MOCK['sid']
)
ADD_REMOVE_TEST_DATA = [
u'testuser-alias',
u'testhost-alias',
u'teststageuser-alias',
]
TRACKER_INIT_DATA = [
(UserTracker, (u'krbalias_user', u'krbalias', u'test',), {},),
(HostTracker, (u'testhost-krb',), {},),
(StageUserTracker, (u'krbalias_stageuser', u'krbalias', u'test',), {},),
]
TRACKER_DATA = [
(ADD_REMOVE_TEST_DATA[i],) + TRACKER_INIT_DATA[i]
for i in range(len(TRACKER_INIT_DATA))
]
@pytest.fixture
def trusted_domain():
"""Fixture providing mocked AD trust entries
The fixture yields after creating a mock of AD trust
entries in the directory server. After the test, the entries
are deleted from the directory.
"""
trusted_dom = TRUSTED_DOMAIN_MOCK
# Write the changes
with MockLDAP() as ldap:
ldap.add_entry(trusted_dom['dn'], trusted_dom['ldif'])
yield trusted_dom
ldap.del_entry(trusted_dom['dn'])
@pytest.fixture
def trusted_domain_with_suffix():
"""Fixture providing mocked AD trust entries
The fixture yields after creating a mock of AD trust
entries in the directory server. After the test, the entries
are deleted from the directory.
"""
trusted_dom = copy.deepcopy(TRUSTED_DOMAIN_MOCK)
trusted_dom['ldif']['ipaNTAdditionalSuffixes'] = (
encode_mockldap_value(trusted_dom['name'])
)
# Write the changes
with MockLDAP() as ldap:
ldap.add_entry(trusted_dom['dn'], trusted_dom['ldif'])
yield trusted_dom
ldap.del_entry(trusted_dom['dn'])
@pytest.fixture(scope='function')
def krbalias_user(request):
tracker = UserTracker(u'krbalias_user', u'krbalias', u'test')
return tracker.make_fixture(request)
@pytest.fixture(scope='function')
def krbalias_user_c(request):
tracker = UserTracker(u'krbalias_user_conflict', u'krbalias', u'test')
return tracker.make_fixture(request)
@pytest.fixture
def krb_service_host(request):
tracker = HostTracker(u'krb-srv-host')
return tracker.make_fixture(request)
@pytest.fixture(scope='function')
def krbalias_service(request, krb_service_host):
krb_service_host.ensure_exists()
tracker = ServiceTracker(name=u'SRV1', host_fqdn=krb_service_host.name)
return tracker.make_fixture(request)
@pytest.fixture(scope='function')
def krbalias(request, tracker_cls, tracker_args, tracker_kwargs):
tracker = tracker_cls(*tracker_args, **tracker_kwargs)
return tracker.make_fixture(request)
@pytest.fixture
def ldapservice(request):
tracker = ServiceTracker(
name=u'ldap', host_fqdn=api.env.host, options={'has_keytab': True})
tracker.track_create()
return tracker
class TestKerberosAliasManipulation(XMLRPC_test):
@pytest.mark.parametrize('alias,tracker_cls,tracker_args,tracker_kwargs',
TRACKER_DATA)
def test_add_principal_alias(self, alias, krbalias):
krbalias.ensure_exists()
krbalias.add_principal([alias])
krbalias.retrieve()
@pytest.mark.parametrize('alias,tracker_cls,tracker_args,tracker_kwargs',
TRACKER_DATA)
def test_remove_principal_alias(self, alias, krbalias):
krbalias.ensure_exists()
krbalias.add_principal([alias])
krbalias.remove_principal(alias)
krbalias.retrieve()
def test_add_service_principal_alias(self, krbalias_service):
krbalias_service.ensure_exists()
krbalias_service.add_principal(
[u'SRV2/{}'.format(krbalias_service.host_fqdn)])
krbalias_service.retrieve()
def test_remove_service_principal_alias(self, krbalias_service):
krbalias_service.ensure_exists()
krbalias_service.add_principal(
[u'SRV2/{}'.format(krbalias_service.host_fqdn)])
krbalias_service.retrieve()
krbalias_service.remove_principal(
[u'SRV2/{}'.format(krbalias_service.host_fqdn)])
krbalias_service.retrieve()
def test_adding_alias_adds_canonical_name(self, krbalias_user):
"""Test adding alias on an entry without canonical name"""
krbalias_user.ensure_exists()
user_krb_principal = krbalias_user.attrs['krbprincipalname'][0]
# Delete all values of krbcanonicalname from an LDAP entry
dn = str(krbalias_user.dn)
modlist = [(ldap.MOD_DELETE, 'krbcanonicalname', None)]
with MockLDAP() as ldapconn:
ldapconn.mod_entry(dn, modlist)
# add new user principal alias
krbalias_user.add_principal(u'krbalias_principal_canonical')
# verify that the previous principal name is now krbcanonicalname
cmd = krbalias_user.make_retrieve_command()
new_canonical_name = cmd()['result']['krbcanonicalname'][0]
assert new_canonical_name == user_krb_principal
def test_authenticate_against_aliased_service(self, ldapservice):
alias = u'ldap/{newname}.{host}'.format(
newname='krbalias', host=api.env.host)
ldapservice.add_principal(alias)
rv = ipautil.run([paths.BIN_KVNO, alias],
capture_error=True, raiseonerr=False)
ldapservice.remove_principal(alias)
assert rv.returncode == 0, rv.error_output
def test_authenticate_with_user_alias(self, krbalias_user):
krbalias_user.ensure_exists()
alias = u"{name}-alias".format(name=krbalias_user.name)
krbalias_user.add_principal(alias)
oldpw, newpw = u"Secret1234", u"Secret123"
pwdmod = krbalias_user.make_update_command({'userpassword': oldpw})
pwdmod()
unlock_principal_password(krbalias_user.name, oldpw, newpw)
with change_principal(alias, newpw, canonicalize=True):
api.Command.ping()
class TestKerberosAliasExceptions(XMLRPC_test):
def test_add_user_coliding_with_alias(self, krbalias_user):
krbalias_user.ensure_exists()
user_alias = u'conflicting_name'
krbalias_user.add_principal([user_alias])
conflict_user = UserTracker(user_alias, u'test', u'conflict')
with pytest.raises(errors.DuplicateEntry):
conflict_user.create()
def test_add_alias_to_two_entries(self, krbalias_user, krbalias_user_c):
krbalias_user.ensure_exists()
krbalias_user_c.ensure_exists()
user_alias = u'krbalias-test'
krbalias_user.add_principal([user_alias])
with pytest.raises(errors.DuplicateEntry):
krbalias_user_c.add_principal([user_alias])
def test_remove_alias_matching_canonical_name(self, krbalias_user):
krbalias_user.ensure_exists()
with pytest.raises(errors.ValidationError):
krbalias_user.remove_principal(
krbalias_user.attrs.get('krbcanonicalname'))
def test_enterprise_principal_overlap_with_AD_realm(
self, krbalias_user, trusted_domain):
krbalias_user.ensure_exists()
# Add an alias overlapping the trusted domain realm
with pytest.raises(errors.ValidationError):
krbalias_user.add_principal(
u'{username}\\@{trusted_domain}@{realm}'.format(
username=krbalias_user.name,
trusted_domain=trusted_domain['name'],
realm=api.env.realm
)
)
def test_enterprise_principal_UPN_overlap(
self, krbalias_user, trusted_domain_with_suffix):
krbalias_user.ensure_exists()
# Add an alias overlapping the UPN of a trusted domain
upn_suffix = (
trusted_domain_with_suffix['ldif']['ipaNTAdditionalSuffixes']
).decode('utf-8')
with pytest.raises(errors.ValidationError):
krbalias_user.add_principal(
u'{username}\\@{trusted_domain}@{realm}'.format(
username=krbalias_user.name,
trusted_domain=upn_suffix,
realm=api.env.realm
)
)
def test_enterprise_principal_NETBIOS_overlap(
self, krbalias_user, trusted_domain_with_suffix):
krbalias_user.ensure_exists()
# Add an alias overlapping the NETBIOS name of a trusted domain
netbios_name = (
trusted_domain_with_suffix['ldif']['ipaNTFlatName']
).decode('utf-8')
with pytest.raises(errors.ValidationError):
krbalias_user.add_principal(
u'{username}\\@{trusted_domain}@{realm}'.format(
username=krbalias_user.name,
trusted_domain=netbios_name,
realm=api.env.realm
)
)
| 9,812
|
Python
|
.py
| 222
| 36.337838
| 77
| 0.677738
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,479
|
test_radiusproxy_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_radiusproxy_plugin.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/>.
import six
from ipalib import errors, api, _
from ipapython.dn import DN
from ipatests.test_xmlrpc.xmlrpc_test import Declarative
from ipatests.test_xmlrpc.test_user_plugin import get_user_result
from ipatests.test_xmlrpc import objectclasses
import pytest
if six.PY3:
unicode = str
radius1 = u'testradius'
radius1_fqdn = u'testradius.test'
radius1_dn = DN(('cn=testradius'), ('cn=radiusproxy'), api.env.basedn)
user1 = u'tuser1'
password1 = u'very*secure123'
password1_bytes = password1.encode('ascii')
@pytest.mark.tier1
class test_raduisproxy(Declarative):
cleanup_commands = [
('radiusproxy_del', [radius1], {}),
('user_del', [user1], {}),
]
tests = [
dict(
desc='Try to retrieve non-existent %r' % radius1,
command=('radiusproxy_show', [radius1], {}),
expected=errors.NotFound(
reason=u'%s: RADIUS proxy server not found' % radius1),
),
dict(
desc='Try to update non-existent %r' % radius1,
command=('radiusproxy_mod', [radius1], {}),
expected=errors.NotFound(
reason=_('%s: RADIUS proxy server not found') % radius1),
),
dict(
desc='Try to delete non-existent %r' % radius1,
command=('radiusproxy_del', [radius1], {}),
expected=errors.NotFound(
reason=_('%s: RADIUS proxy server not found') % radius1),
),
dict(
desc='Try to add multiple radius proxy server %r' % radius1,
command=('radiusproxy_add', [radius1],
dict(
ipatokenradiusserver=radius1_fqdn,
addattr=u'ipatokenradiusserver=radius1_fqdn',
ipatokenradiussecret=password1,
),
),
expected=errors.OnlyOneValueAllowed(attr='ipatokenradiusserver')
),
dict(
desc='Create %r' % radius1,
command=('radiusproxy_add', [radius1],
dict(
ipatokenradiusserver=radius1_fqdn,
ipatokenradiussecret=password1,
),
),
expected=dict(
value=radius1,
summary=u'Added RADIUS proxy server "%s"' % radius1,
result=dict(
cn=[radius1],
dn=radius1_dn,
ipatokenradiussecret=[password1_bytes],
ipatokenradiusserver=[radius1_fqdn],
objectclass=objectclasses.radiusproxy,
),
),
),
dict(
desc='Try to create duplicate %r' % radius1,
command=('radiusproxy_add', [radius1],
dict(
ipatokenradiusserver=radius1_fqdn,
ipatokenradiussecret=password1,
),
),
expected=errors.DuplicateEntry(message=_('RADIUS proxy server '
'with name "%s" already exists') % radius1),
),
dict(
desc='Retrieve %r' % radius1,
command=('radiusproxy_show', [radius1], {}),
expected=dict(
value=radius1,
summary=None,
result=dict(
cn=[radius1],
dn=radius1_dn,
ipatokenradiusserver=[radius1_fqdn],
),
),
),
dict(
desc='Retrieve %r with all=True' % radius1,
command=('radiusproxy_show', [radius1], dict(all=True)),
expected=dict(
value=radius1,
summary=None,
result=dict(
cn=[radius1],
dn=radius1_dn,
ipatokenradiussecret=[password1_bytes],
ipatokenradiusserver=[radius1_fqdn],
objectclass=objectclasses.radiusproxy,
),
),
),
] + [
dict(
desc='Set timeout of %s to %s (valid)' % (radius1, num),
command=('radiusproxy_mod', [radius1],
dict(ipatokenradiustimeout=num)),
expected=dict(
value=radius1,
summary=u'Modified RADIUS proxy server "%s"' % radius1,
result=dict(
cn=[radius1],
ipatokenradiusserver=[radius1_fqdn],
ipatokenradiustimeout=[unicode(num)],
),
),
)
for num in (1, 100)
] + [
dict(
desc='Set timeout of %s to 0 (invalid)' % radius1,
command=('radiusproxy_mod', [radius1],
dict(ipatokenradiustimeout=0)),
expected=errors.ValidationError(
name='timeout', error=_('must be at least 1')),
),
dict(
desc='Unset timeout of %s' % radius1,
command=('radiusproxy_mod', [radius1],
dict(ipatokenradiustimeout=None)),
expected=dict(
value=radius1,
summary=u'Modified RADIUS proxy server "%s"' % radius1,
result=dict(
cn=[radius1],
ipatokenradiusserver=[radius1_fqdn],
),
),
),
] + [
dict(
desc='Set retries of %s to %s (valid)' % (radius1, num),
command=('radiusproxy_mod', [radius1],
dict(ipatokenradiusretries=num)),
expected=dict(
value=radius1,
summary=u'Modified RADIUS proxy server "%s"' % radius1,
result=dict(
cn=[radius1],
ipatokenradiusserver=[radius1_fqdn],
ipatokenradiusretries=[unicode(num)],
),
),
)
for num in (0, 4, 10)
] + [
dict(
desc='Set retries of %s to %s (invalid)' % (radius1, num),
command=('radiusproxy_mod', [radius1],
dict(ipatokenradiusretries=num)),
expected=errors.ValidationError(
name='retries', error=reason),
)
for num, reason in ((-1, 'must be at least 0'),
(11, 'can be at most 10'),
(100, 'can be at most 10'))
] + [
dict(
desc='Unset retries of %s' % radius1,
command=('radiusproxy_mod', [radius1],
dict(ipatokenradiusretries=None)),
expected=dict(
value=radius1,
summary=u'Modified RADIUS proxy server "%s"' % radius1,
result=dict(
cn=[radius1],
ipatokenradiusserver=[radius1_fqdn],
),
),
),
] + [
dict(
desc='Set server string of %s to %s (valid)' % (radius1, fqdn),
command=('radiusproxy_mod', [radius1],
dict(ipatokenradiusserver=fqdn)),
expected=dict(
value=radius1,
summary=u'Modified RADIUS proxy server "%s"' % radius1,
result=dict(
cn=[radius1],
ipatokenradiusserver=[fqdn],
),
),
)
for fqdn in (radius1_fqdn + u':12345', radius1_fqdn)
] + [
dict(
desc='Set server string of %s to %s (invalid)' % (radius1, fqdn),
command=('radiusproxy_mod', [radius1],
dict(ipatokenradiusserver=fqdn)),
expected=errors.ValidationError(name='ipatokenradiusserver',
error=error),
)
for fqdn, error in (
(radius1_fqdn + u':0x5a', 'invalid port number'),
(radius1_fqdn + u':1:2:3',
"only letters, numbers, '_', '-' are allowed. DNS label may not "
"start or end with '-'"),
(u'bogus', 'not fully qualified'),
)
] + [
dict(
desc='Try to unset server string of %s' % radius1,
command=('radiusproxy_mod', [radius1],
dict(ipatokenradiusserver=None)),
expected=errors.RequirementError(name='server'),
),
dict(
desc='Set userattr of %s to %s (valid)' % (radius1, u'cn'),
command=('radiusproxy_mod', [radius1],
dict(ipatokenusermapattribute=u'cn')),
expected=dict(
value=radius1,
summary=u'Modified RADIUS proxy server "%s"' % radius1,
result=dict(
cn=[radius1],
ipatokenradiusserver=[radius1_fqdn],
ipatokenusermapattribute=[u'cn'],
),
),
),
dict(
desc='Set userattr of %s to %s (invalid)' % (radius1, u'$%^&*'),
command=('radiusproxy_mod', [radius1],
dict(ipatokenusermapattribute=u'$%^&*')),
expected=errors.ValidationError(name='ipatokenusermapattribute',
error=u'invalid attribute name'),
),
dict(
desc='Unset userattr of %s' % radius1,
command=('radiusproxy_mod', [radius1],
dict(ipatokenusermapattribute=None)),
expected=dict(
value=radius1,
summary=u'Modified RADIUS proxy server "%s"' % radius1,
result=dict(
cn=[radius1],
ipatokenradiusserver=[radius1_fqdn],
),
),
),
dict(
desc='Set desc of %s' % radius1,
command=('radiusproxy_mod', [radius1],
dict(description=u'a virtual radius server')),
expected=dict(
value=radius1,
summary=u'Modified RADIUS proxy server "%s"' % radius1,
result=dict(
cn=[radius1],
ipatokenradiusserver=[radius1_fqdn],
description=[u'a virtual radius server'],
),
),
),
dict(
desc='Unset desc of %s' % radius1,
command=('radiusproxy_mod', [radius1],
dict(description=None)),
expected=dict(
value=radius1,
summary=u'Modified RADIUS proxy server "%s"' % radius1,
result=dict(
cn=[radius1],
ipatokenradiusserver=[radius1_fqdn],
),
),
),
dict(
desc='Create "%s"' % user1,
command=(
'user_add', [user1], dict(givenname=u'Test', sn=u'User1')
),
expected=dict(
value=user1,
summary=u'Added user "%s"' % user1,
result=get_user_result(user1, u'Test', u'User1', 'add'),
),
),
dict(
desc='Set radiusconfiglink of %r' % user1,
command=('user_mod', [user1],
dict(ipatokenradiusconfiglink=radius1,)),
expected=dict(
result=get_user_result(user1, u'Test', u'User1', 'mod',
ipatokenradiusconfiglink=[radius1]),
value=user1,
summary='Modified user "%s"' % user1,
),
),
dict(
desc='Retrieve %r to verify %s is output' % (radius1, user1),
command=('radiusproxy_show', [radius1], {}),
expected=dict(
value=radius1,
summary=None,
result=dict(
cn=[radius1],
dn=radius1_dn,
ipatokenradiusserver=[radius1_fqdn],
),
),
),
dict(
desc='Retrieve %r to verify %s is output' % (user1, radius1),
command=('user_show', [user1], {}),
expected=dict(
value=user1,
summary=None,
result=get_user_result(user1, u'Test', u'User1', 'show',
ipatokenradiusconfiglink=[radius1]),
),
),
dict(
desc='Delete %r' % radius1,
command=('radiusproxy_del', [radius1], {}),
expected=dict(
value=[radius1],
summary=u'Deleted RADIUS proxy server "%s"' % radius1,
result=dict(failed=[]),
),
),
dict(
desc='Retrieve %s to verify link is deleted' % user1,
command=('user_show', [user1], {}),
expected=dict(
value=user1,
summary=None,
result=get_user_result(user1, u'Test', u'User1', 'show'),
),
),
]
| 13,849
|
Python
|
.py
| 368
| 23.923913
| 78
| 0.488985
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,480
|
test_cert_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_cert_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
#
# Copyright (C) 2009,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/>.
"""
Test the `ipaserver/plugins/cert.py` module against a RA.
"""
from __future__ import print_function, absolute_import
import base64
import os
import pytest
import six
from ipalib import api
from ipalib import errors
from ipaplatform.paths import paths
from ipapython.certdb import NSSDatabase
from ipapython.dn import DN
from ipapython.ipautil import run
from ipatests.test_xmlrpc.testcert import subject_base
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
if six.PY3:
unicode = str
# So we can save the cert from issuance and compare it later
cert = None
newcert = None
sn = None
_DOMAIN = api.env.domain
_EXP_CRL_URI = ''.join(['http://ipa-ca.', _DOMAIN, '/ipa/crl/MasterCRL.bin'])
_EXP_OCSP_URI = ''.join(['http://ipa-ca.', _DOMAIN, '/ca/ocsp'])
def is_db_configured():
"""
Raise an exception if we are testing against lite-server and the
developer cert database is configured.
"""
aliasdir = api.env.dot_ipa + os.sep + 'alias' + os.sep + '.pwd'
if (api.env.xmlrpc_uri == u'http://localhost:8888/ipa/xml' and
not os.path.isfile(aliasdir)):
pytest.skip('developer CA not configured in %s' % aliasdir)
# Test setup
#
# This test needs a configured CA behind it in order to work properly
#
# To test against Apache directly then no changes are required. Just be
# sure the xmlrpc_uri in ~/.ipa/default.conf points to Apache.
#
# To test against Dogtag CA in the lite-server:
#
# - Copy the 3 NSS db files from /var/lib/ipa/radb to ~/.ipa/alias
# - Copy /var/lib/ipa/radb/pwdfile.txt to ~/.ipa/alias/.pwd.
# - Change ownership of these files to be readable by you.
#
# The API tested depends on the value of ~/.ipa/default/ra_plugin when
# running as the lite-server.
class BaseCert(XMLRPC_test):
host_fqdn = u'ipatestcert.%s' % api.env.domain
service_princ = u'test/%s@%s' % (host_fqdn, api.env.realm)
certfile = None
nssdb = None
reqfile = None
subject = None
@pytest.fixture(autouse=True, scope="class")
def basecert_setup(self, request, xmlrpc_setup):
if 'cert_request' not in api.Command:
pytest.skip('cert_request not registered')
if 'cert_show' not in api.Command:
pytest.skip('cert_show not registered')
is_db_configured()
@pytest.fixture(autouse=True)
def basecert_fsetup(self, request):
self.nssdb = NSSDatabase()
secdir = self.nssdb.secdir
self.reqfile = os.path.join(secdir, "test.csr")
self.certfile = os.path.join(secdir, "cert.crt")
# Create our temporary NSS database
self.nssdb.create_db()
self.subject = DN(('CN', self.host_fqdn), subject_base())
def fin():
self.nssdb.close()
request.addfinalizer(fin)
def generateCSR(self, subject):
self.nssdb.run_certutil([
"-R", "-s", subject,
"-o", self.reqfile,
"-z", paths.GROUP,
"-a",
])
with open(self.reqfile, "rb") as f:
return f.read().decode('ascii')
@pytest.mark.tier1
class test_cert(BaseCert):
"""
Test the `cert` plugin.
"""
def test_0001_cert_add(self):
"""
Test the `xmlrpc.cert_request` method without --add.
This should fail because the service principal doesn't exist
"""
# First create the host that will use this policy
assert 'result' in api.Command['host_add'](self.host_fqdn, force=True)
csr = self.generateCSR(str(self.subject))
with pytest.raises(errors.NotFound):
api.Command['cert_request'](csr, principal=self.service_princ)
def test_0002_cert_add(self):
"""
Test the `xmlrpc.cert_request` method with --add.
"""
# Our host should exist from previous test
global cert, sn
csr = self.generateCSR(str(self.subject))
res = api.Command['cert_request'](csr, principal=self.service_princ, add=True)['result']
assert DN(res['subject']) == self.subject
assert 'cacn' in res
# save the cert for the service_show/find tests
cert = res['certificate'].encode('ascii')
# save cert's SN for URI test
sn = res['serial_number']
def test_0003_service_show(self):
"""
Verify that service-show has the right certificate using service-show.
"""
res = api.Command['service_show'](self.service_princ)['result']
assert base64.b64encode(res['usercertificate'][0]) == cert
def test_0004_service_find(self):
"""
Verify that service-find has the right certificate using service-find.
"""
# Assume there is only one service
res = api.Command['service_find'](self.service_princ)['result']
assert base64.b64encode(res[0]['usercertificate'][0]) == cert
def test_0005_cert_uris(self):
"""Test URI details and OCSP-URI in certificate.
See https://fedorahosted.org/freeipa/ticket/5881
"""
result = api.Command.cert_show(sn, out=unicode(self.certfile))
with open(self.certfile, "rb") as f:
pem_cert = f.read().decode('ascii')
result = run([paths.OPENSSL, 'x509', '-text'],
stdin=pem_cert, capture_output=True)
assert _EXP_CRL_URI in result.output
assert _EXP_OCSP_URI in result.output
def test_0006_cert_renew(self):
"""
Issue a new certificate for a service
"""
global newcert
csr = self.generateCSR(str(self.subject))
res = api.Command['cert_request'](csr, principal=self.service_princ)['result']
assert DN(res['subject']) == self.subject
# save the cert for the service_show/find tests
newcert = res['certificate'].encode('ascii')
def test_0007_service_show(self):
"""
Verify the new certificate with service-show.
"""
res = api.Command['service_show'](self.service_princ)['result']
# Both the old and the new certs should be listed as certificates now
certs_encoded = (
base64.b64encode(usercert) for usercert in res['usercertificate']
)
assert set(certs_encoded) == set([cert, newcert])
def test_0008_cert_show(self):
"""
Verify that cert-show shows CA of the certificate without --all
"""
res = api.Command['cert_show'](sn)['result']
assert 'cacn' in res
assert 'valid_not_before' in res
assert 'valid_not_after' in res
def test_0009_cert_find(self):
"""
Verify that cert-find shows CA of the certificate without --all
"""
res = api.Command['cert_find'](min_serial_number=sn,
max_serial_number=sn)['result'][0]
assert 'cacn' in res
assert 'valid_not_before' in res
assert 'valid_not_after' in res
def test_00010_san_in_cert(self):
"""
Test if SAN extension is automatically added with default profile.
"""
csr = self.generateCSR(str(self.subject))
res = api.Command[
'cert_request'](csr, principal=self.service_princ)['result']
assert 'san_dnsname' in res
def test_00011_emails_are_valid(self):
"""
Verify the different scenarios when checking if any email addr
from DN or SAN extension does not appear in ldap entry.
"""
from ipaserver.plugins.cert import _emails_are_valid
email_addrs = [u'any@EmAiL.CoM']
result = _emails_are_valid(email_addrs, [u'any@email.com'])
assert result
email_addrs = [u'any@EmAiL.CoM']
result = _emails_are_valid(email_addrs, [u'any@email.com',
u'another@email.com'])
assert result
result = _emails_are_valid([], [u'any@email.com'])
assert result
email_addrs = [u'invalidEmailAddress']
result = _emails_are_valid(email_addrs, [])
assert not result
def test_00012_cert_find_all(self):
"""
Test that cert-find --all returns successfully.
We don't know how many we'll get but there should be at least 10
by default.
"""
res = api.Command['cert_find'](all=True)
assert 'count' in res and res['count'] >= 10
def test_99999_cleanup(self):
"""
Clean up cert test data
"""
# Now clean things up
api.Command['host_del'](self.host_fqdn)
# Verify that the service is gone
res = api.Command['service_find'](self.service_princ)
assert res['count'] == 0
@pytest.mark.tier1
class test_cert_find(XMLRPC_test):
"""
Test the `cert-find` command.
"""
@pytest.fixture(autouse=True, scope="class")
def certfind_setup(self, request, xmlrpc_setup):
if 'cert_find' not in api.Command:
pytest.skip('cert_find not registered')
if api.env.ra_plugin != 'dogtag':
pytest.skip('cert_find for dogtag CA only')
is_db_configured()
short = api.env.host.split('.', maxsplit=1)[0]
def test_0001_find_all_certs(self):
"""
Search for all certificates.
We don't know how many we'll get but there should be at least 10
by default.
"""
res = api.Command['cert_find']()
assert 'count' in res and res['count'] >= 10
def test_0002_find_CA(self):
"""
Search for the CA certificate.
"""
res = api.Command['cert_find'](subject=u'Certificate Authority')
assert 'count' in res and res['count'] == 1
def test_0003_find_OCSP(self):
"""
Search for the OCSP certificate.
"""
res = api.Command['cert_find'](subject=u'OCSP Subsystem')
assert 'count' in res
assert res['count'], "No OSCP certificate found"
def test_0004_find_this_host(self):
"""
Find all certificates for this IPA server
"""
res = api.Command['cert_find'](subject=api.env.host)
assert 'count' in res and res['count'] > 1
def test_0005_find_this_host_exact(self):
"""
Find all certificates for this IPA server (exact)
"""
res = api.Command['cert_find'](subject=api.env.host, exactly=True)
assert 'count' in res and res['count'] > 1
def test_0006_find_this_short_host_exact(self):
"""
Find all certificates for this IPA server short name (exact)
"""
res = api.Command['cert_find'](subject=self.short, exactly=True)
assert 'count' in res and res['count'] == 0
# tests 0007 to 0016 removed
def test_0017_find_by_issuedon(self):
"""
Find all certificates issued since 2008
"""
res = api.Command['cert_find'](issuedon_from=u'2008-01-01',
sizelimit=10)
assert 'count' in res and res['count'] == 10
def test_0018_find_through_issuedon(self):
"""
Find all certificates issued through 2008
"""
res = api.Command['cert_find'](issuedon_to=u'2008-01-01',
sizelimit=10)
assert 'count' in res and res['count'] == 0
def test_0019_find_notvalid_before(self):
"""
Find all certificates valid not before 2008
"""
res = api.Command['cert_find'](validnotbefore_from=u'2008-01-01',
sizelimit=10)
assert 'count' in res and res['count'] == 10
def test_0020_find_notvalid_before(self):
"""
Find all certificates valid not before to 2100
"""
res = api.Command['cert_find'](validnotbefore_to=u'2100-01-01',
sizelimit=10)
assert 'count' in res and res['count'] == 10
def test_0021_find_notvalid_before(self):
"""
Find all certificates valid not before 2100
"""
res = api.Command['cert_find'](validnotbefore_from=u'2100-01-01',
sizelimit=10)
assert 'count' in res and res['count'] == 0
def test_0022_find_notvalid_before(self):
"""
Find all certificates valid not before to 2008
"""
res = api.Command['cert_find'](validnotbefore_to=u'2008-01-01',
sizelimit=10)
assert 'count' in res and res['count'] == 0
def test_0023_find_notvalid_after(self):
"""
Find all certificates valid not after 2008
"""
res = api.Command['cert_find'](validnotafter_from=u'2008-01-01',
sizelimit=10)
assert 'count' in res and res['count'] == 10
def test_0024_find_notvalid_after(self):
"""
Find all certificates valid not after to 2100
"""
res = api.Command['cert_find'](validnotafter_to=u'2100-01-01',
sizelimit=10)
assert 'count' in res and res['count'] == 10
def test_0025_find_notvalid_after(self):
"""
Find all certificates valid not after 2100
"""
res = api.Command['cert_find'](validnotafter_from=u'2100-01-01',
sizelimit=10)
assert 'count' in res and res['count'] == 0
def test_0026_find_notvalid_after(self):
"""
Find all certificates valid not after to 2008
"""
res = api.Command['cert_find'](validnotafter_to=u'2008-01-01',
sizelimit=10)
assert 'count' in res and res['count'] == 0
def test_0027_sizelimit_zero(self):
"""
Search with a sizelimit of 0
"""
count_all = api.Command['cert_find']()['count']
res = api.Command['cert_find'](sizelimit=0)
assert 'count' in res and res['count'] == count_all
def test_0028_find_negative_size(self):
"""
Search with a negative sizelimit
"""
with pytest.raises(errors.ValidationError):
api.Command['cert_find'](sizelimit=-100)
def test_0029_search_for_notfound(self):
"""
Search for a host that isn't there.
"""
res = api.Command['cert_find'](subject=u'notfound')
assert 'count' in res and res['count'] == 0
def test_0030_search_for_testcerts(self):
"""
Search for certs created in other tests
"""
res = api.Command['cert_find'](subject=u'ipatestcert.%s' % api.env.domain)
assert 'count' in res and res['count'] >= 1
def test_0031_search_on_invalid_date(self):
"""
Search using invalid date format
"""
with pytest.raises(errors.ConversionError):
api.Command['cert_find'](issuedon_from=u'xyz')
@pytest.mark.tier1
class test_cert_revocation(BaseCert):
# create CSR, request cert, revoke cert, check cert attributes
def revoke_cert(self, reason):
# add host
assert 'result' in api.Command['host_add'](self.host_fqdn, force=True)
# generate CSR, request certificate, obtain serial number
self.csr = self.generateCSR(str(self.subject))
res = api.Command['cert_request'](self.csr,
principal=self.service_princ,
add=True, all=True)['result']
serial_number = res['serial_number']
# REMOVE_FROM_CRL (8) needs to be on hold to revoke per RFC 5280
if reason == 8:
assert 'result' in api.Command['cert_revoke'](
serial_number, revocation_reason=6)
# revoke created certificate
assert 'result' in api.Command['cert_revoke'](
serial_number, revocation_reason=reason)
# verify that certificate is revoked with correct reason
res2 = api.Command['cert_show'](serial_number, all=True)['result']
if reason == 8:
assert res2['revoked'] is False
else:
assert res2['revoked']
assert res2['revocation_reason'] == reason
# remove host
assert 'result' in api.Command['host_del'](self.host_fqdn)
def test_revoke_with_reason_0(self):
self.revoke_cert(0)
def test_revoke_with_reason_1(self):
self.revoke_cert(1)
def test_revoke_with_reason_2(self):
self.revoke_cert(2)
def test_revoke_with_reason_3(self):
self.revoke_cert(3)
def test_revoke_with_reason_4(self):
self.revoke_cert(4)
def test_revoke_with_reason_5(self):
self.revoke_cert(5)
def test_revoke_with_reason_6(self):
self.revoke_cert(6)
def test_revoke_with_reason_8(self):
self.revoke_cert(8)
def test_revoke_with_reason_9(self):
self.revoke_cert(9)
def test_revoke_with_reason_10(self):
self.revoke_cert(10)
@pytest.mark.tier1
class test_cert_remove_hold(BaseCert):
# create CSR, request cert, revoke cert, remove hold
def test_revoke_and_remove_hold(self):
# add host
assert 'result' in api.Command['host_add'](self.host_fqdn, force=True)
# generate CSR, request certificate, obtain serial number
self.csr = self.generateCSR(str(self.subject))
res = api.Command['cert_request'](self.csr,
principal=self.service_princ,
add=True, all=True)['result']
serial_number = res['serial_number']
# revoke created certificate
assert 'result' in api.Command['cert_revoke'](
serial_number, revocation_reason=6)
# verify that certificate is revoked with correct reason
res2 = api.Command['cert_show'](serial_number, all=True)['result']
assert res2['revoked']
assert res2['revocation_reason'] == 6
# remove hold
res3 = api.Command['cert_remove_hold'](serial_number)['result']
assert res3['unrevoked']
# remove host
assert 'result' in api.Command['host_del'](self.host_fqdn)
def test_remove_hold_nonexistent_cert(self):
# remove hold must print 'Certificate ID xx not found'
with pytest.raises(errors.NotFound,
match=r'Certificate ID 0x.* not found'):
api.Command['cert_remove_hold'](9999)
| 19,222
|
Python
|
.py
| 466
| 32.459227
| 96
| 0.610269
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,481
|
test_group_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_group_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Pavel Zuna <pzuna@redhat.com>
# Filip Skola <fskola@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/plugins/group.py` module.
"""
import pytest
from ipalib import errors
from ipalib.constants import ERRMSG_GROUPUSER_NAME
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import (
fuzzy_digits, fuzzy_uuid, fuzzy_set_ci,
fuzzy_user_or_group_sid,
XMLRPC_test, raises_exact
)
from ipatests.test_xmlrpc.tracker.group_plugin import GroupTracker
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
from ipatests.util import assert_deepequal, get_group_dn
notagroup = u'notagroup'
renamedgroup1 = u'renamedgroup'
invalidgroup1 = u'+tgroup1'
invalidgroup2 = u'1234'
external_sid1 = u'S-1-1-123456-789-1'
@pytest.fixture(scope='class')
def group(request, xmlrpc_setup):
tracker = GroupTracker(name=u'testgroup1', description=u'Test desc1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def group2(request, xmlrpc_setup):
tracker = GroupTracker(name=u'testgroup2', description=u'Test desc2')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def managed_group(request, user):
user.ensure_exists()
tracker = GroupTracker(
name=user.uid, description=u'User private group for %s' % user.uid
)
tracker.exists = True
# Managed group gets created when user is created
tracker.track_create()
# Managed groups don't have a SID
del tracker.attrs['ipantsecurityidentifier']
return tracker
@pytest.fixture(scope='class')
def user(request, xmlrpc_setup):
tracker = UserTracker(name=u'user1', givenname=u'Test', sn=u'User1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user_npg2(request, group):
""" User tracker fixture for testing users with no private group """
tracker = UserTracker(name=u'npguser2', givenname=u'Npguser',
sn=u'Npguser2', noprivate=True, gidnumber=1000)
tracker.track_create()
del tracker.attrs['mepmanagedentry']
tracker.attrs.update(
gidnumber=[u'1000'], description=[], memberof_group=[group.cn],
objectclass=objectclasses.user_base + ['ipantuserattrs']
)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def admins(request, xmlrpc_setup):
# Track the admins group
tracker = GroupTracker(
name=u'admins', description=u'Account administrators group'
)
tracker.exists = True
tracker.track_create()
tracker.attrs.update(member_user=[u'admin'])
return tracker
@pytest.fixture(scope='class')
def trustadmins(request, xmlrpc_setup):
# Track the 'trust admins' group
tracker = GroupTracker(
name=u'trust admins', description=u'Trusts administrators group'
)
tracker.exists = True
tracker.track_create()
tracker.attrs.update(member_user=[u'admin'])
return tracker
@pytest.mark.tier1
class TestGroup(XMLRPC_test):
def test_create(self, group):
""" Create a group """
group.create()
def test_create_duplicate(self, group):
""" Try to create a duplicate group """
group.ensure_exists()
command = group.make_create_command()
with raises_exact(errors.DuplicateEntry(
message=u'group with name "%s" already exists' % group.cn)):
command()
def test_retrieve(self, group):
""" Retrieve a group """
group.retrieve()
def test_update(self, group):
""" Update a group with new description
and perform retrieve command to verify the update """
group.update(dict(description=u'New desc'))
group.retrieve()
def test_rename(self, group):
""" Rename a group and than rename it back """
origname = group.cn
command = group.make_command('group_mod', *[group.cn],
**dict(setattr=u'cn=%s' % renamedgroup1))
result = command()
group.attrs.update(cn=[renamedgroup1])
group.check_update(result)
group.cn = renamedgroup1
command = group.make_command('group_mod', *[group.cn],
**dict(setattr=u'cn=%s' % origname))
result = command()
group.attrs.update(cn=[origname])
group.check_update(result)
group.cn = origname
def test_convert_posix_to_external(self, group):
""" Try to convert a posix group to external """
command = group.make_update_command(dict(external=True))
with raises_exact(errors.PosixGroupViolation(
reason=u"""This is already a posix group and cannot
be converted to external one""")):
command()
def test_add_with_invalid_name(self, group):
""" Try to add group with an invalid name """
command = group.make_command(
'group_add', *[invalidgroup1], **dict(description=u'Test')
)
with raises_exact(errors.ValidationError(
name='group_name',
error=ERRMSG_GROUPUSER_NAME.format('group'))):
command()
def test_create_with_name_starting_with_numeric(self):
"""Successfully create a group with name starting with numeric chars"""
testgroup = GroupTracker(
name=u'1234group',
description=u'Group name starting with numeric chars',
)
testgroup.create()
testgroup.delete()
def test_create_with_numeric_only_groupname(self):
"""Try to create a group with name only contains numeric chars"""
testgroup = GroupTracker(
name=invalidgroup2, description=u'Numeric only group name',
)
with raises_exact(errors.ValidationError(
name='group_name',
error=ERRMSG_GROUPUSER_NAME.format('group'),
)):
testgroup.create()
def test_rename_setattr_to_invalid_groupname(self, group):
""" Try to rename group using an invalid name with settatr cn= """
group.ensure_exists()
command = group.make_update_command(
updates=dict(setattr='cn=%s' % invalidgroup1))
with raises_exact(errors.ValidationError(
name='cn',
error=ERRMSG_GROUPUSER_NAME.format('group'),
)):
command()
def test_rename_to_invalid_groupname(self, group):
""" Try to rename group using an invalid name """
group.ensure_exists()
command = group.make_update_command(
updates=dict(rename=invalidgroup1))
with raises_exact(errors.ValidationError(
name='rename',
error=ERRMSG_GROUPUSER_NAME.format('group'),
)):
command()
def test_rename_setattr_to_numeric_only_groupname(self, group):
""" Try to rename using an invalid numeric only name with setattr"""
group.ensure_exists()
command = group.make_update_command(
updates=dict(setattr='cn=%s' % invalidgroup2))
with raises_exact(errors.ValidationError(
name='cn',
error=ERRMSG_GROUPUSER_NAME.format('group'),
)):
command()
def test_rename_to_numeric_only_groupname(self, group):
""" Try to rename group using an invalid numeric only name """
group.ensure_exists()
command = group.make_update_command(
updates=dict(rename=invalidgroup2))
with raises_exact(errors.ValidationError(
name='rename',
error=ERRMSG_GROUPUSER_NAME.format('group'),
)):
command()
@pytest.mark.tier1
class TestFindGroup(XMLRPC_test):
def test_search(self, group):
""" Search for a group """
group.ensure_exists()
group.find()
def test_search_for_all_groups_with_members(self, group, group2):
""" Search for all groups """
group.ensure_exists()
group2.create()
command = group.make_command('group_find', no_members=False)
result = command()
assert_deepequal(dict(
summary=u'6 groups matched',
count=6,
truncated=False,
result=[
{
'dn': get_group_dn('admins'),
'member_user': [u'admin'],
'gidnumber': [fuzzy_digits],
'cn': [u'admins'],
'description': [u'Account administrators group'],
},
{
'dn': get_group_dn('editors'),
'gidnumber': [fuzzy_digits],
'cn': [u'editors'],
'description':
[u'Limited admins who can edit other users'],
},
{
'dn': get_group_dn('ipausers'),
'cn': [u'ipausers'],
'description': [u'Default group for all users'],
},
{
'dn': get_group_dn(group.cn),
'cn': [group.cn],
'description': [u'Test desc1'],
'gidnumber': [fuzzy_digits],
},
{
'dn': get_group_dn(group2.cn),
'cn': [group2.cn],
'description': [u'Test desc2'],
'gidnumber': [fuzzy_digits],
},
{
'dn': get_group_dn('trust admins'),
'member_user': [u'admin'],
'cn': [u'trust admins'],
'description': [u'Trusts administrators group'],
},
]), result)
def test_search_for_all_groups(self, group, group2):
""" Search for all groups """
group.ensure_exists()
group2.ensure_exists()
command = group.make_command('group_find')
result = command()
assert_deepequal(dict(
summary=u'6 groups matched',
count=6,
truncated=False,
result=[
{
'dn': get_group_dn('admins'),
'gidnumber': [fuzzy_digits],
'cn': [u'admins'],
'description': [u'Account administrators group'],
},
{
'dn': get_group_dn('editors'),
'gidnumber': [fuzzy_digits],
'cn': [u'editors'],
'description':
[u'Limited admins who can edit other users'],
},
{
'dn': get_group_dn('ipausers'),
'cn': [u'ipausers'],
'description': [u'Default group for all users'],
},
{
'dn': get_group_dn(group.cn),
'cn': [group.cn],
'description': [u'Test desc1'],
'gidnumber': [fuzzy_digits],
},
{
'dn': get_group_dn(group2.cn),
'cn': [group2.cn],
'description': [u'Test desc2'],
'gidnumber': [fuzzy_digits],
},
{
'dn': get_group_dn('trust admins'),
'cn': [u'trust admins'],
'description': [u'Trusts administrators group'],
},
]), result)
def test_search_for_all_posix(self, group, group2):
""" Search for all posix groups """
command = group.make_command(
'group_find', **dict(posix=True, all=True)
)
result = command()
assert_deepequal(dict(
summary=u'4 groups matched',
count=4,
truncated=False,
result=[
{
'dn': get_group_dn('admins'),
'member_user': [u'admin'],
'gidnumber': [fuzzy_digits],
'cn': [u'admins'],
'description': [u'Account administrators group'],
'objectclass': fuzzy_set_ci(objectclasses.posixgroup),
'ipauniqueid': [fuzzy_uuid],
'ipantsecurityidentifier': [fuzzy_user_or_group_sid],
},
{
'dn': get_group_dn('editors'),
'gidnumber': [fuzzy_digits],
'cn': [u'editors'],
'description':
[u'Limited admins who can edit other users'],
'objectclass': fuzzy_set_ci(objectclasses.posixgroup),
'ipauniqueid': [fuzzy_uuid],
'ipantsecurityidentifier': [fuzzy_user_or_group_sid],
},
{
'dn': get_group_dn(group.cn),
'cn': [group.cn],
'description': [u'Test desc1'],
'gidnumber': [fuzzy_digits],
'objectclass': fuzzy_set_ci(objectclasses.posixgroup),
'ipauniqueid': [fuzzy_uuid],
'ipantsecurityidentifier': [fuzzy_user_or_group_sid],
},
{
'dn': get_group_dn(group2.cn),
'cn': [group2.cn],
'description': [u'Test desc2'],
'gidnumber': [fuzzy_digits],
'objectclass': fuzzy_set_ci(objectclasses.posixgroup),
'ipauniqueid': [fuzzy_uuid],
'ipantsecurityidentifier': [fuzzy_user_or_group_sid],
},
]), result)
@pytest.mark.tier1
class TestNonexistentGroup(XMLRPC_test):
def test_retrieve_nonexistent(self, group):
""" Try to retrieve a non-existent group """
group.ensure_missing()
command = group.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: group not found' % group.cn)):
command()
def test_update_nonexistent(self, group):
""" Try to update a non-existent group """
group.ensure_missing()
command = group.make_update_command(
updates=dict(description=u'hey'))
with raises_exact(errors.NotFound(
reason=u'%s: group not found' % group.cn)):
command()
def test_delete_nonexistent(self, group):
""" Try to delete a non-existent user """
group.ensure_missing()
command = group.make_delete_command()
with raises_exact(errors.NotFound(
reason=u'%s: group not found' % group.cn)):
command()
def test_rename_nonexistent(self, group):
""" Try to rename a non-existent user """
group.ensure_missing()
command = group.make_update_command(
updates=dict(setattr=u'cn=%s' % renamedgroup1))
with raises_exact(errors.NotFound(
reason=u'%s: group not found' % group.cn)):
command()
@pytest.mark.tier1
class TestNonposixGroup(XMLRPC_test):
def test_create_nonposix_with_gid(self, group):
""" Try to create non-posix group with GID """
command = group.make_create_command(**dict(nonposix=True,
gidnumber=10011))
with raises_exact(errors.ObjectclassViolation(
info=u'attribute "gidNumber" not allowed with --nonposix')):
command()
def test_create_nonposix(self, group):
""" Create a non-posix group """
group.track_create()
command = group.make_create_command(**dict(nonposix=True))
result = command()
del group.attrs['gidnumber']
group.attrs.update(objectclass=objectclasses.group)
group.check_create(result)
def test_create_duplicate_to_nonposix(self, group):
""" Try to create a duplicate non-posix group """
group.ensure_exists()
command = group.make_create_command()
with raises_exact(errors.DuplicateEntry(
message=u'group with name "%s" already exists' % group.cn)):
command()
def test_retrieve_nonposix(self, group):
""" Retrieve a non-posix group """
group.retrieve()
def test_update_nonposix(self, group):
""" Update a non-posix group with new description
and perform retrieve command to verify the update """
group.update(dict(description=u'New desc'))
group.retrieve()
def test_search_for_all_nonposix(self, group):
""" Perform a search for all non-posix groups """
command = group.make_command(
'group_find', **dict(nonposix=True, all=True)
)
result = command()
assert_deepequal(dict(
summary=u'3 groups matched',
count=3,
truncated=False,
result=[
{
'dn': get_group_dn('ipausers'),
'cn': [u'ipausers'],
'description': [u'Default group for all users'],
'objectclass': fuzzy_set_ci(objectclasses.group),
'ipauniqueid': [fuzzy_uuid],
},
{
'dn': get_group_dn(group.cn),
'cn': [group.cn],
'description': [u'New desc'],
'objectclass': fuzzy_set_ci(objectclasses.group),
'ipauniqueid': [fuzzy_uuid],
},
{
'dn': get_group_dn('trust admins'),
'member_user': [u'admin'],
'cn': [u'trust admins'],
'description': [u'Trusts administrators group'],
'objectclass': fuzzy_set_ci(objectclasses.group),
'ipauniqueid': [fuzzy_uuid],
},
],
), result)
def test_upgrade_nonposix_to_posix_and_external(self, group):
""" Update non-posix group to promote it to posix group & external"""
command = group.make_update_command(dict(posix=True, external=True))
with raises_exact(errors.MutuallyExclusiveError(
reason=u"An external group cannot be POSIX")):
command()
def test_upgrade_nonposix_with_gid_and_external(self, group):
""" Update non-posix group to promote it to posix group & external"""
command = group.make_update_command(dict(gidnumber=12345,
external=True))
with raises_exact(errors.MutuallyExclusiveError(
reason=u"An external group cannot be POSIX")):
command()
def test_upgrade_nonposix_to_posix(self, group):
""" Update non-posix group to promote it to posix group """
group.attrs.update(gidnumber=[fuzzy_digits])
group.update(dict(posix=True), dict(posix=None))
group.retrieve()
def test_search_for_all_nonposix_with_criteria(self, group):
""" Search for all non-posix groups with additional
criteria filter """
command = group.make_command(
'group_find', *[u'users'], **dict(nonposix=True, all=True)
)
result = command()
assert_deepequal(dict(
summary=u'1 group matched',
count=1,
truncated=False,
result=[
{
'dn': get_group_dn('ipausers'),
'cn': [u'ipausers'],
'description': [u'Default group for all users'],
'objectclass': fuzzy_set_ci(objectclasses.group),
'ipauniqueid': [fuzzy_uuid],
},
],
), result)
@pytest.mark.tier1
class TestExternalGroup(XMLRPC_test):
def test_create_external(self, group):
""" Create a non-posix group """
group.track_create()
del group.attrs['gidnumber']
group.attrs.update(objectclass=objectclasses.externalgroup)
# External group don't have a SID
del group.attrs['ipantsecurityidentifier']
command = group.make_create_command(**dict(external=True))
result = command()
group.check_create(result)
def test_search_for_external(self, group):
""" Search for all external groups """
command = group.make_command(
'group_find', **dict(external=True, all=True)
)
result = command()
group.check_find(result, all=True)
def test_convert_external_to_posix(self, group):
""" Try to convert an external group to posix """
command = group.make_update_command(dict(posix=True))
with raises_exact(errors.ExternalGroupViolation(
reason=u'This group cannot be posix because it is external')):
command()
def test_add_external_member_to_external(self, group):
""" Try to add an invalid external member to an external
group and check that proper exceptions are raised """
# When adding external SID member to a group we can't test
# it fully due to possibly missing Samba 4 python bindings
# and/or not configured AD trusts. Thus, we'll use incorrect
# SID value to merely test that proper exceptions are raised
command = group.make_command('group_add_member', *[group.cn],
**dict(ipaexternalmember=external_sid1))
try:
command()
except Exception as ex:
if type(ex) == errors.ValidationError:
pass
elif type(ex) == errors.NotFound:
pass
elif 'failed' in str(ex):
pass
else:
raise ex
def test_delete_external_group(self, group):
group.delete()
@pytest.mark.tier1
class TestGroupMember(XMLRPC_test):
def test_add_nonexistent_member(self, group):
""" Try to add non-existent member to a group """
group.create()
command = group.make_add_member_command(dict(group=notagroup))
result = command()
group.check_add_member_negative(result, dict(group=notagroup))
def test_remove_nonexistent_member(self, group):
""" Try to remove non-existent member from a group """
group.ensure_exists()
command = group.make_remove_member_command(dict(group=notagroup))
result = command()
group.check_remove_member_negative(result, dict(group=notagroup))
def test_add_member(self, group, group2):
""" Add member group to a group """
group.ensure_exists()
group2.ensure_exists()
group.add_member(dict(group=group2.cn))
def test_remove_member(self, group, group2):
""" Remove a group member """
group.ensure_exists()
group2.ensure_exists()
group.remove_member(dict(group=group2.cn))
def test_add_and_remove_group_from_admins(self, group, admins):
""" Add group to protected admins group and then remove it """
# Test scenario from ticket #4448
# https://fedorahosted.org/freeipa/ticket/4448
group.ensure_exists()
admins.add_member(dict(group=group.cn))
admins.remove_member(dict(group=group.cn))
@pytest.mark.tier1
class TestValidation(XMLRPC_test):
# The assumption for this class of tests is that if we don't
# get a validation error then the request was processed normally.
def test_validation_disabled_on_delete(self, group):
""" Test that validation is disabled on group deletes """
command = group.make_command('group_del', invalidgroup1)
with raises_exact(errors.NotFound(
reason=u'%s: group not found' % invalidgroup1)):
command()
def test_validation_disabled_on_show(self, group):
""" Test that validation is disabled on group retrieves """
command = group.make_command('group_show', invalidgroup1)
with raises_exact(errors.NotFound(
reason=u'%s: group not found' % invalidgroup1)):
command()
def test_validation_disabled_on_mod(self, group):
""" Test that validation is disabled on group mods """
command = group.make_command('group_mod', invalidgroup1)
with raises_exact(errors.NotFound(
reason=u'%s: group not found' % invalidgroup1)):
command()
@pytest.mark.tier1
class TestManagedGroups(XMLRPC_test):
def test_verify_managed_created(self, managed_group):
""" Verify that managed group is created with new user """
managed_group.retrieve()
def test_verify_managed_findable(self, managed_group):
""" Verify that managed group can be found """
command = managed_group.make_find_command(
**dict(cn=managed_group.cn, private=True)
)
result = command()
managed_group.check_find(result)
def test_delete_managed(self, managed_group):
""" Try to delete managed group """
command = managed_group.make_delete_command()
with raises_exact(errors.ManagedGroupError()):
command()
def test_detach_managed(self, managed_group):
""" Detach managed group from a user """
command = managed_group.make_detach_command()
result = command()
managed_group.check_detach(result)
def test_delete_detached_managed(self, managed_group, user):
""" Delete a previously managed group that is now detached
and verify it's really gone """
managed_group.delete()
command = managed_group.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: group not found' % managed_group.cn)):
command()
user.ensure_missing()
def test_verify_managed_missing_for_user_without_upg(self, user_npg2):
""" Create a user without user private group and
verify private group wasn't created """
user_npg2.attrs.update(memberof_group=[u'ipausers'])
command = user_npg2.make_create_command()
result = command()
user_npg2.check_create(result, [u'description', u'memberof_group'])
command = user_npg2.make_command('group_show', *[user_npg2.uid])
with raises_exact(errors.NotFound(
reason=u'%s: group not found' % user_npg2.uid)):
command()
@pytest.mark.tier1
class TestManagedGroupObjectclasses(XMLRPC_test):
def test_check_objectclasses_after_detach(self, user, managed_group):
""" Check objectclasses after user was detached from managed group """
# https://fedorahosted.org/freeipa/ticket/4909#comment:1
user.ensure_exists()
user.run_command('group_detach', *[user.uid])
managed_group.retrieve(all=True)
managed_group.add_member(dict(user=user.uid))
managed_group.ensure_missing()
user.ensure_missing()
@pytest.mark.tier1
class TestAdminGroup(XMLRPC_test):
def test_remove_admin_from_admins(self, admins):
""" Remove the original admin from admins group """
command = admins.make_remove_member_command(
dict(user=u'admin')
)
with raises_exact(errors.LastMemberError(
key=u'admin', label=u'group', container=admins.cn)):
command()
def test_add_another_admin(self, admins, user):
""" Add second member to the admins group """
user.ensure_exists()
admins.add_member(dict(user=user.uid))
def test_remove_all_admins_from_admins(self, admins, user):
""" Try to remove both original and our admin from admins group """
command = admins.make_remove_member_command(
dict(user=[u'admin', user.uid])
)
with raises_exact(errors.LastMemberError(
key=u'admin', label=u'group', container=admins.cn)):
command()
def test_delete_admins(self, admins):
""" Try to delete the protected admins group """
command = admins.make_delete_command()
with raises_exact(errors.ProtectedEntryError(label=u'group',
key=admins.cn, reason='privileged group')):
command()
def test_rename_admins(self, admins):
""" Try to rename the protected admins group """
command = admins.make_command('group_mod', *[admins.cn],
**dict(rename=renamedgroup1))
with raises_exact(errors.ProtectedEntryError(label=u'group',
key=admins.cn, reason='Cannot be renamed')):
command()
def test_rename_admins_using_setattr(self, admins):
""" Try to rename the protected admins group using setattr """
command = admins.make_command('group_mod', *[admins.cn],
**dict(setattr=u'cn=%s' % renamedgroup1))
with raises_exact(errors.ProtectedEntryError(label=u'group',
key=admins.cn, reason='Cannot be renamed')):
command()
def test_update_admins_to_support_external_membership(self, admins):
""" Try to modify the admins group to support external membership """
command = admins.make_command('group_mod', *[admins.cn],
**dict(external=True))
with raises_exact(errors.ProtectedEntryError(label=u'group',
key=admins.cn,
reason='Cannot support external non-IPA members')):
command()
@pytest.mark.tier1
class TestTrustAdminGroup(XMLRPC_test):
def test_delete_trust_admins(self, trustadmins):
""" Try to delete the protected 'trust admins' group """
command = trustadmins.make_delete_command()
with raises_exact(errors.ProtectedEntryError(label=u'group',
key=trustadmins.cn, reason='privileged group')):
command()
def test_rename_trust_admins(self, trustadmins):
""" Try to rename the protected 'trust admins' group """
command = trustadmins.make_command('group_mod', *[trustadmins.cn],
**dict(rename=renamedgroup1))
with raises_exact(errors.ProtectedEntryError(label=u'group',
key=trustadmins.cn, reason='Cannot be renamed')):
command()
def test_rename_trust_admins_using_setattr(self, trustadmins):
""" Try to rename the protected 'trust admins' group using setattr """
command = trustadmins.make_command(
'group_mod', *[trustadmins.cn],
**dict(setattr=u'cn=%s' % renamedgroup1)
)
with raises_exact(errors.ProtectedEntryError(label=u'group',
key=trustadmins.cn, reason='Cannot be renamed')):
command()
def test_update_trust_admins_to_support_external_membership(
self, trustadmins
):
""" Try to modify the 'trust admins' group to
support external membership """
command = trustadmins.make_command(
'group_mod', *[trustadmins.cn],
**dict(external=True)
)
with raises_exact(errors.ProtectedEntryError(label=u'group',
key=trustadmins.cn,
reason='Cannot support external non-IPA members')):
command()
@pytest.mark.tier1
class TestGroupMemberManager(XMLRPC_test):
def test_add_member_manager_user(self, user, group):
user.ensure_exists()
group.ensure_exists()
group.add_member_manager({"user": user.uid})
def test_remove_member_manager_user(self, user, group):
user.ensure_exists()
group.ensure_exists()
group.remove_member_manager({"user": user.uid})
def test_add_member_manager_group(self, group, group2):
group.ensure_exists()
group2.ensure_exists()
group.add_member_manager({"group": group2.cn})
def test_remove_member_manager_group(self, group, group2):
group.ensure_exists()
group2.ensure_exists()
group.remove_member_manager({"group": group2.cn})
def test_member_manager_delete_user(self, user, group):
user.ensure_exists()
group.ensure_exists()
group.add_member_manager({"user": user.uid})
user.delete()
# deleting a user also deletes member manager reference
group.attrs.pop("membermanager_user")
group.retrieve()
| 33,326
|
Python
|
.py
| 761
| 32.592641
| 79
| 0.586365
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,482
|
test_automember_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_automember_plugin.py
|
# Authors:
# Jr Aquino <jr.aquino@citrix.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 `ipaserver/plugins/automember.py` module.
"""
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
from ipatests.test_xmlrpc.tracker.host_plugin import HostTracker
from ipatests.test_xmlrpc.tracker.group_plugin import GroupTracker
from ipatests.test_xmlrpc.tracker.hostgroup_plugin import HostGroupTracker
from ipatests.test_xmlrpc.tracker.automember_plugin import AutomemberTracker
from ipalib import api, errors
from ipapython.dn import DN
from ipapython.ipautil import run
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, raises_exact
from ipatests.util import assert_deepequal
from ipaserver.plugins.automember import REBUILD_TASK_CONTAINER
import time
import pytest
import re
from pkg_resources import parse_version
try:
from ipaserver.plugins.ldap2 import ldap2
except ImportError:
have_ldap2 = False
else:
have_ldap2 = True
user_does_not_exist = u'does_not_exist'
fqdn_does_not_exist = u'does_not_exist.%s' % api.env.domain
group_include_regex = u'mscott'
hostgroup_include_regex = u'^web[1-9]'
hostgroup_include_regex2 = u'^www[1-9]'
hostgroup_include_regex3 = u'webserver[1-9]'
hostgroup_exclude_regex = u'^web5'
hostgroup_exclude_regex2 = u'^www5'
hostgroup_exclude_regex3 = u'^webserver5'
@pytest.fixture(scope='class')
def manager1(request, xmlrpc_setup):
""" User tracker used as a manager account """
tracker = UserTracker(name=u'mscott', sn=u'Manager1',
givenname=u'Automember test manager user1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def user1(request, manager1):
""" User tracker with assigned manager """
tracker = UserTracker(name=u'tuser1', sn=u'User1', manager=manager1.name,
givenname=u'Automember test user1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def group1(request, xmlrpc_setup):
tracker = GroupTracker(name=u'tgroup1',
description=u'Automember test group1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def defaultgroup1(request, xmlrpc_setup):
tracker = GroupTracker(name=u'defaultgroup1',
description=u'Automember test defaultgroup1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def hostgroup1(request, xmlrpc_setup):
tracker = HostGroupTracker(name=u'thostgroup1',
description=u'Automember test hostgroup1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def hostgroup2(request, xmlrpc_setup):
tracker = HostGroupTracker(name=u'thostgroup2',
description=u'Automember test hostgroup2')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def hostgroup3(request, xmlrpc_setup):
tracker = HostGroupTracker(name=u'thostgroup3',
description=u'Automember test hostgroup3')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def hostgroup4(request, xmlrpc_setup):
tracker = HostGroupTracker(name=u'thostgroup4',
description=u'Automember test hostgroup4')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def defaulthostgroup1(request, xmlrpc_setup):
tracker = HostGroupTracker(name=u'defaulthostgroup1',
description=u'Automember test'
'defaulthostgroup1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def host1(request, xmlrpc_setup):
tracker = HostTracker(u'web1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def host2(request, xmlrpc_setup):
tracker = HostTracker(u'dev1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def host3(request, xmlrpc_setup):
tracker = HostTracker(u'web5')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def host4(request, xmlrpc_setup):
tracker = HostTracker(u'www5')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def host5(request, xmlrpc_setup):
tracker = HostTracker(u'webserver5')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def automember_group(request, group1):
tracker = AutomemberTracker(groupname=group1.cn,
description=u'Automember group tracker',
membertype=u'group')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def automember_hostgroup(request, hostgroup1):
tracker = AutomemberTracker(groupname=hostgroup1.cn,
description=u'Automember hostgroup tracker',
membertype=u'hostgroup')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def automember_hostgroup2(request, hostgroup2):
tracker = AutomemberTracker(groupname=hostgroup2.cn,
description=u'Automember hostgroup tracker 2',
membertype=u'hostgroup')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def automember_hostgroup3(request, hostgroup3):
tracker = AutomemberTracker(groupname=hostgroup3.cn,
description=u'Automember hostgroup tracker 3',
membertype=u'hostgroup')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def automember_hostgroup4(request, hostgroup4):
tracker = AutomemberTracker(groupname=hostgroup4.cn,
description=u'Automember hostgroup tracker 4',
membertype=u'hostgroup')
return tracker.make_fixture(request)
@pytest.mark.tier1
class TestAutomemberAddNegative(XMLRPC_test):
"""Test the ipa automember-add command."""
def test_create_with_nonexistent_group(self, automember_group, group1):
""" Try to add a rule with non-existent group """
group1.ensure_missing()
command = automember_group.make_create_command()
with raises_exact(errors.NotFound(
reason=u'group "%s" not found' % group1.cn)):
command()
def test_create_with_nonexistent_hostgroup(self, automember_hostgroup,
hostgroup1):
""" Try to add a rule with non-existent group """
hostgroup1.ensure_missing()
command = automember_hostgroup.make_create_command()
with raises_exact(errors.NotFound(
reason=u'hostgroup "%s" not found' % hostgroup1.cn)):
command()
@pytest.mark.parametrize(
"automember_grp", [
"automember_group",
"automember_hostgroup"
])
def test_delete_with_nonexistent_automember(self, automember_grp,
request):
""" Try to delete a rule a non-existent rule"""
automember_grp = request.getfixturevalue(automember_grp)
automember_grp.ensure_missing()
command = automember_grp.make_delete_command()
with pytest.raises(errors.NotFound,
match=r'%s: Automember rule not found'
% automember_grp.cn):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_create_with_existent_group(self, automember_grp, grp, request):
""" Try to add a rule that already exists """
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_create_command()
with pytest.raises(errors.DuplicateEntry,
match=r'Automember rule with name "%s" '
r'already exists' % grp.cn):
command()
class TestAutomemberFindNegative(XMLRPC_test):
"""Test the ipa automember-find command."""
@pytest.mark.parametrize(
"automember_grp", [
"automember_group",
"automember_hostgroup"
])
def test_find_with_nonexistent_automember(self, automember_grp,
request):
""" Try to find a rule a non-existent rule """
automember_grp = request.getfixturevalue(automember_grp)
automember_grp.ensure_missing()
command = automember_grp.make_find_command()
result = command()
assert_deepequal(dict(
count=0,
truncated=False,
summary=u'0 rules matched',
result=[],
), result)
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_find_with_invalidtype(self, automember_grp, grp, request):
""" Try to find rule with invalid type """
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_command('automember_find', grp.name,
type='badtype')
with pytest.raises(errors.ValidationError,
match=r'invalid \'type\': must be one '
r'of \'group\', \'hostgroup\''):
command()
class TestAutomemberShowNegative(XMLRPC_test):
"""Test the ipa automember-show command."""
@pytest.mark.parametrize(
"automember_grp", [
"automember_group",
"automember_hostgroup"
])
def test_show_with_nonexistent_automember(self, automember_grp,
request):
""" Try to show a non-existent rule """
automember_grp = request.getfixturevalue(automember_grp)
automember_grp.ensure_missing()
command = automember_grp.make_retrieve_command()
with pytest.raises(errors.NotFound,
match=r'%s: Automember rule not found'
% automember_grp.cn):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_show_with_invalidtype_group(self, automember_grp, grp, request):
""" Try to show a rule with invalid type """
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_command('automember_show', grp.name,
type='badtype')
with pytest.raises(errors.ValidationError,
match=r'invalid \'type\': must be one '
r'of \'group\', \'hostgroup\''):
command()
@pytest.mark.tier1
class TestCRUDFOnAutomember(XMLRPC_test):
def test_basic_ops_on_group_automember(self, automember_group, group1):
""" Test create, retrieve, find, update,
and delete operations on a group automember """
group1.create()
automember_group.create()
automember_group.retrieve()
automember_group.find()
automember_group.update(dict(description=u'New description'))
automember_group.delete()
def test_basic_ops_on_hostgroup_automember(self, automember_hostgroup,
hostgroup1):
""" Test create, retrieve, find, update,
and delete operations on a hostgroup automember """
hostgroup1.create()
automember_hostgroup.create()
automember_hostgroup.retrieve()
automember_hostgroup.find()
automember_hostgroup.update(dict(description=u'New description'))
automember_hostgroup.delete()
def set_automember_process_modify_ops(value):
"""Configure the auto member plugin to process modifyOps
Set the value for the attribute autoMemberProcessModifyOps of the entry
cn=Auto Membership Plugin,cn=plugins,cn=config.
:param value: can be either on or off
"""
if not have_ldap2:
pytest.skip('server plugin not available')
ldap = ldap2(api)
ldap.connect()
plugin_entry = ldap.get_entry(
DN("cn=Auto Membership Plugin,cn=plugins,cn=config"))
plugin_entry['autoMemberProcessModifyOps'] = value
try:
ldap.update_entry(plugin_entry)
except errors.EmptyModlist:
pass
# Requires a 389-ds restart
dashed_domain = api.env.realm.replace(".", "-")
cmd = ['systemctl', 'restart', 'dirsrv@{}'.format(dashed_domain)]
run(cmd)
def wait_automember_rebuild():
"""Wait for an asynchronous automember rebuild to finish
Lookup the rebuild taskid and then loop until it is finished.
If no task is found assume that the task is already finished.
"""
if not have_ldap2:
pytest.skip('server plugin not available')
ldap = ldap2(api)
ldap.connect()
# give the task a chance to start
time.sleep(1)
try:
task_entries, unused = ldap.find_entries(
base_dn=REBUILD_TASK_CONTAINER,
filter='(&(!(nstaskexitcode=0))(scope=*))')
except errors.NotFound:
# either it's done already or it never started
return
# we run these serially so there should be only one at a time
assert len(task_entries) == 1
task_dn = task_entries[0].dn
start_time = time.time()
while True:
try:
task = ldap.get_entry(task_dn)
except errors.NotFound:
# not likely but let's hope the task disappered because it's
# finished
break
if 'nstaskexitcode' in task:
# a non-zero exit code means something broke
assert task.single_value['nstaskexitcode'] == '0'
break
time.sleep(1)
# same arbitrary wait time as hardcoded in automember plugin
assert time.time() < (start_time + 60)
@pytest.mark.tier1
class TestAutomemberRebuildHostMembership(XMLRPC_test):
def test_create_deps_for_rebuilding_hostgroups(self, hostgroup1, host1,
automember_hostgroup):
""" Create host, hostgroup, and automember tracker for this class
of tests """
hostgroup1.ensure_exists()
host1.ensure_exists()
automember_hostgroup.ensure_exists()
automember_hostgroup.add_condition(
key=u'fqdn', type=u'hostgroup',
inclusiveregex=[hostgroup_include_regex]
)
hostgroup1.retrieve()
def test_rebuild_membership_hostgroups(self, automember_hostgroup,
hostgroup1, host1):
""" Rebuild automember membership for hosts, both synchonously and
asynchronously. Check the host has been added to the hostgroup. """
# In the first part of test,
# auto member process modify ops is disabled
# This means that we can manually remove a member without
# triggering the auto member plugin
try:
set_automember_process_modify_ops(value=b'off')
automember_hostgroup.rebuild()
automember_hostgroup.rebuild(no_wait=True)
wait_automember_rebuild()
# After rebuild, the member is added, and we need to update
# the tracker obj
hostgroup1.attrs.update(member_host=[host1.fqdn])
hostgroup1.retrieve()
# Now try to remove the member
hostgroup1.remove_member(dict(host=host1.fqdn))
hostgroup1.retrieve()
finally:
set_automember_process_modify_ops(value=b'on')
# Rebuild membership to re-add the member
automember_hostgroup.rebuild()
automember_hostgroup.rebuild(no_wait=True)
wait_automember_rebuild()
# After rebuild, the member is added, and we need to update
# the tracker obj
hostgroup1.attrs.update(member_host=[host1.fqdn])
hostgroup1.retrieve()
# In the second part of the test,
# enable auto member process modify ops
# This means that a manual removal of a member will return success
# but the member gets re-added by the auto member plugin
# Expecting to raise an error as the member gets re-added
with pytest.raises(AssertionError) as error:
hostgroup1.remove_member(dict(host=host1.fqdn))
assert "extra keys = ['member_host']" in str(error.value)
def test_rebuild_membership_for_host(self, host1, automember_hostgroup,
hostgroup1):
""" Rebuild automember membership for one host, both synchronously and
asynchronously. Check the host has been added to the hostgroup. """
command = automember_hostgroup.make_rebuild_command(hosts=host1.fqdn)
result = command()
automember_hostgroup.check_rebuild(result)
command = automember_hostgroup.make_rebuild_command(hosts=host1.fqdn,
no_wait=True)
result = command()
automember_hostgroup.check_rebuild(result, no_wait=True)
wait_automember_rebuild()
hostgroup1.attrs.update(member_host=[host1.fqdn])
hostgroup1.retrieve()
def test_delete_deps_for_rebuilding_hostgroups(self, host1, hostgroup1,
automember_hostgroup):
""" Delete dependences for this class of tests in desired order """
host1.delete()
hostgroup1.delete()
automember_hostgroup.delete()
class TestAutomemberModifyNegative(XMLRPC_test):
"""Test the ipa automember-mod command."""
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_modify_with_same_value(self, automember_grp, grp, request):
""" Try to modify an existing rule with the same value """
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_update_command(updates=dict(
description='%s' % automember_grp.description))
with pytest.raises(errors.EmptyModlist,
match=r"no modifications to be performed"):
command()
@pytest.mark.parametrize(
"automember_grp", [
"automember_group",
"automember_hostgroup"
])
def test_modify_with_nonexistent_automember(self, automember_grp,
request):
""" Try to modify a non-existent rule """
automember_grp = request.getfixturevalue(automember_grp)
automember_grp.ensure_missing()
command = automember_grp.make_update_command(updates=dict(
description='WEB_SERVERS'))
with pytest.raises(errors.NotFound,
match=r'%s: Automember rule not found' %
automember_grp.cn):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_modify_with_invalidtype_group(self, automember_grp, grp, request):
""" Try to modify rule with invalid type """
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_command('automember_mod', grp.name,
type='badtype',
description='WEB_SERVERS')
with pytest.raises(errors.ValidationError,
match=r'invalid \'type\': must be one '
r'of \'group\', \'hostgroup\''):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_modify_with_group_badattr(self, automember_grp, grp, request):
"Try to modify rule with invalid attribute"
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_update_command(updates=dict(
badattr='WEB_SERVERS'))
with raises_exact(errors.OptionError(
('Unknown option: %(option)s'), option='badattr')):
command()
@pytest.mark.tier1
class TestAutomemberRebuildGroupMembership(XMLRPC_test):
def test_create_deps_for_rebuilding_groups(self, group1, manager1, user1,
automember_group):
""" Create users, groups, and automember tracker for this class
of tests """
group1.ensure_exists()
manager1.ensure_exists()
user1.ensure_exists()
automember_group.ensure_exists()
automember_group.add_condition(
key=u'manager', type=u'group', inclusiveregex=[group_include_regex]
)
group1.retrieve()
def test_rebuild_membership_groups(self, automember_group, group1, user1):
""" Rebuild automember membership for groups, both synchonously and
asynchronously. Check the user has been added to the group. """
# In the first part of test,
# auto member process modify ops is disabled
# This means that we can manually remove a member without
# triggering the auto member plugin
try:
set_automember_process_modify_ops(value=b'off')
automember_group.rebuild()
automember_group.rebuild(no_wait=True)
wait_automember_rebuild()
# After rebuild, the member is added, and we need to update
# the tracker obj
group1.attrs.update(member_user=[user1.name])
group1.retrieve()
# Now try to remove the member
group1.remove_member(dict(user=user1.name))
group1.retrieve()
finally:
set_automember_process_modify_ops(value=b'on')
# Rebuild membership to re-add the member
automember_group.rebuild()
automember_group.rebuild(no_wait=True)
wait_automember_rebuild()
# After rebuild, the member is added, and we need to update
# the tracker obj
group1.attrs.update(member_user=[user1.name])
group1.retrieve()
# In the second part of the test,
# auto member process modify ops is enabled
# This means that a manual removal of a member will return success
# but the member gets re-added by the auto member plugin
# Expecting to raise an error as the member gets re-added
with pytest.raises(AssertionError) as error:
group1.remove_member(dict(user=user1.name))
assert "extra keys = ['member_user']" in str(error.value)
def test_rebuild_membership_for_user(self, user1, automember_group,
group1):
""" Rebuild automember membership for one user, both synchronously and
asynchronously. Check the user has been added to the group. """
command = automember_group.make_rebuild_command(users=user1.name)
result = command()
automember_group.check_rebuild(result)
command = automember_group.make_rebuild_command(users=user1.name,
no_wait=True)
result = command()
automember_group.check_rebuild(result, no_wait=True)
wait_automember_rebuild()
group1.attrs.update(member_user=[user1.name])
group1.retrieve()
def test_delete_deps_for_rebuilding_groups(self, user1, manager1, group1,
automember_group):
""" Delete dependences for this class of tests in desired order """
user1.delete()
manager1.delete()
group1.delete()
automember_group.delete()
@pytest.mark.tier1
class TestAutomemberRebuildMembershipIncorrectly(XMLRPC_test):
def test_rebuild_membership_hosts_incorrectly(self, automember_hostgroup):
""" Try to issue rebuild automember command without 'type' parameter
"""
command = automember_hostgroup.make_rebuild_command()
with raises_exact(errors.MutuallyExclusiveError(
reason=u'at least one of options: '
'type, users, hosts must be specified')):
command()
def test_rebuild_membership_user_hosts(self, automember_hostgroup, user1,
host1):
""" Try to issue rebuild membership command with --users and --hosts
together """
command = automember_hostgroup.make_rebuild_command(users=user1.name,
hosts=host1.fqdn)
with raises_exact(errors.MutuallyExclusiveError(
reason=u'users and hosts cannot both be set')):
command()
def test_rebuild_membership_users_hostgroup(self, automember_hostgroup,
user1):
""" Try to issue rebuild membership command with type --hosts and
users specified """
command = automember_hostgroup.make_rebuild_command(users=user1.name,
type=u'hostgroup')
with raises_exact(errors.MutuallyExclusiveError(
reason=u"users cannot be set when type is 'hostgroup'")):
command()
def test_rebuild_membership_hosts_group(self, automember_hostgroup, user1,
host1):
""" Try to issue rebuild membership command with type --users and
hosts specified """
command = automember_hostgroup.make_rebuild_command(hosts=host1.fqdn,
type=u'group')
with raises_exact(errors.MutuallyExclusiveError(
reason=u"hosts cannot be set when type is 'group'")):
command()
class TestAutomemberAddConditionNegative(XMLRPC_test):
"""Test the ipa automember-add-condition command."""
@pytest.mark.parametrize(
"automember_grp", [
"automember_group",
"automember_hostgroup"
])
def test_create_inclusive_with_nonexistent_automember(
self, automember_grp, request):
automember_grp = request.getfixturevalue(automember_grp)
automember_grp.ensure_missing()
command = automember_grp.make_add_condition_command(
key=u'manager', type=automember_grp.membertype,
automemberinclusiveregex="eng[0-9]+.example.com")
with pytest.raises(errors.NotFound,
match=r'Auto member rule: %s not found'
% automember_grp.cn):
command()
@pytest.mark.parametrize(
"automember_grp", [
"automember_group",
"automember_hostgroup"
])
def test_create_exclusive_with_nonexistent_automember(
self, automember_grp, request):
automember_grp = request.getfixturevalue(automember_grp)
automember_grp.ensure_missing()
command = automember_grp.make_add_condition_command(
key=u'manager', type=automember_grp.membertype,
automemberexclusiveregex="qa[0-9]+.example.com")
with pytest.raises(errors.NotFound,
match=r'Auto member rule: %s not found'
% automember_grp.cn):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_create_inclusive_with_existent_automember(
self, automember_grp, grp, request):
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
automember_grp.add_condition(key=u'manager',
type=automember_grp.membertype,
inclusiveregex=[group_include_regex])
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_create_exclusive_with_existent_automember(
self, automember_grp, grp, request):
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
automember_grp.add_condition_exclusive(
key=u'manager', type=automember_grp.membertype,
exclusiveregex=[u'mjohn'])
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_create_inclusive_with_group_invalidtype(self, automember_grp,
grp, request):
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_add_condition_command(
key=u'manager', type='badtype',
automemberinclusiveregex=[u'mjohn'])
with pytest.raises(errors.ValidationError,
match=r'invalid \'type\': must be one '
r'of \'group\', \'hostgroup\''):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_create_exclusive_with_group_invalidtype(self, automember_grp,
grp, request):
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_add_condition_command(
key=u'fqdn', type='badtype',
automemberexclusiveregex="eng[0-9]+.example.com")
with pytest.raises(errors.ValidationError,
match=r'invalid \'type\': must be one '
r'of \'group\', \'hostgroup\''):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_create_inclusive_with_group_invalidkey(self, automember_grp,
grp, request):
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_add_condition_command(
key='badkey', type=automember_grp.membertype,
automemberinclusiveregex=[group_include_regex])
with pytest.raises(errors.NotFound,
match=r'badkey is not a valid attribute.'):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_create_exclusive_with_group_invalidkey(self, automember_grp,
grp, request):
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_add_condition_command(
key='badkey', type=automember_grp.membertype,
automemberexclusiveregex=[group_include_regex])
with pytest.raises(errors.NotFound,
match=r'badkey is not a valid attribute.'):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_create_inclusive_with_group_badregextype(
self, automember_grp, grp, request):
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_add_condition_command(
key='manager', type=automember_grp.membertype,
badregextype_regex=[group_include_regex])
with raises_exact(errors.OptionError(
('Unknown option: %(option)s'), option='badregextype_regex')):
command()
class TestAutomemberRemoveCondition(XMLRPC_test):
"""Test the ipa automember-remove-condition command."""
@pytest.mark.parametrize(
"automember_grp", [
"automember_group",
"automember_hostgroup"
])
def test_remove_inclusive_with_nonexistent_automember(
self, automember_grp, request):
"""Test automember-remove-condition RULE when RULE does not exist."""
automember_grp = request.getfixturevalue(automember_grp)
automember_grp.ensure_missing()
command = automember_grp.make_remove_condition_command(
key=u'manager', type=automember_grp.membertype,
automemberinclusiveregex="eng[0-9]+.example.com")
with pytest.raises(errors.NotFound,
match=r'Auto member rule: %s not found'
% automember_grp.cn):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_remove_inclusive_with_group_invalidtype(self, automember_grp,
grp, request):
"""Test automember-remove-condition RULE --type TYPE with invalid
TYPE."""
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_remove_condition_command(
key=u'manager', type='badtype',
automemberinclusiveregex=[u'mjohn'])
with pytest.raises(errors.ValidationError,
match=r'invalid \'type\': must be one '
r'of \'group\', \'hostgroup\''):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_remove_inclusive_with_group_badregextype(
self, automember_grp, grp, request):
"""Test automember-remove-condition RULE with invalid regextype."""
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_remove_condition_command(
key='manager', type=automember_grp.membertype,
badregextype_regex=[group_include_regex])
with raises_exact(errors.OptionError(
('Unknown option: %(option)s'), option='badregextype_regex')):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_remove_inclusive_with_group_invalidkey(
self, automember_grp, grp, request):
"""Test automember-remove-condition RULE --key KEY with invalid KEY."""
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
automember_grp.add_condition(key=u'manager',
type=automember_grp.membertype,
inclusiveregex=[group_include_regex])
command = automember_grp.make_remove_condition_command(
key='badkey', type=automember_grp.membertype,
automemberinclusiveregex=[group_include_regex])
result = command()
expected = dict(
value=automember_grp.cn,
summary=u'Removed condition(s) from "%s"' % automember_grp.cn,
completed=0,
failed=dict(
failed=dict(
automemberexclusiveregex=tuple(),
automemberinclusiveregex=(u'badkey=%s' %
group_include_regex,),
)
),
result=dict(
automemberinclusiveregex=[u'manager=%s' %
group_include_regex],
),
)
assert_deepequal(expected, result)
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_remove_inclusive_with_group_badregex(
self, automember_grp, grp, request):
"""Test automember-remove-condition RULE with invalid regex."""
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_remove_condition_command(
key='manager', type=automember_grp.membertype,
automemberinclusiveregex=[u'badmscott'])
result = command()
expected = dict(
value=automember_grp.cn,
summary=u'Removed condition(s) from "%s"' % automember_grp.cn,
completed=0,
failed=dict(
failed=dict(
automemberexclusiveregex=tuple(),
automemberinclusiveregex=(u'manager=badmscott',),
)
),
result=dict(
automemberinclusiveregex=[u'manager=%s' %
group_include_regex],
),
)
assert_deepequal(expected, result)
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_positive_remove_inclusive(
self, automember_grp, grp, request):
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_remove_condition_command(
key='manager', type=automember_grp.membertype,
automemberinclusiveregex=[u'mjohn'])
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_remove_exclusive_with_group_invalidtype(self, automember_grp,
grp, request):
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_remove_condition_command(
key=u'fqdn', type='badtype',
automemberexclusiveregex="eng[0-9]+.example.com")
with pytest.raises(errors.ValidationError,
match=r'invalid \'type\': must be one '
r'of \'group\', \'hostgroup\''):
command()
@pytest.mark.parametrize(
"automember_grp", [
"automember_group",
"automember_hostgroup"
])
def test_remove_exclusive_with_nonexistent_automember(
self, automember_grp, request):
automember_grp = request.getfixturevalue(automember_grp)
automember_grp.ensure_missing()
command = automember_grp.make_remove_condition_command(
key=u'manager', type=automember_grp.membertype,
automemberexclusiveregex="qa[0-9]+.example.com")
with pytest.raises(errors.NotFound,
match=r'Auto member rule: %s not found'
% automember_grp.cn):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_remove_exclusive_with_group_badregextype(
self, automember_grp, grp, request):
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_remove_condition_command(
key='manager', type=automember_grp.membertype,
badregextype_regex="qa[0-9]+.example.com")
with raises_exact(errors.OptionError(
('Unknown option: %(option)s'), option='badregextype_regex')):
command()
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_remove_exclusive_with_group_invalidkey(
self, automember_grp, grp, request):
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
automember_grp.add_condition_exclusive(key=u'manager',
type=automember_grp.membertype,
exclusiveregex=[u'mjohn'])
command = automember_grp.make_remove_condition_command(
key='badkey', type=automember_grp.membertype,
automemberexclusiveregex=[u'mjohn'])
result = command()
expected = dict(
value=automember_grp.cn,
summary=u'Removed condition(s) from "%s"' % automember_grp.cn,
completed=0,
failed=dict(
failed=dict(
automemberexclusiveregex=(u'badkey=mjohn',),
automemberinclusiveregex=tuple(),
)
),
result=dict(
automemberexclusiveregex=[u'manager=mjohn'],
),
)
assert_deepequal(expected, result)
@pytest.mark.parametrize(
"automember_grp, grp", [
("automember_group", "group1"),
("automember_hostgroup", "hostgroup1")
])
def test_remove_exclusive_with_group_badregex(
self, automember_grp, grp, request):
grp = request.getfixturevalue(grp)
automember_grp = request.getfixturevalue(automember_grp)
grp.ensure_exists()
automember_grp.ensure_exists()
command = automember_grp.make_remove_condition_command(
key='manager', type=automember_grp.membertype,
automemberexclusiveregex=[u'badmjohn'])
result = command()
expected = dict(
value=automember_grp.cn,
summary=u'Removed condition(s) from "%s"' % automember_grp.cn,
completed=0,
failed=dict(
failed=dict(
automemberinclusiveregex=tuple(),
automemberexclusiveregex=(u'manager=badmjohn',),
)
),
result=dict(
automemberexclusiveregex=[u'manager=mjohn'],
),
)
assert_deepequal(expected, result)
@pytest.mark.tier1
class TestMultipleAutomemberConditions(XMLRPC_test):
def test_create_deps_for_multiple_conditions(
self, group1, hostgroup1, hostgroup2, hostgroup3, hostgroup4,
defaultgroup1, defaulthostgroup1,
automember_group, automember_hostgroup
):
""" Create groups, hostgroups, and automember conditions
for this class of tests """
group1.ensure_exists()
hostgroup1.ensure_exists()
hostgroup2.ensure_exists()
hostgroup3.ensure_exists()
hostgroup4.ensure_exists()
defaultgroup1.ensure_exists()
defaulthostgroup1.ensure_exists()
automember_group.ensure_exists()
automember_group.add_condition(key=u'manager', type=u'group',
inclusiveregex=[group_include_regex])
automember_hostgroup.ensure_exists()
automember_hostgroup.add_condition(
key=u'fqdn', type=u'hostgroup',
inclusiveregex=[hostgroup_include_regex]
)
def test_create_duplicate_automember_condition(self, automember_hostgroup,
hostgroup1):
""" Try to create a duplicate automember condition """
command = automember_hostgroup.make_add_condition_command(
key=u'fqdn', type=u'hostgroup',
automemberinclusiveregex=[hostgroup_include_regex]
)
result = command()
automember_hostgroup.check_add_condition_negative(result)
def test_create_additional_automember_conditions(self,
automember_hostgroup):
""" Add additional automember conditions to existing one, with both
inclusive and exclusive regular expressions the condition """
command = automember_hostgroup.make_add_condition_command(
key=u'fqdn', type=u'hostgroup',
automemberinclusiveregex=[hostgroup_include_regex2,
hostgroup_include_regex3],
automemberexclusiveregex=[hostgroup_exclude_regex,
hostgroup_exclude_regex2,
hostgroup_exclude_regex3]
)
result = command()
expected = dict(
value=automember_hostgroup.cn,
summary=u'Added condition(s) to "%s"' % automember_hostgroup.cn,
completed=5,
failed=dict(
failed=dict(
automemberinclusiveregex=tuple(),
automemberexclusiveregex=tuple(),
)
),
result=dict(
cn=[automember_hostgroup.cn],
description=[automember_hostgroup.description],
automembertargetgroup=[automember_hostgroup.attrs
['automembertargetgroup'][0]],
automemberinclusiveregex=[u'fqdn=%s' %
hostgroup_include_regex,
u'fqdn=%s' %
hostgroup_include_regex3,
u'fqdn=%s' %
hostgroup_include_regex2,
],
automemberexclusiveregex=[u'fqdn=%s' %
hostgroup_exclude_regex2,
u'fqdn=%s' %
hostgroup_exclude_regex3,
u'fqdn=%s' %
hostgroup_exclude_regex,
],
),
)
assert_deepequal(expected, result)
automember_hostgroup.attrs.update(
automemberinclusiveregex=[u'fqdn=%s' % hostgroup_include_regex,
u'fqdn=%s' % hostgroup_include_regex3,
u'fqdn=%s' % hostgroup_include_regex2,
],
automemberexclusiveregex=[u'fqdn=%s' % hostgroup_exclude_regex2,
u'fqdn=%s' % hostgroup_exclude_regex3,
u'fqdn=%s' % hostgroup_exclude_regex,
]
) # modify automember_hostgroup tracker for next tests
def test_create_set_of_hostgroup_automembers(self, automember_hostgroup2,
automember_hostgroup3,
automember_hostgroup4):
""" Create three more hostgroup automembers """
automember_hostgroup2.ensure_exists()
automember_hostgroup2.add_condition(
key=u'fqdn', type=u'hostgroup',
inclusiveregex=[hostgroup_exclude_regex]
)
automember_hostgroup3.ensure_exists()
automember_hostgroup3.add_condition(
key=u'fqdn', type=u'hostgroup',
inclusiveregex=[hostgroup_exclude_regex2]
)
automember_hostgroup4.ensure_exists()
automember_hostgroup4.add_condition(
key=u'fqdn', type=u'hostgroup',
inclusiveregex=[hostgroup_exclude_regex3]
)
def test_set_default_group_for_automembers(self, defaultgroup1):
""" Set new default group for group automembers """
result = api.Command['automember_default_group_set'](
type=u'group',
automemberdefaultgroup=defaultgroup1.cn
)
assert_deepequal(
dict(
result=dict(
cn=[u'Group'],
automemberdefaultgroup=[DN(('cn', defaultgroup1.cn),
('cn', 'groups'),
('cn', 'accounts'),
api.env.basedn)],
),
value=u'group',
summary=u'Set default (fallback) group for automember "group"'
),
result)
result = api.Command['automember_default_group_show'](
type=u'group',
)
assert_deepequal(
dict(
result=dict(dn=DN(('cn', 'group'),
('cn', 'automember'),
('cn', 'etc'), api.env.basedn),
cn=[u'Group'],
automemberdefaultgroup=[
DN(('cn', defaultgroup1.cn),
('cn', 'groups'),
('cn', 'accounts'),
api.env.basedn)
],
),
value=u'group',
summary=None,
),
result)
def test_set_default_hostgroup_for_automembers(self, defaulthostgroup1):
""" Set new default hostgroup for hostgroup automembers """
result = api.Command['automember_default_group_set'](
type=u'hostgroup',
automemberdefaultgroup=defaulthostgroup1.cn
)
assert_deepequal(
dict(
result=dict(
cn=[u'Hostgroup'],
automemberdefaultgroup=[DN(('cn', defaulthostgroup1.cn),
('cn', 'hostgroups'),
('cn', 'accounts'),
api.env.basedn)],
),
value=u'hostgroup',
summary=u'Set default (fallback) group for '
'automember "hostgroup"'),
result)
result = api.Command['automember_default_group_show'](
type=u'hostgroup',
)
assert_deepequal(
dict(
result=dict(dn=DN(('cn', 'hostgroup'),
('cn', 'automember'),
('cn', 'etc'), api.env.basedn),
cn=[u'Hostgroup'],
automemberdefaultgroup=[
DN(('cn', defaulthostgroup1.cn),
('cn', 'hostgroups'),
('cn', 'accounts'),
api.env.basedn)],
),
value=u'hostgroup',
summary=None,
),
result)
def test_create_deps_under_new_conditions(
self, manager1, user1, host1, host2, host3, host4, host5,
hostgroup1, hostgroup2, hostgroup3, hostgroup4,
defaulthostgroup1, defaultgroup1, group1
):
""" Create users and hosts under previously defined
automember conditions """
defaulthostgroup1.retrieve()
defaultgroup1.retrieve()
manager1.ensure_missing()
user1.ensure_missing()
manager1.track_create()
manager1.attrs.update(memberof_group=[defaultgroup1.cn, u'ipausers'])
command = manager1.make_create_command()
result = command()
manager1.check_create(result)
user1.track_create()
user1.attrs.update(memberof_group=[group1.cn, u'ipausers'])
command = user1.make_create_command()
result = command()
user1.check_create(result)
host1.track_create()
host1.attrs.update(memberofindirect_netgroup=[hostgroup1.cn],
memberof_hostgroup=[hostgroup1.cn])
command = host1.make_create_command()
result = command()
hostgroup1.attrs.update(member_host=[host1.fqdn])
host2.track_create()
host2.attrs.update(memberof_hostgroup=[defaulthostgroup1.cn],
memberofindirect_netgroup=[defaulthostgroup1.cn])
command = host2.make_create_command()
result = command()
defaulthostgroup1.attrs.update(member_host=[host2.fqdn])
host3.track_create()
host3.attrs.update(memberofindirect_netgroup=[hostgroup2.cn],
memberof_hostgroup=[hostgroup2.cn])
command = host3.make_create_command()
result = command()
hostgroup2.attrs.update(member_host=[host3.fqdn])
host4.track_create()
host4.attrs.update(memberofindirect_netgroup=[hostgroup3.cn],
memberof_hostgroup=[hostgroup3.cn])
command = host4.make_create_command()
result = command()
hostgroup3.attrs.update(member_host=[host4.fqdn])
host5.track_create()
host5.attrs.update(memberofindirect_netgroup=[hostgroup4.cn],
memberof_hostgroup=[hostgroup4.cn])
command = host5.make_create_command()
result = command()
hostgroup4.attrs.update(member_host=[host5.fqdn])
hostgroup1.retrieve()
hostgroup2.retrieve()
hostgroup3.retrieve()
hostgroup4.retrieve()
def test_rebuild_membership_for_one_host(self, automember_hostgroup,
host1):
""" Rebuild hostgroup automember membership for one host """
command = automember_hostgroup.make_rebuild_command(type=u'hostgroup',
hosts=host1.fqdn)
result = command()
automember_hostgroup.check_rebuild(result)
def test_rebuild_membership_for_one_user(self, automember_group, user1):
""" Rebuild group automember membership for one user """
command = automember_group.make_rebuild_command(type=u'group',
users=user1.name)
result = command()
automember_group.check_rebuild(result)
def test_rebuild_membership_with_invalid_hosts_in_hosts(
self, automember_hostgroup):
""" Try to rebuild membership with invalid host in --hosts """
command = automember_hostgroup.make_rebuild_command(
hosts=fqdn_does_not_exist)
with raises_exact(errors.NotFound(
reason=u'%s: host not found' % fqdn_does_not_exist)):
command()
def test_rebuild_membership_with_invalid_user_in_users(self,
automember_group):
""" Try to rebuild membership with invalid user in --users """
command = automember_group.make_rebuild_command(
users=user_does_not_exist)
with raises_exact(errors.NotFound(
reason=u'%s: user not found' % user_does_not_exist)):
command()
def test_reset_automember_default_groups(self, defaultgroup1, user1,
defaulthostgroup1, manager1):
""" Reset automember group defaults """
manager1.delete()
user1.delete()
result = api.Command['automember_default_group_remove'](
type=u'group',
)
assert_deepequal(
dict(
result=dict(
automemberdefaultgroup=u'No default (fallback) group set',
cn=([u'Group'])
),
value=u'group',
summary=u'Removed default (fallback) group'
' for automember "group"'),
result)
result = api.Command['automember_default_group_remove'](
type=u'hostgroup',
)
assert_deepequal(
dict(
result=dict(
automemberdefaultgroup=u'No default (fallback) group set',
cn=([u'Hostgroup'])
),
value=u'hostgroup',
summary=u'Removed default (fallback) group'
' for automember "hostgroup"'),
result)
defaultgroup1.ensure_missing()
defaulthostgroup1.ensure_missing()
@pytest.mark.tier1
class TestAutomemberFindOrphans(XMLRPC_test):
def test_create_deps_for_find_orphans(self, hostgroup1, host1,
automember_hostgroup):
""" Create host, hostgroup, and automember tracker for this class
of tests. """
# Create hostgroup1 and automember rule with condition
hostgroup1.ensure_exists()
host1.ensure_exists()
# Manually create automember rule and condition, racker will try to
# remove the automember rule in the end, which is failing as the rule
# is already removed
api.Command['automember_add'](hostgroup1.cn, type=u'hostgroup')
api.Command['automember_add_condition'](
hostgroup1.cn,
key=u'fqdn', type=u'hostgroup',
automemberinclusiveregex=[hostgroup_include_regex]
)
hostgroup1.retrieve()
def test_find_orphan_automember_rules(self, hostgroup1):
""" Remove hostgroup1, find and remove obsolete automember rules. """
# Remove hostgroup1
hostgroup1.ensure_missing()
# Test rebuild (is failing)
# rebuild fails if 389-ds is older than 1.4.0.22 where unmembering
# feature was implemented: https://pagure.io/389-ds-base/issue/50077
if not have_ldap2:
pytest.skip('server plugin not available')
ldap = ldap2(api)
ldap.connect()
rootdse = ldap.get_entry(DN(''), ['vendorVersion'])
version = rootdse.single_value.get('vendorVersion')
# The format of vendorVersion is the following:
# 389-Directory/1.3.8.4 B2019.037.1535
# Extract everything between 389-Directory/ and ' B'
mo = re.search(r'389-Directory/(.*) B', version)
vendor_version = parse_version(mo.groups()[0])
expected_failure = vendor_version < parse_version('1.4.0.22')
try:
api.Command['automember_rebuild'](type=u'hostgroup')
except errors.DatabaseError:
rebuild_failure = True
else:
rebuild_failure = False
if expected_failure != rebuild_failure:
pytest.fail("unexpected result for automember_rebuild with "
"an orphan automember rule")
# Find obsolete automember rules
result = api.Command['automember_find_orphans'](type=u'hostgroup')
assert result['count'] == 1
# Find and remove obsolete automember rules
result = api.Command['automember_find_orphans'](type=u'hostgroup',
remove=True)
assert result['count'] == 1
# Find obsolete automember rules
result = api.Command['automember_find_orphans'](type=u'hostgroup')
assert result['count'] == 0
# Test rebuild (may not be failing)
try:
api.Command['automember_rebuild'](type=u'hostgroup')
except errors.DatabaseError:
assert False
# Final cleanup of automember rule if it still exists
with raises_exact(errors.NotFound(
reason=u'%s: Automember rule not found' % hostgroup1.cn)):
api.Command['automember_del'](hostgroup1.cn, type=u'hostgroup')
| 63,013
|
Python
|
.py
| 1,366
| 33.286969
| 79
| 0.590434
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,483
|
test_replace.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_replace.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Filip Skola <fskola@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 modlist replace logic. Some attributes require a MOD_REPLACE
while others are fine using ADD/DELETE.
Note that member management in other tests also exercises the
gen_modlist code.
"""
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
import pytest
@pytest.fixture(scope='class')
def user(request, xmlrpc_setup):
tracker = UserTracker(
name=u'user1', givenname=u'Test', sn=u'User1',
mail=[u'test1@example.com', u'test2@example.com']
)
return tracker.make_fixture(request)
@pytest.mark.tier1
class TestReplace(XMLRPC_test):
def test_create(self, user):
""" Create a user account with two mail addresses """
user.create()
def test_drop_one_add_another_mail(self, user):
""" Drop one mail address and add another to the user """
updates = {'mail': [u'test1@example.com', u'test3@example.com']}
user.update(updates, updates)
def test_set_new_single_mail(self, user):
""" Reset mail attribute to one single value """
updates = {'mail': u'test4@example.com'}
user.update(updates)
def test_set_three_new_mails(self, user):
""" Assign three new mail addresses to the user """
updates = {'mail': [
u'test5@example.com', u'test6@example.com', u'test7@example.com'
]}
user.update(updates, updates)
def test_remove_all_mails(self, user):
""" Remove all email addresses from the user """
updates = {'mail': u''}
user.update(updates)
def test_replace_initials(self, user):
""" Test single value attribute by replacing initials """
updates = {'initials': u'ABC'}
user.update(updates)
def test_drop_initials(self, user):
""" Test drop of single value attribute by dropping initials """
updates = {'initials': u''}
user.update(updates)
| 2,764
|
Python
|
.py
| 66
| 37.090909
| 76
| 0.695976
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,484
|
test_otptoken_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_otptoken_plugin.py
|
#
# Copyright (C) 2018 FreeIPA Contributors see COPYING for license
#
"""
Test the otptoken plugin.
"""
from __future__ import print_function
import pytest
from ipalib import api, errors
from ipatests.util import change_principal, unlock_principal_password
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
user_password = u'userSecretPassword123'
@pytest.fixture
def user(request):
tracker = UserTracker(name=u'user_for_otp_test',
givenname=u'Test', sn=u'User for OTP')
return tracker.make_fixture(request)
def id_function(arg):
"""
Return a label for the test parameters.
The params can be:
- the global config (list containing ipauserauthtypes)
in this case we need to extract the 'disabled' auth type to evaluate
whether user setting override is allowed
Example: [u'disabled', u'otp'] will return a label noOverride-otp
[u'otp', u'password'] otp+password
- the user config (list containing ipauserauthtypes)
- the expected outcome (boolean True if delete should be allowed)
"""
if isinstance(arg, list):
# The arg is a list, need to extract the override flag
labels = list()
if u'disabled' in arg:
labels.append('noOverride')
label = 'default'
if arg:
without_override = [item for item in arg if item != u'disabled']
if without_override:
label = '+'.join(without_override)
labels.append(label)
return "-".join(labels)
if isinstance(arg, bool):
return "allowed" if arg else "forbidden"
return 'default'
class TestDeleteLastOtpToken(XMLRPC_test):
@pytest.mark.parametrize(
"globalCfg,userCfg,allowDelLast", [
# When Global config is not set and prevents user override,
# it is possible to delete last token
([u'disabled'], None, True),
([u'disabled'], [u'otp'], True),
([u'disabled'], [u'password'], True),
([u'disabled'], [u'password', u'otp'], True),
# When Global config is not set and allows user override,
# the userCfg applies
# Deletion is forbidden only when usercfg = otp only
(None, None, True),
(None, [u'otp'], False),
(None, [u'password'], True),
(None, [u'password', u'otp'], True),
# When Global config is set to otp and prevents user override,
# it is forbidden to delete last token
([u'disabled', u'otp'], None, False),
([u'disabled', u'otp'], [u'otp'], False),
([u'disabled', u'otp'], [u'password'], False),
([u'disabled', u'otp'], [u'password', u'otp'], False),
# When Global config is set to otp and allows user override,
# the userCfg applies
# Deletion is forbidden when usercfg = otp only or usercfg not set
([u'otp'], None, False),
([u'otp'], [u'otp'], False),
([u'otp'], [u'password'], True),
([u'otp'], [u'password', u'otp'], True),
# When Global config is set to password and prevents user override,
# it is possible to delete last token
([u'disabled', u'password'], None, True),
([u'disabled', u'password'], [u'otp'], True),
([u'disabled', u'password'], [u'password'], True),
([u'disabled', u'password'], [u'password', u'otp'], True),
# When Global config is set to password and allows user override,
# the userCfg applies
# Deletion is forbidden when usercfg = otp only
([u'password'], None, True),
([u'password'], [u'otp'], False),
([u'password'], [u'password'], True),
([u'password'], [u'password', u'otp'], True),
# When Global config is set to password+otp and prevents user
# override, it is possible to delete last token
([u'disabled', u'password', u'otp'], None, True),
([u'disabled', u'password', u'otp'], [u'otp'], True),
([u'disabled', u'password', u'otp'], [u'password'], True),
([u'disabled', u'password', u'otp'], [u'password', u'otp'], True),
# When Global config is set to password+otp and allows user
# override, the userCfg applies
# Deletion is forbidden when usercfg = otp only
([u'password', u'otp'], None, True),
([u'password', u'otp'], [u'otp'], False),
([u'password', u'otp'], [u'password'], True),
([u'password', u'otp'], [u'password', u'otp'], True),
],
ids=id_function)
def test_delete(self, globalCfg, userCfg, allowDelLast, user):
"""
Test the deletion of the last otp token
The user auth type can be defined at a global level, or
per-user if the override is not disabled.
Depending on the resulting setting, the deletion of last token
is allowed or forbidden.
"""
# Save current global config
result = api.Command.config_show()
current_globalCfg = result.get('ipauserauthtype', None)
try:
# Set the global config for the test
api.Command.config_mod(ipauserauthtype=globalCfg)
except errors.EmptyModlist:
pass
try:
user.ensure_exists()
api.Command.user_mod(user.name, userpassword=user_password)
unlock_principal_password(user.name,
user_password, user_password)
# Set the user config for the test
api.Command.user_mod(user.name, ipauserauthtype=userCfg)
# Connect as user, create and delete the token
with change_principal(user.name, user_password):
api.Command.otptoken_add(u'lastotp', description=u'last otp',
ipatokenowner=user.name)
if allowDelLast:
# We are expecting the del command to succeed
api.Command.otptoken_del(u'lastotp')
else:
# We are expecting the del command to fail
with pytest.raises(errors.DatabaseError):
api.Command.otptoken_del(u'lastotp')
finally:
# Make sure the token is removed
try:
api.Command.otptoken_del(u'lastotp',)
except errors.NotFound:
pass
# Restore the previous ipauserauthtype
try:
api.Command.config_mod(ipauserauthtype=current_globalCfg)
except errors.EmptyModlist:
pass
| 6,872
|
Python
|
.py
| 147
| 35.517007
| 79
| 0.579191
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,485
|
test_service_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_service_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Pavel Zuna <pzuna@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/plugins/service.py` module.
"""
from ipalib import api, errors
from ipatests.test_xmlrpc.xmlrpc_test import Declarative, fuzzy_uuid, fuzzy_hash
from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_digits, fuzzy_date, fuzzy_issuer
from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_hex, XMLRPC_test
from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_set_optional_oc
from ipatests.test_xmlrpc.xmlrpc_test import raises_exact
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.testcert import get_testcert, subject_base
from ipatests.test_xmlrpc.test_user_plugin import get_user_result, get_group_dn
from ipatests.test_xmlrpc.tracker.service_plugin import ServiceTracker
from ipatests.test_xmlrpc.tracker.host_plugin import HostTracker
from ipatests.util import change_principal, host_keytab
import base64
from ipapython.dn import DN
import pytest
fqdn1 = u'testhost1.%s' % api.env.domain
fqdn2 = u'testhost2.%s' % api.env.domain
fqdn3 = u'TestHost3.%s' % api.env.domain
service1_no_realm = u'HTTP/%s' % fqdn1
service1 = u'%s@%s' % (service1_no_realm, api.env.realm)
badservice = u'badservice@%s' % api.env.realm # no hostname
hostprincipal1 = u'host/%s@%s' % (fqdn1, api.env.realm)
service1dn = DN(('krbprincipalname',service1),('cn','services'),('cn','accounts'),api.env.basedn)
host1dn = DN(('fqdn',fqdn1),('cn','computers'),('cn','accounts'),api.env.basedn)
host2dn = DN(('fqdn',fqdn2),('cn','computers'),('cn','accounts'),api.env.basedn)
host3dn = DN(('fqdn',fqdn3),('cn','computers'),('cn','accounts'),api.env.basedn)
d_service_no_realm = u'some/at.some.arbitrary.name'
d_service = u'%s@%s' % (d_service_no_realm, api.env.realm)
d_servicedn = DN(('krbprincipalname', d_service),
('cn', 'services'), ('cn', 'accounts'),
api.env.basedn)
role1 = u'Test Role'
role1_dn = DN(('cn', role1), api.env.container_rolegroup, api.env.basedn)
servercert = get_testcert(DN(('CN', api.env.host), subject_base()),
'unittest/%s@%s' % (api.env.host, api.env.realm))
randomissuercert = (
"MIICbzCCAdigAwIBAgICA/4wDQYJKoZIhvcNAQEFBQAwKTEnMCUGA1UEAxMeSVBBIFRlc3Q"
"gQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4XDTEwMDgwOTE1MDIyN1oXDTIwMDgwOTE1MDIyN1"
"owKTEMMAoGA1UEChMDSVBBMRkwFwYDVQQDExBwdW1hLmdyZXlvYWsuY29tMIIBIjANBgkqh"
"kiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwYbfEOQPgGenPn9vt1JFKvWm/Je3y2tawGWA3LXD"
"uqfFJyYtZ8ib3TcBUOnLk9WK5g2qCwHaNlei7bj8ggIfr5hegAVe10cun+wYErjnYo7hsHY"
"d+57VZezeipWrXu+7NoNd4+c4A5lk4A/xJay9j3bYx2oOM8BEox4xWYoWge1ljPrc5JK46f"
"0X7AGW4F2VhnKPnf8rwSuzI1U8VGjutyM9TWNy3m9KMWeScjyG/ggIpOjUDMV7HkJL0Di61"
"lznR9jXubpiEC7gWGbTp84eGl/Nn9bgK1AwHfJ2lHwfoY4uiL7ge1gyP6EvuUlHoBzdb7pe"
"kiX28iePjW3iEG9IawIDAQABoyIwIDARBglghkgBhvhCAQEEBAMCBkAwCwYDVR0PBAQDAgU"
"gMA0GCSqGSIb3DQEBBQUAA4GBACRESLemRV9BPxfEgbALuxH5oE8jQm8WZ3pm2pALbpDlAd"
"9wQc3yVf6RtkfVthyDnM18bg7IhxKpd77/p3H8eCnS8w5MLVRda6ktUC6tGhFTS4QKAf0Wy"
"DGTcIgkXbeDw0OPAoNHivoXbIXIIRxlw/XgaSaMzJQDBG8iROsN4kCv")
randomissuer = DN(('CN', 'puma.greyoak.com'), 'O=IPA')
user1 = u'tuser1'
user2 = u'tuser2'
group1 = u'group1'
group1_dn = get_group_dn(group1)
group2 = u'group2'
group2_dn = get_group_dn(group2)
hostgroup1 = u'testhostgroup1'
hostgroup1_dn = DN(('cn',hostgroup1),('cn','hostgroups'),('cn','accounts'),
api.env.basedn)
@pytest.mark.tier1
class test_service(Declarative):
cleanup_commands = [
('host_del', [fqdn1], {}),
('host_del', [fqdn2], {}),
('host_del', [fqdn3], {}),
('service_del', [service1], {}),
('service_del', [d_service], {}),
]
tests = [
dict(
desc='Try to retrieve non-existent %r' % service1,
command=('service_show', [service1], {}),
expected=errors.NotFound(
reason=u'%s: service not found' % service1),
),
dict(
desc='Try to update non-existent %r' % service1,
command=('service_mod', [service1], dict(usercertificate=servercert)),
expected=errors.NotFound(
reason=u'%s: service not found' % service1),
),
dict(
desc='Try to delete non-existent %r' % service1,
command=('service_del', [service1], {}),
expected=errors.NotFound(
reason=u'%s: service not found' % service1),
),
dict(
desc='Try to delete service without hostname %r' % badservice,
command=('service_del', [badservice], {}),
expected=errors.NotFound(
reason=u'%s: service not found' % badservice),
),
dict(
desc='Create %r' % fqdn1,
command=('host_add', [fqdn1],
dict(
description=u'Test host 1',
l=u'Undisclosed location 1',
force=True,
),
),
expected=dict(
value=fqdn1,
summary=u'Added host "%s"' % fqdn1,
result=dict(
dn=host1dn,
fqdn=[fqdn1],
description=[u'Test host 1'],
l=[u'Undisclosed location 1'],
krbprincipalname=[u'host/%s@%s' % (fqdn1, api.env.realm)],
krbcanonicalname=[u'host/%s@%s' % (fqdn1, api.env.realm)],
objectclass=objectclasses.host,
ipauniqueid=[fuzzy_uuid],
managedby_host=[u'%s' % fqdn1],
has_keytab=False,
has_password=False,
),
),
),
dict(
desc='Create %r' % fqdn2,
command=('host_add', [fqdn2],
dict(
description=u'Test host 2',
l=u'Undisclosed location 2',
force=True,
),
),
expected=dict(
value=fqdn2,
summary=u'Added host "%s"' % fqdn2,
result=dict(
dn=host2dn,
fqdn=[fqdn2],
description=[u'Test host 2'],
l=[u'Undisclosed location 2'],
krbprincipalname=[u'host/%s@%s' % (fqdn2, api.env.realm)],
krbcanonicalname=[u'host/%s@%s' % (fqdn2, api.env.realm)],
objectclass=objectclasses.host,
ipauniqueid=[fuzzy_uuid],
managedby_host=[u'%s' % fqdn2],
has_keytab=False,
has_password=False,
),
),
),
dict(
desc='Create %r' % fqdn3,
command=('host_add', [fqdn3],
dict(
description=u'Test host 3',
l=u'Undisclosed location 3',
force=True,
),
),
expected=dict(
value=fqdn3.lower(),
summary=u'Added host "%s"' % fqdn3.lower(),
result=dict(
dn=host3dn,
fqdn=[fqdn3.lower()],
description=[u'Test host 3'],
l=[u'Undisclosed location 3'],
krbprincipalname=[u'host/%s@%s' % (fqdn3.lower(), api.env.realm)],
krbcanonicalname=[u'host/%s@%s' % (
fqdn3.lower(), api.env.realm)],
objectclass=objectclasses.host,
ipauniqueid=[fuzzy_uuid],
managedby_host=[u'%s' % fqdn3.lower()],
has_keytab=False,
has_password=False,
),
),
),
dict(
desc='Create %r' % service1,
command=('service_add', [service1],
dict(
force=True,
),
),
expected=dict(
value=service1,
summary=u'Added service "%s"' % service1,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
objectclass=objectclasses.service,
ipauniqueid=[fuzzy_uuid],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Try to create duplicate %r' % service1,
command=('service_add', [service1],
dict(
force=True,
),
),
expected=errors.DuplicateEntry(
message=u'service with name "%s" already exists' % service1),
),
dict(
desc='Retrieve %r' % service1,
command=('service_show', [service1], {}),
expected=dict(
value=service1,
summary=None,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
has_keytab=False,
managedby_host=[fqdn1],
),
),
),
dict(
desc='Retrieve %r with all=True' % service1,
command=('service_show', [service1], dict(all=True)),
expected=dict(
value=service1,
summary=None,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
ipakrbprincipalalias=[service1],
krbcanonicalname=[service1],
objectclass=objectclasses.service,
ipauniqueid=[fuzzy_uuid],
managedby_host=[fqdn1],
has_keytab=False,
ipakrbrequirespreauth=True,
ipakrbokasdelegate=False,
ipakrboktoauthasdelegate=False,
krbpwdpolicyreference=[DN(
u'cn=Default Service Password Policy',
api.env.container_service,
api.env.basedn,
)],
),
),
),
dict(
desc='Allow admin to create keytab for %r' % service1,
command=('service_allow_create_keytab', [service1],
dict(user=u'admin'),
),
expected=dict(
completed=1,
failed=dict(
ipaallowedtoperform_write_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[]
)
),
result=dict(
dn=service1dn,
ipaallowedtoperform_write_keys_user=[u'admin'],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Retrieve %r with all=True and keytab allowed' % service1,
command=('service_show', [service1], dict(all=True)),
expected=dict(
value=service1,
summary=None,
result=dict(
dn=service1dn,
ipaallowedtoperform_write_keys_user=[u'admin'],
krbprincipalname=[service1],
ipakrbprincipalalias=[service1],
krbcanonicalname=[service1],
objectclass=objectclasses.service + [
u'ipaallowedoperations'
],
ipauniqueid=[fuzzy_uuid],
managedby_host=[fqdn1],
has_keytab=False,
ipakrbrequirespreauth=True,
ipakrbokasdelegate=False,
ipakrboktoauthasdelegate=False,
krbpwdpolicyreference=[DN(
u'cn=Default Service Password Policy',
api.env.container_service,
api.env.basedn,
)],
),
),
),
dict(
desc='Search for %r with members' % service1,
command=('service_find', [service1], {'no_members': False}),
expected=dict(
count=1,
truncated=False,
summary=u'1 service matched',
result=[
dict(
dn=service1dn,
ipaallowedtoperform_write_keys_user=[u'admin'],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
has_keytab=False,
),
],
),
),
dict(
desc='Disallow admin to create keytab for %r' % service1,
command=(
'service_disallow_create_keytab', [service1],
dict(user=u'admin'),
),
expected=dict(
completed=1,
failed=dict(
ipaallowedtoperform_write_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[]
)
),
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Search for %r' % service1,
command=('service_find', [service1], {}),
expected=dict(
count=1,
truncated=False,
summary=u'1 service matched',
result=[
dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
has_keytab=False,
),
],
),
),
dict(
desc='Search for %r with all=True' % service1,
command=('service_find', [service1], dict(all=True)),
expected=dict(
count=1,
truncated=False,
summary=u'1 service matched',
result=[
dict(
dn=service1dn,
krbprincipalname=[service1],
ipakrbprincipalalias=[service1],
krbcanonicalname=[service1],
objectclass=objectclasses.service + [
u'ipaallowedoperations'
],
ipauniqueid=[fuzzy_uuid],
has_keytab=False,
managedby_host=[fqdn1],
ipakrbrequirespreauth=True,
ipakrbokasdelegate=False,
ipakrboktoauthasdelegate=False,
krbpwdpolicyreference=[DN(
u'cn=Default Service Password Policy',
api.env.container_service,
api.env.basedn,
)],
),
],
),
),
dict(
desc='Add non-existent host to %r' % service1,
command=('service_add_host', [service1], dict(host=u'notfound')),
expected=dict(
failed=dict(managedby=dict(host=[(u'notfound', u'no such entry')])),
completed=0,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Remove non-existent host from %r' % service1,
command=('service_remove_host', [service1], dict(host=u'notfound')),
expected=dict(
failed=dict(managedby=dict(host=[(u'notfound', u'This entry is not a member')])),
completed=0,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Add host to %r' % service1,
command=('service_add_host', [service1], dict(host=fqdn2)),
expected=dict(
failed=dict(managedby=dict(host=[])),
completed=1,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1, fqdn2],
),
),
),
dict(
desc='Remove host from %r' % service1,
command=('service_remove_host', [service1], dict(host=fqdn2)),
expected=dict(
failed=dict(managedby=dict(host=[])),
completed=1,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Add mixed-case host to %r' % service1,
command=('service_add_host', [service1], dict(host=fqdn3)),
expected=dict(
failed=dict(managedby=dict(host=[])),
completed=1,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1, fqdn3.lower()],
),
),
),
dict(
desc='Remove mixed-case host from %r' % service1,
command=('service_remove_host', [service1], dict(host=fqdn3)),
expected=dict(
failed=dict(managedby=dict(host=[])),
completed=1,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Update %r with a random issuer certificate' % service1,
command=(
'service_mod',
[service1],
dict(usercertificate=base64.b64decode(randomissuercert))),
expected=dict(
value=service1,
summary=u'Modified service "%s"' % service1,
result=dict(
usercertificate=[base64.b64decode(randomissuercert)],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
valid_not_before=fuzzy_date,
valid_not_after=fuzzy_date,
subject=randomissuer,
serial_number=fuzzy_digits,
serial_number_hex=fuzzy_hex,
sha1_fingerprint=fuzzy_hash,
sha256_fingerprint=fuzzy_hash,
issuer=fuzzy_issuer,
),
),
),
dict(
desc='Update %r' % service1,
command=('service_mod', [service1], dict(usercertificate=servercert)),
expected=dict(
value=service1,
summary=u'Modified service "%s"' % service1,
result=dict(
usercertificate=[base64.b64decode(servercert)],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
valid_not_before=fuzzy_date,
valid_not_after=fuzzy_date,
subject=DN(('CN', api.env.host), subject_base()),
serial_number=fuzzy_digits,
serial_number_hex=fuzzy_hex,
sha1_fingerprint=fuzzy_hash,
sha256_fingerprint=fuzzy_hash,
issuer=fuzzy_issuer,
),
),
),
dict(
desc='Try to update %r with invalid ipakrbauthz data '
'combination' % service1,
command=('service_mod', [service1],
dict(ipakrbauthzdata=[u'MS-PAC', u'NONE'])),
expected=errors.ValidationError(name='ipakrbauthzdata',
error=u'NONE value cannot be combined with other PAC types')
),
dict(
desc='Update %r with valid ipakrbauthz data '
'combination' % service1,
command=('service_mod', [service1],
dict(ipakrbauthzdata=[u'MS-PAC'])),
expected=dict(
value=service1,
summary=u'Modified service "%s"' % service1,
result=dict(
usercertificate=[base64.b64decode(servercert)],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
ipakrbauthzdata=[u'MS-PAC'],
valid_not_before=fuzzy_date,
valid_not_after=fuzzy_date,
subject=DN(('CN', api.env.host), subject_base()),
serial_number=fuzzy_digits,
serial_number_hex=fuzzy_hex,
sha1_fingerprint=fuzzy_hash,
sha256_fingerprint=fuzzy_hash,
issuer=fuzzy_issuer,
),
),
),
dict(
desc='Retrieve %r to verify update' % service1,
command=('service_show', [service1], {}),
expected=dict(
value=service1,
summary=None,
result=dict(
dn=service1dn,
usercertificate=[base64.b64decode(servercert)],
krbprincipalname=[service1],
krbcanonicalname=[service1],
has_keytab=False,
managedby_host=[fqdn1],
ipakrbauthzdata=[u'MS-PAC'],
# These values come from the servercert that is in this
# test case.
valid_not_before=fuzzy_date,
valid_not_after=fuzzy_date,
subject=DN(('CN', api.env.host), subject_base()),
serial_number=fuzzy_digits,
serial_number_hex=fuzzy_hex,
sha1_fingerprint=fuzzy_hash,
sha256_fingerprint=fuzzy_hash,
issuer=fuzzy_issuer,
),
),
),
dict(
desc='Enable %r OK_AS_DELEGATE Kerberos ticket flag' % service1,
command=('service_mod', [service1], dict(ipakrbokasdelegate=True)),
expected=dict(
value=service1,
summary=u'Modified service "%s"' % service1,
result=dict(
usercertificate=[base64.b64decode(servercert)],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
ipakrbauthzdata=[u'MS-PAC'],
valid_not_before=fuzzy_date,
valid_not_after=fuzzy_date,
subject=DN(('CN', api.env.host), subject_base()),
serial_number=fuzzy_digits,
serial_number_hex=fuzzy_hex,
sha1_fingerprint=fuzzy_hash,
sha256_fingerprint=fuzzy_hash,
issuer=fuzzy_issuer,
krbticketflags=[u'1048704'],
ipakrbokasdelegate=True,
),
),
),
dict(
desc='Update %r Kerberos ticket flags with setattr' % service1,
command=('service_mod', [service1],
dict(setattr=[u'krbTicketFlags=1048577'])),
expected=dict(
value=service1,
summary=u'Modified service "%s"' % service1,
result=dict(
usercertificate=[base64.b64decode(servercert)],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
ipakrbauthzdata=[u'MS-PAC'],
valid_not_before=fuzzy_date,
valid_not_after=fuzzy_date,
subject=DN(('CN', api.env.host), subject_base()),
serial_number=fuzzy_digits,
serial_number_hex=fuzzy_hex,
sha1_fingerprint=fuzzy_hash,
sha256_fingerprint=fuzzy_hash,
issuer=fuzzy_issuer,
krbticketflags=[u'1048577'],
),
),
),
dict(
desc='Disable %r OK_AS_DELEGATE Kerberos ticket flag' % service1,
command=('service_mod', [service1], dict(ipakrbokasdelegate=False)),
expected=dict(
value=service1,
summary=u'Modified service "%s"' % service1,
result=dict(
usercertificate=[base64.b64decode(servercert)],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
ipakrbauthzdata=[u'MS-PAC'],
valid_not_before=fuzzy_date,
valid_not_after=fuzzy_date,
subject=DN(('CN', api.env.host), subject_base()),
serial_number=fuzzy_digits,
serial_number_hex=fuzzy_hex,
sha1_fingerprint=fuzzy_hash,
sha256_fingerprint=fuzzy_hash,
issuer=fuzzy_issuer,
krbticketflags=[u'1'],
ipakrbokasdelegate=False,
),
),
),
dict(
desc='Delete %r' % service1,
command=('service_del', [service1], {}),
expected=dict(
value=[service1],
summary=u'Deleted service "%s"' % service1,
result=dict(failed=[]),
),
),
dict(
desc='Try to retrieve non-existent %r' % service1,
command=('service_show', [service1], {}),
expected=errors.NotFound(
reason=u'%s: service not found' % service1),
),
dict(
desc='Try to update non-existent %r' % service1,
command=('service_mod', [service1], dict(usercertificate=servercert)),
expected=errors.NotFound(
reason=u'%s: service not found' % service1),
),
dict(
desc='Try to update service without hostname %r' % badservice,
command=(
'service_mod',
[badservice],
dict(usercertificate=servercert)
),
expected=errors.NotFound(
reason=u'%s: service not found' % badservice),
),
dict(
desc='Try to delete non-existent %r' % service1,
command=('service_del', [service1], {}),
expected=errors.NotFound(
reason=u'%s: service not found' % service1),
),
dict(
desc='Create service with malformed principal "foo"',
command=('service_add', [u'foo'], {}),
expected=errors.ValidationError(
name='canonical_principal',
error='Service principal is required')
),
dict(
desc='Create service with bad realm "HTTP/foo@FOO.NET"',
command=('service_add', [u'HTTP/foo@FOO.NET'], {}),
expected=errors.RealmMismatch(),
),
dict(
desc='Create a host service %r' % hostprincipal1,
command=('service_add', [hostprincipal1], {}),
expected=errors.HostService()
),
# These tests will only succeed when running against lite-server.py
# on same box as IPA install.
dict(
desc='Delete the current host (master?) %s HTTP service, should be caught' % api.env.host,
command=('service_del', ['HTTP/%s' % api.env.host], {}),
expected=errors.ValidationError(
name='principal',
error='HTTP/%s@%s is required by the IPA master' % (
api.env.host,
api.env.realm
)
),
),
# DN is case insensitive, see https://pagure.io/freeipa/issue/8308
dict(
desc=(
'Delete the current host (master?) %s HTTP service, should '
'be caught'
) % api.env.host,
command=('service_del', ['http/%s' % api.env.host], {}),
expected=errors.ValidationError(
name='principal',
error='http/%s@%s is required by the IPA master' % (
api.env.host,
api.env.realm
)
),
),
dict(
desc='Delete the current host (master?) %s ldap service, should be caught' % api.env.host,
command=('service_del', ['ldap/%s' % api.env.host], {}),
expected=errors.ValidationError(
name='principal',
error='ldap/%s@%s is required by the IPA master' % (
api.env.host,
api.env.realm
)
),
),
dict(
desc=('Delete the current host (master?) %s dns service,'
' should be caught' % api.env.host),
command=('service_del', ['DNS/%s' % api.env.host], {}),
expected=errors.ValidationError(
name='principal',
error='DNS/%s@%s is required by the IPA master' % (
api.env.host,
api.env.realm
)
),
),
dict(
desc='Disable the current host (master?) %s HTTP service, should be caught' % api.env.host,
command=('service_disable', ['HTTP/%s' % api.env.host], {}),
expected=errors.ValidationError(
name='principal',
error='HTTP/%s@%s is required by the IPA master' % (
api.env.host,
api.env.realm
)
),
),
dict(
desc=(
'Disable the current host (master?) %s HTTP service, should '
'be caught'
) % api.env.host,
command=('service_disable', ['http/%s' % api.env.host], {}),
expected=errors.ValidationError(
name='principal',
error='http/%s@%s is required by the IPA master' % (
api.env.host,
api.env.realm
)
),
),
dict(
desc='Disable the current host (master?) %s ldap service, should be caught' % api.env.host,
command=('service_disable', ['ldap/%s' % api.env.host], {}),
expected=errors.ValidationError(
name='principal',
error='ldap/%s@%s is required by the IPA master' % (
api.env.host,
api.env.realm
)
),
),
dict(
desc=('Disable the current host (master?) %s dns service,'
' should be caught' % api.env.host),
command=('service_disable', ['DNS/%s' % api.env.host], {}),
expected=errors.ValidationError(
name='principal',
error='DNS/%s@%s is required by the IPA master' % (
api.env.host,
api.env.realm
)
),
),
# Create a service disconnected from any host
dict(
desc='Try to create service %r without any host' % d_service,
command=('service_add', [d_service_no_realm],
dict(force=True, skip_host_check=True),),
expected=dict(
value=d_service,
summary=u'Added service "%s"' % d_service,
result=dict(
dn=d_servicedn,
krbprincipalname=[d_service],
krbcanonicalname=[d_service],
objectclass=objectclasses.service,
ipauniqueid=[fuzzy_uuid],
),
),
),
]
@pytest.mark.tier1
class test_service_in_role(Declarative):
cleanup_commands = [
('host_del', [fqdn1], {}),
('service_del', [service1], {}),
('role_del', [role1], {}),
]
tests = [
dict(
desc='Create %r' % fqdn1,
command=('host_add', [fqdn1],
dict(
description=u'Test host 1',
l=u'Undisclosed location 1',
force=True,
),
),
expected=dict(
value=fqdn1,
summary=u'Added host "%s"' % fqdn1,
result=dict(
dn=host1dn,
fqdn=[fqdn1],
description=[u'Test host 1'],
l=[u'Undisclosed location 1'],
krbprincipalname=[u'host/%s@%s' % (fqdn1, api.env.realm)],
krbcanonicalname=[u'host/%s@%s' % (fqdn1, api.env.realm)],
objectclass=objectclasses.host,
ipauniqueid=[fuzzy_uuid],
managedby_host=[u'%s' % fqdn1],
has_keytab=False,
has_password=False,
),
),
),
dict(
desc='Create %r' % service1,
command=('service_add', [service1_no_realm], dict(force=True)),
expected=dict(
value=service1,
summary=u'Added service "%s"' % service1,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
objectclass=objectclasses.service,
ipauniqueid=[fuzzy_uuid],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Create %r' % role1,
command=('role_add', [role1], dict(description=u'role desc 1')),
expected=dict(
value=role1,
summary=u'Added role "%s"' % role1,
result=dict(
dn=role1_dn,
cn=[role1],
description=[u'role desc 1'],
objectclass=objectclasses.role,
),
),
),
dict(
desc='Add %r to %r' % (service1, role1),
command=('role_add_member', [role1],
dict(service=service1_no_realm)),
expected=dict(
failed=dict(
member=dict(
host=[],
group=[],
hostgroup=[],
service=[],
user=[],
idoverrideuser=[],
),
),
completed=1,
result=dict(
dn=role1_dn,
cn=[role1],
description=[u'role desc 1'],
member_service=[service1],
),
),
),
dict(
desc='Verify %r is member of %r' % (service1, role1),
command=('service_show', [service1_no_realm], {}),
expected=dict(
value=service1,
summary=None,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
memberof_role=[role1],
has_keytab=False,
),
),
),
dict(
desc='Verify %r has member %r' % (role1, service1),
command=('role_show', [role1], {}),
expected=dict(
value=role1,
summary=None,
result=dict(
dn=role1_dn,
cn=[role1],
description=[u'role desc 1'],
member_service=[service1],
),
),
),
]
@pytest.mark.tier1
class test_service_allowed_to(Declarative):
cleanup_commands = [
('user_del', [user1], {}),
('user_del', [user2], {}),
('service_del', [d_service], {}),
('group_del', [group1], {}),
('group_del', [group2], {}),
('host_del', [fqdn1], {}),
('service_del', [service1], {}),
('hostgroup_del', [hostgroup1], {}),
]
tests = [
# prepare entries
dict(
desc='Create %r' % user1,
command=(
'user_add', [], dict(givenname=u'Test', sn=u'User1')
),
expected=dict(
value=user1,
summary=u'Added user "%s"' % user1,
result=get_user_result(user1, u'Test', u'User1', 'add'),
),
),
dict(
desc='Create %r' % user2,
command=(
'user_add', [], dict(givenname=u'Test', sn=u'User2')
),
expected=dict(
value=user2,
summary=u'Added user "%s"' % user2,
result=get_user_result(user2, u'Test', u'User2', 'add'),
),
),
dict(
desc='Create group: %r' % group1,
command=(
'group_add', [group1], dict()
),
expected=dict(
value=group1,
summary=u'Added group "%s"' % group1,
result=dict(
cn=[group1],
objectclass=fuzzy_set_optional_oc(
objectclasses.posixgroup, 'ipantgroupattrs'),
ipauniqueid=[fuzzy_uuid],
gidnumber=[fuzzy_digits],
dn=group1_dn
),
),
),
# Create a service disconnected from any host
dict(
desc='Try to create service %r without any host' % d_service,
command=('service_add', [d_service],
dict(force=True, skip_host_check=True)),
expected=dict(
value=d_service,
summary=u'Added service "%s"' % d_service,
result=dict(
dn=d_servicedn,
krbprincipalname=[d_service],
krbcanonicalname=[d_service],
objectclass=objectclasses.service,
ipauniqueid=[fuzzy_uuid],
),
),
),
dict(
desc='Add service %r to a group: %r' % (d_service, group1),
command=('group_add_member', [group1],
dict(service=[d_service_no_realm])),
expected=dict(
completed=1,
failed=dict(member=dict(group=[],
service=[],
user=[],
idoverrideuser=[])),
result=dict(
cn=[group1],
gidnumber=[fuzzy_digits],
dn=group1_dn,
member_service=[d_service],
),
),
),
dict(
desc='Create group: %r' % group2,
command=(
'group_add', [group2], dict()
),
expected=dict(
value=group2,
summary=u'Added group "%s"' % group2,
result=dict(
cn=[group2],
objectclass=fuzzy_set_optional_oc(
objectclasses.posixgroup, 'ipantgroupattrs'),
ipauniqueid=[fuzzy_uuid],
gidnumber=[fuzzy_digits],
dn=group2_dn
),
),
),
dict(
desc='Create %r' % fqdn1,
command=(
'host_add', [fqdn1],
dict(
description=u'Test host 1',
l=u'Undisclosed location 1',
force=True,
),
),
expected=dict(
value=fqdn1,
summary=u'Added host "%s"' % fqdn1,
result=dict(
dn=host1dn,
fqdn=[fqdn1],
description=[u'Test host 1'],
l=[u'Undisclosed location 1'],
krbprincipalname=[u'host/%s@%s' % (fqdn1, api.env.realm)],
krbcanonicalname=[u'host/%s@%s' % (fqdn1, api.env.realm)],
objectclass=objectclasses.host,
ipauniqueid=[fuzzy_uuid],
managedby_host=[u'%s' % fqdn1],
has_keytab=False,
has_password=False,
),
),
),
dict(
desc='Create %r' % hostgroup1,
command=('hostgroup_add', [hostgroup1],
dict(description=u'Test hostgroup 1')
),
expected=dict(
value=hostgroup1,
summary=u'Added hostgroup "testhostgroup1"',
result=dict(
dn=hostgroup1_dn,
cn=[hostgroup1],
objectclass=objectclasses.hostgroup,
description=[u'Test hostgroup 1'],
ipauniqueid=[fuzzy_uuid],
mepmanagedentry=[DN(('cn',hostgroup1),('cn','ng'),('cn','alt'),
api.env.basedn)],
),
),
),
dict(
desc='Create %r' % service1,
command=('service_add', [service1_no_realm], dict(force=True)),
expected=dict(
value=service1,
summary=u'Added service "%s"' % service1,
result=dict(
dn=service1dn,
krbprincipalname=[service1],
krbcanonicalname=[service1],
objectclass=objectclasses.service,
ipauniqueid=[fuzzy_uuid],
managedby_host=[fqdn1],
),
),
),
# verify
dict(
desc='Allow %r to a retrieve keytab of %r' % (user1, service1),
command=('service_allow_retrieve_keytab', [service1],
dict(user=user1)),
expected=dict(
failed=dict(
ipaallowedtoperform_read_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[],
),
),
completed=1,
result=dict(
dn=service1dn,
ipaallowedtoperform_read_keys_user=[user1],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Duplicate add: user %r' % (user1),
command=('service_allow_retrieve_keytab', [service1],
dict(user=user1)),
expected=dict(
failed=dict(
ipaallowedtoperform_read_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[[user1, u'This entry is already a member']],
),
),
completed=0,
result=dict(
dn=service1dn,
ipaallowedtoperform_read_keys_user=[user1],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Allow %r, %r, %r to a retrieve keytab of %r' % (
group1, group2, fqdn1, service1),
command=('service_allow_retrieve_keytab', [service1],
dict(group=[group1, group2], host=[fqdn1],
hostgroup=[hostgroup1])),
expected=dict(
failed=dict(
ipaallowedtoperform_read_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[],
),
),
completed=4,
result=dict(
dn=service1dn,
ipaallowedtoperform_read_keys_user=[user1],
ipaallowedtoperform_read_keys_group=[group1, group2],
ipaallowedtoperform_read_keys_host=[fqdn1],
ipaallowedtoperform_read_keys_hostgroup=[hostgroup1],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Invalid removal of retrieve keytab %r' % (user2),
command=('service_disallow_retrieve_keytab', [service1],
dict(user=[user2])),
expected=dict(
failed=dict(
ipaallowedtoperform_read_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[[user2, u'This entry is not a member']],
),
),
completed=0,
result=dict(
dn=service1dn,
ipaallowedtoperform_read_keys_user=[user1],
ipaallowedtoperform_read_keys_group=[group1, group2],
ipaallowedtoperform_read_keys_host=[fqdn1],
ipaallowedtoperform_read_keys_hostgroup=[hostgroup1],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Removal of retrieve keytab %r' % (group2),
command=('service_disallow_retrieve_keytab', [service1],
dict(group=[group2])),
expected=dict(
failed=dict(
ipaallowedtoperform_read_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[],
),
),
completed=1,
result=dict(
dn=service1dn,
ipaallowedtoperform_read_keys_user=[user1],
ipaallowedtoperform_read_keys_group=[group1],
ipaallowedtoperform_read_keys_host=[fqdn1],
ipaallowedtoperform_read_keys_hostgroup=[hostgroup1],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Allow %r, %r, %r to a create keytab of %r' % (
group1, user1, fqdn1, service1),
command=('service_allow_create_keytab', [service1],
dict(group=[group1, group2], user=[user1], host=[fqdn1],
hostgroup=[hostgroup1])),
expected=dict(
failed=dict(
ipaallowedtoperform_write_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[],
),
),
completed=5,
result=dict(
dn=service1dn,
ipaallowedtoperform_read_keys_user=[user1],
ipaallowedtoperform_read_keys_group=[group1],
ipaallowedtoperform_read_keys_host=[fqdn1],
ipaallowedtoperform_read_keys_hostgroup=[hostgroup1],
ipaallowedtoperform_write_keys_user=[user1],
ipaallowedtoperform_write_keys_group=[group1, group2],
ipaallowedtoperform_write_keys_host=[fqdn1],
ipaallowedtoperform_write_keys_hostgroup=[hostgroup1],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Duplicate add: %r, %r' % (user1, group1),
command=('service_allow_create_keytab', [service1],
dict(group=[group1], user=[user1], host=[fqdn1],
hostgroup=[hostgroup1])),
expected=dict(
failed=dict(
ipaallowedtoperform_write_keys=dict(
group=[[group1, u'This entry is already a member']],
host=[[fqdn1, u'This entry is already a member']],
user=[[user1, u'This entry is already a member']],
hostgroup=[[hostgroup1, u'This entry is already a member']],
),
),
completed=0,
result=dict(
dn=service1dn,
ipaallowedtoperform_read_keys_user=[user1],
ipaallowedtoperform_read_keys_group=[group1],
ipaallowedtoperform_read_keys_host=[fqdn1],
ipaallowedtoperform_read_keys_hostgroup=[hostgroup1],
ipaallowedtoperform_write_keys_user=[user1],
ipaallowedtoperform_write_keys_group=[group1, group2],
ipaallowedtoperform_write_keys_host=[fqdn1],
ipaallowedtoperform_write_keys_hostgroup=[hostgroup1],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Invalid removal of create keytab %r' % (user2),
command=('service_disallow_create_keytab', [service1],
dict(user=[user2])),
expected=dict(
failed=dict(
ipaallowedtoperform_write_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[[user2, u'This entry is not a member']],
),
),
completed=0,
result=dict(
dn=service1dn,
ipaallowedtoperform_read_keys_user=[user1],
ipaallowedtoperform_read_keys_group=[group1],
ipaallowedtoperform_read_keys_host=[fqdn1],
ipaallowedtoperform_read_keys_hostgroup=[hostgroup1],
ipaallowedtoperform_write_keys_user=[user1],
ipaallowedtoperform_write_keys_group=[group1, group2],
ipaallowedtoperform_write_keys_host=[fqdn1],
ipaallowedtoperform_write_keys_hostgroup=[hostgroup1],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Removal of create keytab %r' % (group2),
command=('service_disallow_create_keytab', [service1],
dict(group=[group2])),
expected=dict(
failed=dict(
ipaallowedtoperform_write_keys=dict(
group=[],
host=[],
hostgroup=[],
user=[],
),
),
completed=1,
result=dict(
dn=service1dn,
ipaallowedtoperform_read_keys_user=[user1],
ipaallowedtoperform_read_keys_group=[group1],
ipaallowedtoperform_read_keys_host=[fqdn1],
ipaallowedtoperform_read_keys_hostgroup=[hostgroup1],
ipaallowedtoperform_write_keys_user=[user1],
ipaallowedtoperform_write_keys_group=[group1],
ipaallowedtoperform_write_keys_host=[fqdn1],
ipaallowedtoperform_write_keys_hostgroup=[hostgroup1],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Presence of ipaallowedtoperform in show output',
command=('service_show', [service1_no_realm], {}),
expected=dict(
value=service1,
summary=None,
result=dict(
dn=service1dn,
has_keytab=False,
ipaallowedtoperform_read_keys_user=[user1],
ipaallowedtoperform_read_keys_group=[group1],
ipaallowedtoperform_read_keys_host=[fqdn1],
ipaallowedtoperform_read_keys_hostgroup=[hostgroup1],
ipaallowedtoperform_write_keys_user=[user1],
ipaallowedtoperform_write_keys_group=[group1],
ipaallowedtoperform_write_keys_host=[fqdn1],
ipaallowedtoperform_write_keys_hostgroup=[hostgroup1],
krbprincipalname=[service1],
krbcanonicalname=[service1],
managedby_host=[fqdn1],
),
),
),
dict(
desc='Presence of ipaallowedtoperform in mod output',
command=(
'service_mod', [service1_no_realm],
dict(ipakrbokasdelegate=True)),
expected=dict(
value=service1,
summary=u'Modified service "%s"' % service1,
result=dict(
ipaallowedtoperform_read_keys_user=[user1],
ipaallowedtoperform_read_keys_group=[group1],
ipaallowedtoperform_read_keys_host=[fqdn1],
ipaallowedtoperform_read_keys_hostgroup=[hostgroup1],
ipaallowedtoperform_write_keys_user=[user1],
ipaallowedtoperform_write_keys_group=[group1],
ipaallowedtoperform_write_keys_host=[fqdn1],
ipaallowedtoperform_write_keys_hostgroup=[hostgroup1],
ipakrbokasdelegate=True,
krbprincipalname=[service1],
krbcanonicalname=[service1],
krbticketflags=[u'1048704'],
managedby_host=[fqdn1],
),
),
),
]
@pytest.fixture(scope='function')
def indicators_host(request):
tracker = HostTracker(name=u'testhost1', fqdn=fqdn1)
return tracker.make_fixture(request)
@pytest.fixture(scope='function')
def this_host(request):
"""Fixture for the current master"""
tracker = HostTracker(name=api.env.host.partition('.')[0],
fqdn=api.env.host)
tracker.exists = True
return tracker
@pytest.fixture(scope='function')
def indicators_service(request):
tracker = ServiceTracker(
name=u'SRV1', host_fqdn=fqdn1, options={
u'krbprincipalauthind': u'otp'})
return tracker.make_fixture(request)
@pytest.mark.tier1
class TestAuthenticationIndicators(XMLRPC_test):
def test_create_service_with_otp_indicator(
self, indicators_host, indicators_service):
indicators_host.create()
indicators_service.create()
def test_adding_all_indicators(
self, indicators_host, indicators_service):
indicators_host.create()
indicators_service.create()
indicators_service.update(
updates={
u'krbprincipalauthind': [
u'otp', u'radius', u'pkinit', u'hardened', u'idp',
u'passkey',
]
}
)
def test_update_indicator(self, indicators_host, indicators_service):
indicators_host.create()
indicators_service.create()
indicators_service.update(
updates={u'krbprincipalauthind': u'radius'},
expected_updates={u'krbprincipalauthind': [u'radius']}
)
def test_update_indicator_internal_service(self, this_host):
command = this_host.make_command('service_mod',
'ldap/' + this_host.fqdn,
**dict(krbprincipalauthind='otp'))
with raises_exact(errors.ValidationError(
name='krbprincipalauthind',
error=u'authentication indicators not allowed '
'in service "ldap"'
)):
command()
@pytest.fixture(scope='function')
def managing_host(request):
tracker = HostTracker(name=u'managinghost2', fqdn=fqdn2)
return tracker.make_fixture(request)
@pytest.fixture(scope='function')
def managed_service(request):
tracker = ServiceTracker(
name=u'managed-service', host_fqdn=fqdn2)
return tracker.make_fixture(request)
@pytest.mark.tier1
class TestManagedServices(XMLRPC_test):
def test_managed_service(
self, managing_host, managed_service):
""" Add a host and then add a service as a host
Finally, remove the service as a host """
managing_host.ensure_exists()
with host_keytab(managing_host.name) as keytab_filename:
with change_principal(managing_host.attrs['krbcanonicalname'][0],
keytab=keytab_filename):
managed_service.create()
managed_service.delete()
| 60,456
|
Python
|
.py
| 1,510
| 24.101325
| 103
| 0.474361
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,486
|
test_idviews_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_idviews_plugin.py
|
# Authors:
# Tomas Babej <tbabej@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/>.
"""
Test the `ipalib.plugins.idviews` module.
"""
import re
import six
from ipalib import api, errors
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import (Declarative, uuid_re,
fuzzy_set_optional_oc,
fuzzy_uuid, fuzzy_digits)
from ipatests.test_xmlrpc.test_user_plugin import get_user_result
from ipatests.test_xmlrpc.test_group_plugin import get_group_dn
from ipatests.util import Fuzzy
from ipapython.dn import DN
import pytest
if six.PY3:
unicode = str
idview1 = u'idview1'
idview2 = u'idview2'
hostgroup1 = u'hostgroup1'
hostgroup2 = u'hostgroup2'
idoverrideuser1 = u'testuser'
idoverridegroup1 = u'testgroup'
idoverrideuser_removed = u'testuser-removed'
idoverridegroup_removed = u'testgroup-removed'
nonexistentuser = u'nonexistentuser'
nonexistentgroup = u'nonexistentgroup'
host1 = u'testhost1'
host2 = u'testhost2'
host3 = u'testhost3'
host4 = u'testhost4'
sshpubkey = (u'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDGAX3xAeLeaJggwTqMjxNwa6X'
'HBUAikXPGMzEpVrlLDCZtv00djsFTBi38PkgxBJVkgRWMrcBsr/35lq7P6w8KGI'
'wA8GI48Z0qBS2NBMJ2u9WQ2hjLN6GdMlo77O0uJY3251p12pCVIS/bHRSq8kHO2'
'No8g7KA9fGGcagPfQH+ee3t7HUkpbQkFTmbPPN++r3V8oVUk5LxbryB3UIIVzNm'
'cSIn3JrXynlvui4MixvrtX6zx+O/bBo68o8/eZD26QrahVbA09fivrn/4h3TM01'
'9Eu/c2jOdckfU3cHUV/3Tno5d6JicibyaoDDK7S/yjdn5jhaz8MSEayQvFkZkiF'
'0L public key test')
sshpubkeyfp = (u'SHA256:cStA9o5TRSARbeketEOooMUMSWRSsArIAXloBZ4vNsE '
'public key test (ssh-rsa)')
# Test helpers
def get_idview_dn(name):
return u"cn={name},cn=views,cn=accounts,{suffix}".format(
name=name,
suffix=api.env.basedn,
)
def get_override_dn(view, anchor):
return Fuzzy(u"ipaanchoruuid=:IPA:{domain}:{uuid},"
"cn={view},"
"cn=views,cn=accounts,{suffix}"
.format(uuid=uuid_re,
domain=re.escape(unicode(api.env.domain)),
view=re.escape(view),
suffix=re.escape(unicode(api.env.basedn)),
))
def get_fqdn(host):
return u'{short}.{domain}'.format(short=host, domain=api.env.domain)
def get_host_principal(host):
return u'host/%s@%s' % (get_fqdn(host), api.env.realm)
def get_host_dn(host):
return DN(('fqdn', get_fqdn(host)),
('cn', 'computers'),
('cn', 'accounts'),
api.env.basedn)
def get_hostgroup_dn(hostgroup):
return DN(('cn', hostgroup),
('cn', 'hostgroups'),
('cn', 'accounts'),
api.env.basedn)
def get_hostgroup_netgroup_dn(hostgroup):
return DN(('cn', hostgroup),
('cn', 'ng'),
('cn', 'alt'),
api.env.basedn)
@pytest.mark.tier1
class test_idviews(Declarative):
cleanup_commands = [
('idview_del', [idview1, idview2], {'continue': True}),
('host_del', [host1, host2, host3, host4], {'continue': True}),
('hostgroup_del', [hostgroup1, hostgroup2], {'continue': True}),
('idview_del', [idview1], {'continue': True}),
('user_del', [idoverrideuser1, idoverrideuser_removed], {'continue': True}),
('group_del', [idoverridegroup1, idoverridegroup_removed], {'continue': True}),
]
tests = [
# ID View object management
dict(
desc='Try to retrieve non-existent ID View "%s"' % idview1,
command=('idview_show', [idview1], {}),
expected=errors.NotFound(
reason=u'%s: ID View not found' % idview1
),
),
dict(
desc='Try to update non-existent ID View "%s"' % idview1,
command=('idview_mod', [idview1], dict(description=u'description')),
expected=errors.NotFound(
reason=u'%s: ID View not found' % idview1
),
),
dict(
desc='Try to delete non-existent ID View "%s"' % idview1,
command=('idview_del', [idview1], {}),
expected=errors.NotFound(
reason=u'%s: ID View not found' % idview1
),
),
dict(
desc='Try to rename non-existent ID View "%s"' % idview1,
command=('idview_mod', [idview1], dict(setattr=u'cn=renamedview')),
expected=errors.NotFound(
reason=u'%s: ID View not found' % idview1
),
),
dict(
desc='Create ID View "%s"' % idview1,
command=(
'idview_add',
[idview1],
{}
),
expected=dict(
value=idview1,
summary=u'Added ID View "%s"' % idview1,
result=dict(
dn=get_idview_dn(idview1),
objectclass=objectclasses.idview,
cn=[idview1]
)
),
),
dict(
desc='Try to create duplicate ID View "%s"' % idview1,
command=(
'idview_add',
[idview1],
{}
),
expected=errors.DuplicateEntry(
message=u'ID View with name "%s" already exists' % idview1
),
),
# Create some users and groups for id override object management tests
dict(
desc='Create "%s"' % idoverrideuser1,
command=(
'user_add',
[idoverrideuser1],
dict(
givenname=u'Test',
sn=u'User1',
)
),
expected=dict(
value=idoverrideuser1,
summary=u'Added user "%s"' % idoverrideuser1,
result=get_user_result(
idoverrideuser1,
u'Test',
u'User1',
'add',
objectclass=fuzzy_set_optional_oc(
objectclasses.user, 'ipantuserattrs'),
),
),
),
dict(
desc='Create group %r' % idoverridegroup1,
command=(
'group_add',
[idoverridegroup1],
dict(description=u'Test desc 1')
),
expected=dict(
value=idoverridegroup1,
summary=u'Added group "%s"' % idoverridegroup1,
result=dict(
cn=[idoverridegroup1],
description=[u'Test desc 1'],
objectclass=fuzzy_set_optional_oc(
objectclasses.posixgroup, 'ipantgroupattrs'),
ipauniqueid=[fuzzy_uuid],
gidnumber=[fuzzy_digits],
dn=get_group_dn(idoverridegroup1),
),
),
),
# ID override object management negative tests for nonexisting objects
dict(
desc='Try to retrieve non-existent User ID override '
'for non-existent object "%s"' % nonexistentuser,
command=('idoverrideuser_show', [idview1, nonexistentuser], {}),
expected=errors.NotFound(
reason="%s: user not found" % nonexistentuser
),
),
dict(
desc='Try to update non-existent User ID override '
'for non-existent object "%s"' % nonexistentuser,
command=('idoverrideuser_mod',
[idview1, nonexistentuser],
dict(uid=u'randomuser')),
expected=errors.NotFound(
reason="%s: user not found" % nonexistentuser
),
),
dict(
desc='Try to delete non-existent User ID override '
'for non-existent object "%s"' % nonexistentuser,
command=('idoverrideuser_del',
[idview1, nonexistentuser],
{}),
expected=errors.NotFound(
reason="%s: user not found" % nonexistentuser
),
),
dict(
desc='Try to rename non-existent User ID override '
'for non-existent object "%s"' % nonexistentuser,
command=('idoverrideuser_mod',
[idview1, nonexistentuser],
dict(setattr=u'ipaanchoruuid=:IPA:dom:renamedoverride')),
expected=errors.NotFound(
reason="%s: user not found" % nonexistentuser
),
),
dict(
desc='Try to retrieve non-existent Group ID override '
'for non-existent object "%s"' % nonexistentgroup,
command=('idoverridegroup_show', [idview1, nonexistentgroup], {}),
expected=errors.NotFound(
reason="%s: group not found" % nonexistentgroup
),
),
dict(
desc='Try to update non-existent Group ID override '
'for non-existent object "%s"' % nonexistentgroup,
command=('idoverridegroup_mod',
[idview1, nonexistentgroup],
dict(cn=u'randomnewname')),
expected=errors.NotFound(
reason="%s: group not found" % nonexistentgroup
),
),
dict(
desc='Try to delete non-existent Gruop ID override '
'for non-existent object "%s"' % nonexistentgroup,
command=('idoverridegroup_del',
[idview1, nonexistentgroup],
{}),
expected=errors.NotFound(
reason="%s: group not found" % nonexistentgroup
),
),
dict(
desc='Try to rename non-existent Group ID override '
'for non-existent object "%s"' % nonexistentgroup,
command=('idoverridegroup_mod',
[idview1, nonexistentgroup],
dict(setattr=u'ipaanchoruuid=:IPA:dom:renamedoverride')),
expected=errors.NotFound(
reason="%s: group not found" % nonexistentgroup
),
),
# ID override object management for existing objects
dict(
desc='Try to retrieve non-existent User ID override "%s"'
% idoverrideuser1,
command=('idoverrideuser_show', [idview1, idoverrideuser1], {}),
expected=errors.NotFound(
reason=u'%s: User ID override not found' % idoverrideuser1
),
),
dict(
desc='Try to update non-existent User ID override "%s"'
% idoverrideuser1,
command=('idoverrideuser_mod',
[idview1, idoverrideuser1],
dict(uid=u'randomuser')),
expected=errors.NotFound(reason=u'no such entry'),
),
dict(
desc='Try to delete non-existent User ID override "%s"'
% idoverrideuser1,
command=('idoverrideuser_del',
[idview1, idoverrideuser1],
{}),
expected=errors.NotFound(
reason=u'%s: User ID override not found' % idoverrideuser1
),
),
dict(
desc='Try to rename non-existent User ID override "%s"'
% idoverrideuser1,
command=('idoverrideuser_mod',
[idview1, idoverrideuser1],
dict(setattr=u'ipaanchoruuid=:IPA:dom:renamedoverride')),
expected=errors.NotFound(reason=u'no such entry'),
),
dict(
desc='Try to retrieve non-existent Group ID override "%s"'
% idoverridegroup1,
command=('idoverridegroup_show', [idview1, idoverridegroup1], {}),
expected=errors.NotFound(
reason=u'%s: Group ID override not found' % idoverridegroup1
),
),
dict(
desc='Try to update non-existent Group ID override "%s"'
% idoverridegroup1,
command=('idoverridegroup_mod',
[idview1, idoverridegroup1],
dict(cn=u'randomnewname')),
expected=errors.NotFound(
reason=u'%s: Group ID override not found' % idoverridegroup1
),
),
dict(
desc='Try to delete non-existent Gruop ID override "%s"'
% idoverridegroup1,
command=('idoverridegroup_del',
[idview1, idoverridegroup1],
{}),
expected=errors.NotFound(
reason=u'%s: Group ID override not found' % idoverridegroup1
),
),
dict(
desc='Try to rename non-existent Group ID override "%s"'
% idoverridegroup1,
command=('idoverridegroup_mod',
[idview1, idoverridegroup1],
dict(setattr=u'ipaanchoruuid=:IPA:dom:renamedoverride')),
expected=errors.NotFound(
reason=u'%s: Group ID override not found' % idoverridegroup1
),
),
# ID override tests
dict(
desc='Create User ID override "%s"' % idoverrideuser1,
command=(
'idoverrideuser_add',
[idview1, idoverrideuser1],
dict(description=u'description')
),
expected=dict(
value=idoverrideuser1,
summary=u'Added User ID override "%s"' % idoverrideuser1,
result=dict(
dn=get_override_dn(idview1, idoverrideuser1),
objectclass=objectclasses.idoverrideuser,
ipaanchoruuid=[idoverrideuser1],
ipaoriginaluid=[idoverrideuser1],
description=[u'description']
)
),
),
dict(
desc='Try to create duplicate ID override "%s"' % idoverrideuser1,
command=(
'idoverrideuser_add',
[idview1, idoverrideuser1],
dict(description=u'description')
),
expected=errors.DuplicateEntry(
message=(u'User ID override with name "%s" '
'already exists' % idoverrideuser1)
),
),
dict(
desc='Modify User ID override "%s" to override uidnumber'
% idoverrideuser1,
command=(
'idoverrideuser_mod',
[idview1, idoverrideuser1],
dict(uidnumber=12345, all=True)
),
expected=dict(
value=idoverrideuser1,
summary=u'Modified an User ID override "%s"' % idoverrideuser1,
result=dict(
dn=get_override_dn(idview1, idoverrideuser1),
objectclass=objectclasses.idoverrideuser,
ipaanchoruuid=[idoverrideuser1],
ipaoriginaluid=[idoverrideuser1],
description=[u'description'],
uidnumber=[u'12345'],
)
),
),
dict(
desc='Modify ID override "%s" to not override '
'uidnumber' % idoverrideuser1,
command=(
'idoverrideuser_mod',
[idview1, idoverrideuser1],
dict(uidnumber=None, all=True)
),
expected=dict(
value=idoverrideuser1,
summary=u'Modified an User ID override "%s"' % idoverrideuser1,
result=dict(
dn=get_override_dn(idview1, idoverrideuser1),
objectclass=objectclasses.idoverrideuser,
ipaanchoruuid=[idoverrideuser1],
ipaoriginaluid=[idoverrideuser1],
description=[u'description']
)
),
),
dict(
desc='Modify ID override "%s" to override login' % idoverrideuser1,
command=(
'idoverrideuser_mod',
[idview1, idoverrideuser1],
dict(uid=u'newlogin', all=True)
),
expected=dict(
value=idoverrideuser1,
summary=u'Modified an User ID override "%s"' % idoverrideuser1,
result=dict(
dn=get_override_dn(idview1, idoverrideuser1),
objectclass=objectclasses.idoverrideuser,
ipaanchoruuid=[idoverrideuser1],
ipaoriginaluid=[idoverrideuser1],
description=[u'description'],
uid=[u'newlogin'],
)
),
),
dict(
desc='Modify User ID override "%s" to override home '
'directory' % idoverrideuser1,
command=(
'idoverrideuser_mod',
[idview1, idoverrideuser1],
dict(homedirectory=u'/home/newhome', all=True)
),
expected=dict(
value=idoverrideuser1,
summary=u'Modified an User ID override "%s"' % idoverrideuser1,
result=dict(
dn=get_override_dn(idview1, idoverrideuser1),
objectclass=objectclasses.idoverrideuser,
ipaanchoruuid=[idoverrideuser1],
ipaoriginaluid=[idoverrideuser1],
description=[u'description'],
homedirectory=[u'/home/newhome'],
uid=[u'newlogin'],
)
),
),
dict(
desc='Modify User ID override "%s" to override '
'sshpubkey' % idoverrideuser1,
command=(
'idoverrideuser_mod',
[idview1, idoverrideuser1],
dict(ipasshpubkey=sshpubkey, all=True)
),
expected=dict(
value=idoverrideuser1,
summary=u'Modified an User ID override "%s"' % idoverrideuser1,
result=dict(
dn=get_override_dn(idview1, idoverrideuser1),
objectclass=objectclasses.idoverrideuser,
ipaanchoruuid=[idoverrideuser1],
ipaoriginaluid=[idoverrideuser1],
description=[u'description'],
homedirectory=[u'/home/newhome'],
uid=[u'newlogin'],
ipasshpubkey=[sshpubkey],
sshpubkeyfp=[sshpubkeyfp],
)
),
),
dict(
desc='Modify User ID override "%s" to not override '
'sshpubkey' % idoverrideuser1,
command=(
'idoverrideuser_mod',
[idview1, idoverrideuser1],
dict(ipasshpubkey=None, all=True)
),
expected=dict(
value=idoverrideuser1,
summary=u'Modified an User ID override "%s"' % idoverrideuser1,
result=dict(
dn=get_override_dn(idview1, idoverrideuser1),
objectclass=objectclasses.idoverrideuser,
ipaanchoruuid=[idoverrideuser1],
ipaoriginaluid=[idoverrideuser1],
description=[u'description'],
homedirectory=[u'/home/newhome'],
uid=[u'newlogin'],
)
),
),
dict(
desc='Remove User ID override "%s"' % idoverrideuser1,
command=('idoverrideuser_del', [idview1, idoverrideuser1], {}),
expected=dict(
result=dict(failed=[]),
value=[idoverrideuser1],
summary=u'Deleted User ID override "%s"' % idoverrideuser1,
),
),
dict(
desc='Create User ID override "%s"' % idoverrideuser1,
command=(
'idoverrideuser_add',
[idview1, idoverrideuser1],
dict(description=u'description',
homedirectory=u'/home/newhome',
uid=u'newlogin',
uidnumber=12345,
ipasshpubkey=sshpubkey,
)
),
expected=dict(
value=idoverrideuser1,
summary=u'Added User ID override "%s"' % idoverrideuser1,
result=dict(
dn=get_override_dn(idview1, idoverrideuser1),
objectclass=objectclasses.idoverrideuser,
ipaanchoruuid=[idoverrideuser1],
ipaoriginaluid=[idoverrideuser1],
description=[u'description'],
homedirectory=[u'/home/newhome'],
uidnumber=[u'12345'],
uid=[u'newlogin'],
ipasshpubkey=[sshpubkey],
sshpubkeyfp=[sshpubkeyfp],
)
),
),
dict(
desc='Create Group ID override "%s"' % idoverridegroup1,
command=(
'idoverridegroup_add',
[idview1, idoverridegroup1],
dict(description=u'description')
),
expected=dict(
value=idoverridegroup1,
summary=u'Added Group ID override "%s"' % idoverridegroup1,
result=dict(
dn=get_override_dn(idview1, idoverridegroup1),
objectclass=objectclasses.idoverridegroup,
ipaanchoruuid=[idoverridegroup1],
description=[u'description']
)
),
),
dict(
desc='Try to create duplicate Group ID override "%s"'
% idoverridegroup1,
command=(
'idoverridegroup_add',
[idview1, idoverridegroup1],
dict(description=u'description')
),
expected=errors.DuplicateEntry(
message=(u'Group ID override with name "%s" '
'already exists' % idoverridegroup1)
),
),
dict(
desc='Modify Group ID override "%s" to override gidnumber'
% idoverridegroup1,
command=(
'idoverridegroup_mod',
[idview1, idoverridegroup1],
dict(gidnumber=54321, all=True)
),
expected=dict(
value=idoverridegroup1,
summary=u'Modified an Group ID override "%s"'
% idoverridegroup1,
result=dict(
dn=get_override_dn(idview1, idoverridegroup1),
objectclass=objectclasses.idoverridegroup,
ipaanchoruuid=[idoverridegroup1],
description=[u'description'],
gidnumber=[u'54321'],
)
),
),
dict(
desc='Modify Group ID override "%s" to not override '
'gidnumber' % idoverridegroup1,
command=(
'idoverridegroup_mod',
[idview1, idoverridegroup1],
dict(gidnumber=None, all=True)
),
expected=dict(
value=idoverridegroup1,
summary=u'Modified an Group ID override "%s"'
% idoverridegroup1,
result=dict(
dn=get_override_dn(idview1, idoverridegroup1),
objectclass=objectclasses.idoverridegroup,
ipaanchoruuid=[idoverridegroup1],
description=[u'description']
)
),
),
dict(
desc='Modify Group ID override "%s" to override group name'
% idoverridegroup1,
command=(
'idoverridegroup_mod',
[idview1, idoverridegroup1],
dict(cn=u'newgroup', all=True)
),
expected=dict(
value=idoverridegroup1,
summary=u'Modified an Group ID override "%s"'
% idoverridegroup1,
result=dict(
dn=get_override_dn(idview1, idoverridegroup1),
objectclass=objectclasses.idoverridegroup,
ipaanchoruuid=[idoverridegroup1],
description=[u'description'],
cn=[u'newgroup'],
)
),
),
dict(
desc='Remove Group ID override "%s"' % idoverridegroup1,
command=('idoverridegroup_del', [idview1, idoverridegroup1], {}),
expected=dict(
result=dict(failed=[]),
value=[idoverridegroup1],
summary=u'Deleted Group ID override "%s"' % idoverridegroup1,
),
),
dict(
desc='Create Group ID override "%s"' % idoverridegroup1,
command=(
'idoverridegroup_add',
[idview1, idoverridegroup1],
dict(description=u'description',
cn=u'newgroup',
gidnumber=12345,
)
),
expected=dict(
value=idoverridegroup1,
summary=u'Added Group ID override "%s"' % idoverridegroup1,
result=dict(
dn=get_override_dn(idview1, idoverridegroup1),
objectclass=objectclasses.idoverridegroup,
ipaanchoruuid=[idoverridegroup1],
description=[u'description'],
gidnumber=[u'12345'],
cn=[u'newgroup'],
)
),
),
dict(
desc='See that ID View "%s" enumerates overrides' % idview1,
command=(
'idview_show',
[idview1],
dict(all=True)
),
expected=dict(
value=idview1,
summary=None,
result=dict(
cn=[idview1],
dn=get_idview_dn(idview1),
objectclass=objectclasses.idview,
useroverrides=[idoverrideuser1],
groupoverrides=[idoverridegroup1],
)
),
),
# Test ID View applying to a master
# Try to apply to the localhost = master
dict(
desc=u'Apply %s to %s' % (idview1, api.env.host),
command=(
'idview_apply',
[idview1],
dict(host=api.env.host)
),
expected=dict(
completed=0,
succeeded=dict(
host=tuple(),
),
failed=dict(
memberhost=dict(
host=([api.env.host,
u'ID View cannot be applied to IPA master'],),
hostgroup=tuple(),
),
),
summary=u'Applied ID View "%s"' % idview1,
),
),
# Try to apply to the group ipaservers = all masters
dict(
desc=u'Apply %s to %s' % (idview1, 'ipaservers'),
command=(
'idview_apply',
[idview1],
dict(hostgroup=u'ipaservers')
),
expected=dict(
completed=0,
succeeded=dict(
host=tuple(),
),
failed=dict(
memberhost=dict(
host=([api.env.host,
u'ID View cannot be applied to IPA master'],),
hostgroup=tuple(),
),
),
summary=u'Applied ID View "%s"' % idview1,
),
),
# Test ID View applying
dict(
desc='Create %r' % host1,
command=('host_add', [get_fqdn(host1)],
dict(
description=u'Test host 1',
l=u'Undisclosed location 1',
force=True,
),
),
expected=dict(
value=get_fqdn(host1),
summary=u'Added host "%s"' % get_fqdn(host1),
result=dict(
dn=get_host_dn(host1),
fqdn=[get_fqdn(host1)],
description=[u'Test host 1'],
l=[u'Undisclosed location 1'],
krbprincipalname=[
u'host/%s@%s' % (get_fqdn(host1), api.env.realm)],
krbcanonicalname=[
u'host/%s@%s' % (get_fqdn(host1), api.env.realm)],
objectclass=objectclasses.host,
ipauniqueid=[fuzzy_uuid],
managedby_host=[get_fqdn(host1)],
has_keytab=False,
has_password=False,
),
),
),
dict(
desc='Create %r' % host2,
command=('host_add', [get_fqdn(host2)],
dict(
description=u'Test host 2',
l=u'Undisclosed location 2',
force=True,
),
),
expected=dict(
value=get_fqdn(host2),
summary=u'Added host "%s"' % get_fqdn(host2),
result=dict(
dn=get_host_dn(host2),
fqdn=[get_fqdn(host2)],
description=[u'Test host 2'],
l=[u'Undisclosed location 2'],
krbprincipalname=[
u'host/%s@%s' % (get_fqdn(host2), api.env.realm)],
krbcanonicalname=[
u'host/%s@%s' % (get_fqdn(host2), api.env.realm)],
objectclass=objectclasses.host,
ipauniqueid=[fuzzy_uuid],
managedby_host=[get_fqdn(host2)],
has_keytab=False,
has_password=False,
),
),
),
dict(
desc='Create %r' % host3,
command=('host_add', [get_fqdn(host3)],
dict(
description=u'Test host 3',
l=u'Undisclosed location 3',
force=True,
),
),
expected=dict(
value=get_fqdn(host3),
summary=u'Added host "%s"' % get_fqdn(host3),
result=dict(
dn=get_host_dn(host3),
fqdn=[get_fqdn(host3)],
description=[u'Test host 3'],
l=[u'Undisclosed location 3'],
krbprincipalname=[
u'host/%s@%s' % (get_fqdn(host3), api.env.realm)],
krbcanonicalname=[
u'host/%s@%s' % (get_fqdn(host3), api.env.realm)],
objectclass=objectclasses.host,
ipauniqueid=[fuzzy_uuid],
managedby_host=[get_fqdn(host3)],
has_keytab=False,
has_password=False,
),
),
),
dict(
desc='Create %r' % hostgroup1,
command=('hostgroup_add', [hostgroup1],
dict(description=u'Test hostgroup 1')
),
expected=dict(
value=hostgroup1,
summary=u'Added hostgroup "%s"' % hostgroup1,
result=dict(
dn=get_hostgroup_dn(hostgroup1),
cn=[hostgroup1],
objectclass=objectclasses.hostgroup,
description=[u'Test hostgroup 1'],
ipauniqueid=[fuzzy_uuid],
mepmanagedentry=[get_hostgroup_netgroup_dn(hostgroup1)],
),
),
),
dict(
desc='Create %r' % hostgroup1,
command=('hostgroup_add', [hostgroup2],
dict(description=u'Test hostgroup 2')
),
expected=dict(
value=hostgroup2,
summary=u'Added hostgroup "%s"' % hostgroup2,
result=dict(
dn=get_hostgroup_dn(hostgroup2),
cn=[hostgroup2],
objectclass=objectclasses.hostgroup,
description=[u'Test hostgroup 2'],
ipauniqueid=[fuzzy_uuid],
mepmanagedentry=[get_hostgroup_netgroup_dn(hostgroup2)],
),
),
),
dict(
desc=u'Add host %r to %r' % (host1, hostgroup1),
command=(
'hostgroup_add_member',
[hostgroup1],
dict(host=get_fqdn(host1))
),
expected=dict(
completed=1,
failed=dict(
member=dict(
host=tuple(),
hostgroup=tuple(),
),
),
result={
'dn': get_hostgroup_dn(hostgroup1),
'cn': [hostgroup1],
'description': [u'Test hostgroup 1'],
'member_host': [get_fqdn(host1)],
},
),
),
dict(
desc=u'Add host %r to %r' % (host2, hostgroup2),
command=(
'hostgroup_add_member',
[hostgroup2],
dict(host=get_fqdn(host2))
),
expected=dict(
completed=1,
failed=dict(
member=dict(
host=tuple(),
hostgroup=tuple(),
),
),
result={
'dn': get_hostgroup_dn(hostgroup2),
'cn': [hostgroup2],
'description': [u'Test hostgroup 2'],
'member_host': [get_fqdn(host2)],
},
),
),
dict(
desc=u'Add hostgroup %r to %r' % (hostgroup2, hostgroup1),
command=(
'hostgroup_add_member',
[hostgroup1],
dict(hostgroup=hostgroup2)
),
expected=dict(
completed=1,
failed=dict(
member=dict(
host=tuple(),
hostgroup=tuple(),
),
),
result={
'dn': get_hostgroup_dn(hostgroup1),
'cn': [hostgroup1],
'description': [u'Test hostgroup 1'],
'member_host': [get_fqdn(host1)],
'memberindirect_host': [get_fqdn(host2)],
'member_hostgroup': [hostgroup2],
},
),
),
dict(
desc=u'Apply %s to %s' % (idview1, host3),
command=(
'idview_apply',
[idview1],
dict(host=get_fqdn(host3))
),
expected=dict(
completed=1,
succeeded=dict(
host=[get_fqdn(host3)],
),
failed=dict(
memberhost=dict(
host=tuple(),
hostgroup=tuple(),
),
),
summary=u'Applied ID View "%s"' % idview1,
),
),
dict(
desc='Check that %s has %s applied' % (host3, idview1),
command=('host_show', [get_fqdn(host3)], {'all': True}),
expected=dict(
value=get_fqdn(host3),
summary=None,
result=dict(
cn=[get_fqdn(host3)],
dn=get_host_dn(host3),
fqdn=[get_fqdn(host3)],
description=[u'Test host 3'],
l=[u'Undisclosed location 3'],
krbprincipalname=[get_host_principal(host3)],
krbcanonicalname=[get_host_principal(host3)],
has_keytab=False,
has_password=False,
managedby_host=[get_fqdn(host3)],
ipakrbokasdelegate=False,
ipakrbrequirespreauth=True,
ipauniqueid=[fuzzy_uuid],
managing_host=[get_fqdn(host3)],
objectclass=objectclasses.host,
serverhostname=[host3],
ipaassignedidview=[idview1],
ipakrboktoauthasdelegate=False,
krbpwdpolicyreference=[DN(
u'cn=Default Host Password Policy',
api.env.container_host,
api.env.basedn,
)],
),
),
),
dict(
desc='Check that %s has not %s applied' % (host2, idview1),
command=('host_show', [get_fqdn(host2)], {'all': True}),
expected=dict(
value=get_fqdn(host2),
summary=None,
result=dict(
cn=[get_fqdn(host2)],
dn=get_host_dn(host2),
fqdn=[get_fqdn(host2)],
description=[u'Test host 2'],
l=[u'Undisclosed location 2'],
krbprincipalname=[get_host_principal(host2)],
krbcanonicalname=[get_host_principal(host2)],
has_keytab=False,
has_password=False,
managedby_host=[get_fqdn(host2)],
ipakrbokasdelegate=False,
ipakrbrequirespreauth=True,
ipauniqueid=[fuzzy_uuid],
managing_host=[get_fqdn(host2)],
objectclass=objectclasses.host,
serverhostname=[host2],
memberof_hostgroup=[hostgroup2],
memberofindirect_hostgroup=[hostgroup1],
ipakrboktoauthasdelegate=False,
krbpwdpolicyreference=[DN(
u'cn=Default Host Password Policy',
api.env.container_host,
api.env.basedn,
)],
),
),
),
dict(
desc=u'Apply %s to %s' % (idview1, hostgroup1),
command=(
'idview_apply',
[idview1],
dict(hostgroup=hostgroup1)
),
expected=dict(
completed=2,
succeeded=dict(
host=[get_fqdn(host1), get_fqdn(host2)],
),
failed=dict(
memberhost=dict(
host=tuple(),
hostgroup=tuple(),
),
),
summary=u'Applied ID View "%s"' % idview1,
),
),
dict(
desc='Check that %s has %s applied' % (host2, idview1),
command=('host_show', [get_fqdn(host2)], {'all': True}),
expected=dict(
value=get_fqdn(host2),
summary=None,
result=dict(
cn=[get_fqdn(host2)],
dn=get_host_dn(host2),
fqdn=[get_fqdn(host2)],
description=[u'Test host 2'],
l=[u'Undisclosed location 2'],
krbprincipalname=[get_host_principal(host2)],
krbcanonicalname=[get_host_principal(host2)],
has_keytab=False,
has_password=False,
managedby_host=[get_fqdn(host2)],
ipakrbokasdelegate=False,
ipakrbrequirespreauth=True,
ipauniqueid=[fuzzy_uuid],
managing_host=[get_fqdn(host2)],
objectclass=objectclasses.host,
serverhostname=[host2],
memberof_hostgroup=[hostgroup2],
memberofindirect_hostgroup=[hostgroup1],
ipaassignedidview=[idview1],
ipakrboktoauthasdelegate=False,
krbpwdpolicyreference=[DN(
u'cn=Default Host Password Policy',
api.env.container_host,
api.env.basedn,
)],
),
),
),
dict(
desc='Check that %s has %s applied' % (host1, idview1),
command=('host_show', [get_fqdn(host1)], {'all': True}),
expected=dict(
value=get_fqdn(host1),
summary=None,
result=dict(
cn=[get_fqdn(host1)],
dn=get_host_dn(host1),
fqdn=[get_fqdn(host1)],
description=[u'Test host 1'],
l=[u'Undisclosed location 1'],
krbprincipalname=[get_host_principal(host1)],
krbcanonicalname=[get_host_principal(host1)],
has_keytab=False,
has_password=False,
managedby_host=[get_fqdn(host1)],
ipakrbokasdelegate=False,
ipakrbrequirespreauth=True,
ipauniqueid=[fuzzy_uuid],
managing_host=[get_fqdn(host1)],
objectclass=objectclasses.host,
serverhostname=[host1],
memberof_hostgroup=[hostgroup1],
ipaassignedidview=[idview1],
ipakrboktoauthasdelegate=False,
krbpwdpolicyreference=[DN(
u'cn=Default Host Password Policy',
api.env.container_host,
api.env.basedn,
)],
),
),
),
dict(
desc='See that ID View "%s" enumerates hosts' % idview1,
command=(
'idview_show',
[idview1],
dict(all=True, show_hosts=True)
),
expected=dict(
value=idview1,
summary=None,
result=dict(
cn=[idview1],
dn=get_idview_dn(idview1),
objectclass=objectclasses.idview,
useroverrides=[idoverrideuser1],
groupoverrides=[idoverridegroup1],
appliedtohosts=[get_fqdn(host)
for host in (host1, host2, host3)]
)
),
),
dict(
desc=u'Unapply %s from %s and %s' % (idview1, host1, host3),
command=(
'idview_unapply',
[],
dict(host=[get_fqdn(host1), get_fqdn(host3)]),
),
expected=dict(
completed=2,
succeeded=dict(
host=[get_fqdn(host1), get_fqdn(host3)],
),
failed=dict(
memberhost=dict(
host=tuple(),
hostgroup=tuple(),
),
),
summary=u'Cleared ID Views',
),
),
dict(
desc='Check that %s has not %s applied' % (host1, idview1),
command=('host_show', [get_fqdn(host1)], {'all': True}),
expected=dict(
value=get_fqdn(host1),
summary=None,
result=dict(
cn=[get_fqdn(host1)],
dn=get_host_dn(host1),
fqdn=[get_fqdn(host1)],
description=[u'Test host 1'],
l=[u'Undisclosed location 1'],
krbprincipalname=[get_host_principal(host1)],
krbcanonicalname=[get_host_principal(host1)],
has_keytab=False,
has_password=False,
managedby_host=[get_fqdn(host1)],
ipakrbokasdelegate=False,
ipakrbrequirespreauth=True,
ipauniqueid=[fuzzy_uuid],
managing_host=[get_fqdn(host1)],
objectclass=objectclasses.host,
serverhostname=[host1],
memberof_hostgroup=[hostgroup1],
ipakrboktoauthasdelegate=False,
krbpwdpolicyreference=[DN(
u'cn=Default Host Password Policy',
api.env.container_host,
api.env.basedn,
)],
),
),
),
dict(
desc='Check that %s has not %s applied' % (host3, idview1),
command=('host_show', [get_fqdn(host3)], {'all': True}),
expected=dict(
value=get_fqdn(host3),
summary=None,
result=dict(
cn=[get_fqdn(host3)],
dn=get_host_dn(host3),
fqdn=[get_fqdn(host3)],
description=[u'Test host 3'],
l=[u'Undisclosed location 3'],
krbprincipalname=[get_host_principal(host3)],
krbcanonicalname=[get_host_principal(host3)],
has_keytab=False,
has_password=False,
managedby_host=[get_fqdn(host3)],
ipakrbokasdelegate=False,
ipakrbrequirespreauth=True,
ipauniqueid=[fuzzy_uuid],
managing_host=[get_fqdn(host3)],
objectclass=objectclasses.host,
serverhostname=[host3],
ipakrboktoauthasdelegate=False,
krbpwdpolicyreference=[DN(
u'cn=Default Host Password Policy',
api.env.container_host,
api.env.basedn,
)],
),
),
),
dict(
desc='See that ID View "%s" enumerates only one host' % idview1,
command=(
'idview_show',
[idview1],
dict(all=True, show_hosts=True)
),
expected=dict(
value=idview1,
summary=None,
result=dict(
cn=[idview1],
dn=get_idview_dn(idview1),
objectclass=objectclasses.idview,
useroverrides=[idoverrideuser1],
groupoverrides=[idoverridegroup1],
appliedtohosts=[get_fqdn(host2)]
)
),
),
dict(
desc=u'Unapply %s from %s' % (idview1, hostgroup2),
command=(
'idview_unapply',
[],
dict(hostgroup=hostgroup2),
),
expected=dict(
completed=1,
succeeded=dict(
host=[get_fqdn(host2)],
),
failed=dict(
memberhost=dict(
host=tuple(),
hostgroup=tuple(),
),
),
summary=u'Cleared ID Views',
),
),
dict(
desc='See that ID View "%s" enumerates no host' % idview1,
command=(
'idview_show',
[idview1],
dict(all=True, show_hosts=True)
),
expected=dict(
value=idview1,
summary=None,
result=dict(
cn=[idview1],
dn=get_idview_dn(idview1),
objectclass=objectclasses.idview,
useroverrides=[idoverrideuser1],
groupoverrides=[idoverridegroup1],
)
),
),
# Deleting ID overrides
dict(
desc='Delete User ID override "%s"' % idoverrideuser1,
command=('idoverrideuser_del', [idview1, idoverrideuser1], {}),
expected=dict(
result=dict(failed=[]),
summary=u'Deleted User ID override "%s"' % idoverrideuser1,
value=[idoverrideuser1],
),
),
dict(
desc='Delete Group ID override "%s"' % idoverridegroup1,
command=('idoverridegroup_del', [idview1, idoverridegroup1], {}),
expected=dict(
result=dict(failed=[]),
summary=u'Deleted Group ID override "%s"' % idoverridegroup1,
value=[idoverridegroup1],
),
),
# Delete the ID View
dict(
desc='Delete empty ID View "%s"' % idview1,
command=('idview_del', [idview1], {}),
expected=dict(
result=dict(failed=[]),
summary=u'Deleted ID View "%s"' % idview1,
value=[idview1],
),
),
# Recreate the view and delete it when it contains overrides
dict(
desc='Create ID View "%s"' % idview1,
command=(
'idview_add',
[idview1],
{}
),
expected=dict(
value=idview1,
summary=u'Added ID View "%s"' % idview1,
result=dict(
dn=get_idview_dn(idview1),
objectclass=objectclasses.idview,
cn=[idview1]
)
),
),
dict(
desc='Recreate User ID override "%s"' % idoverrideuser1,
command=(
'idoverrideuser_add',
[idview1, idoverrideuser1],
dict(description=u'description')
),
expected=dict(
value=idoverrideuser1,
summary=u'Added User ID override "%s"' % idoverrideuser1,
result=dict(
dn=get_override_dn(idview1, idoverrideuser1),
objectclass=objectclasses.idoverrideuser,
ipaanchoruuid=[idoverrideuser1],
ipaoriginaluid=[idoverrideuser1],
description=[u'description']
)
),
),
dict(
desc='Recreate Group ID override "%s"' % idoverridegroup1,
command=(
'idoverridegroup_add',
[idview1, idoverridegroup1],
dict(description=u'description')
),
expected=dict(
value=idoverridegroup1,
summary=u'Added Group ID override "%s"' % idoverridegroup1,
result=dict(
dn=get_override_dn(idview1, idoverridegroup1),
objectclass=objectclasses.idoverridegroup,
ipaanchoruuid=[idoverridegroup1],
description=[u'description'],
)
),
),
dict(
desc='Delete full ID View "%s"' % idview1,
command=('idview_del', [idview1], {}),
expected=dict(
result=dict(failed=[]),
summary=u'Deleted ID View "%s"' % idview1,
value=[idview1],
),
),
# Recreate the view, assign it to a host and then delete the view
# Check that the host no longer references the view
dict(
desc='Create ID View "%s"' % idview1,
command=(
'idview_add',
[idview1],
{}
),
expected=dict(
value=idview1,
summary=u'Added ID View "%s"' % idview1,
result=dict(
dn=get_idview_dn(idview1),
objectclass=objectclasses.idview,
cn=[idview1]
)
),
),
dict(
desc='Create %r' % host4,
command=('host_add', [get_fqdn(host4)],
dict(
description=u'Test host 4',
l=u'Undisclosed location 4',
force=True,
),
),
expected=dict(
value=get_fqdn(host4),
summary=u'Added host "%s"' % get_fqdn(host4),
result=dict(
dn=get_host_dn(host4),
fqdn=[get_fqdn(host4)],
description=[u'Test host 4'],
l=[u'Undisclosed location 4'],
krbprincipalname=[
u'host/%s@%s' % (get_fqdn(host4), api.env.realm)],
krbcanonicalname=[
u'host/%s@%s' % (get_fqdn(host4), api.env.realm)],
objectclass=objectclasses.host,
ipauniqueid=[fuzzy_uuid],
managedby_host=[get_fqdn(host4)],
has_keytab=False,
has_password=False,
),
),
),
dict(
desc='Delete ID View that is assigned "%s"' % idview1,
command=('idview_del', [idview1], {}),
expected=dict(
result=dict(failed=[]),
summary=u'Deleted ID View "%s"' % idview1,
value=[idview1],
),
),
dict(
desc='Check that %s has not %s applied' % (host4, idview1),
command=('host_show', [get_fqdn(host4)], {'all': True}),
expected=dict(
value=get_fqdn(host4),
summary=None,
result=dict(
cn=[get_fqdn(host4)],
dn=get_host_dn(host4),
fqdn=[get_fqdn(host4)],
description=[u'Test host 4'],
l=[u'Undisclosed location 4'],
krbprincipalname=[get_host_principal(host4)],
krbcanonicalname=[get_host_principal(host4)],
has_keytab=False,
has_password=False,
managedby_host=[get_fqdn(host4)],
ipakrbokasdelegate=False,
ipakrbrequirespreauth=True,
ipauniqueid=[fuzzy_uuid],
managing_host=[get_fqdn(host4)],
objectclass=objectclasses.host,
serverhostname=[host4],
ipakrboktoauthasdelegate=False,
krbpwdpolicyreference=[DN(
u'cn=Default Host Password Policy',
api.env.container_host,
api.env.basedn,
)],
),
),
),
# Test integrity of idoverride objects agains their references
dict(
desc='Create ID View "%s"' % idview1,
command=(
'idview_add',
[idview1],
{}
),
expected=dict(
value=idview1,
summary=u'Added ID View "%s"' % idview1,
result=dict(
dn=get_idview_dn(idview1),
objectclass=objectclasses.idview,
cn=[idview1]
)
),
),
dict(
desc='Create "%s"' % idoverrideuser_removed,
command=(
'user_add',
[idoverrideuser_removed],
dict(
givenname=u'Removed',
sn=u'User',
)
),
expected=dict(
value=idoverrideuser_removed,
summary=u'Added user "%s"' % idoverrideuser_removed,
result=get_user_result(
idoverrideuser_removed,
u'Removed',
u'User',
'add',
objectclass=fuzzy_set_optional_oc(
objectclasses.user, 'ipantuserattrs'),
),
),
),
dict(
desc='Create group %r' % idoverridegroup_removed,
command=(
'group_add',
[idoverridegroup_removed],
dict(description=u'Removed group')
),
expected=dict(
value=idoverridegroup_removed,
summary=u'Added group "%s"' % idoverridegroup_removed,
result=dict(
cn=[idoverridegroup_removed],
description=[u'Removed group'],
objectclass=fuzzy_set_optional_oc(
objectclasses.posixgroup, 'ipantgroupattrs'),
ipauniqueid=[fuzzy_uuid],
gidnumber=[fuzzy_digits],
dn=get_group_dn(idoverridegroup_removed),
),
),
),
dict(
desc='Create User ID override "%s"' % idoverrideuser_removed,
command=(
'idoverrideuser_add',
[idview1, idoverrideuser_removed],
dict(description=u'description',
homedirectory=u'/home/newhome',
uid=u'newlogin',
uidnumber=12345,
ipasshpubkey=sshpubkey,
)
),
expected=dict(
value=idoverrideuser_removed,
summary=u'Added User ID override "%s"' % idoverrideuser_removed,
result=dict(
dn=get_override_dn(idview1, idoverrideuser_removed),
objectclass=objectclasses.idoverrideuser,
ipaanchoruuid=[idoverrideuser_removed],
ipaoriginaluid=[idoverrideuser_removed],
description=[u'description'],
homedirectory=[u'/home/newhome'],
uidnumber=[u'12345'],
uid=[u'newlogin'],
ipasshpubkey=[sshpubkey],
sshpubkeyfp=[sshpubkeyfp],
)
),
),
dict(
desc='Create Group ID override "%s"' % idoverridegroup_removed,
command=(
'idoverridegroup_add',
[idview1, idoverridegroup_removed],
dict(description=u'description')
),
expected=dict(
value=idoverridegroup_removed,
summary=u'Added Group ID override "%s"' % idoverridegroup_removed,
result=dict(
dn=get_override_dn(idview1, idoverridegroup_removed),
objectclass=objectclasses.idoverridegroup,
ipaanchoruuid=[idoverridegroup_removed],
description=[u'description'],
)
),
),
dict(
desc='Delete "%s"' % idoverrideuser_removed,
command=('user_del', [idoverrideuser_removed], {}),
expected=dict(
result=dict(failed=[]),
summary=u'Deleted user "%s"' % idoverrideuser_removed,
value=[idoverrideuser_removed],
),
),
dict(
desc='Delete "%s"' % idoverridegroup_removed,
command=('group_del', [idoverridegroup_removed], {}),
expected=dict(
result=dict(failed=[]),
summary=u'Deleted group "%s"' % idoverridegroup_removed,
value=[idoverridegroup_removed],
),
),
dict(
desc='Make sure idoverrideuser objects have been cleaned',
command=(
'idoverrideuser_find',
[idview1],
dict(),
),
expected=dict(
result=[],
summary=u'0 User ID overrides matched',
count=0,
truncated=False,
),
),
dict(
desc='Make sure idoverridegroup objects have been cleaned',
command=(
'idoverridegroup_find',
[idview1],
dict(),
),
expected=dict(
result=[],
summary=u'0 Group ID overrides matched',
count=0,
truncated=False,
),
),
# Delete the ID View
dict(
desc='Delete ID View "%s"' % idview1,
command=('idview_del', [idview1], {}),
expected=dict(
result=dict(failed=[]),
summary=u'Deleted ID View "%s"' % idview1,
value=[idview1],
),
),
# Test the creation of ID view with domain resolution order
# Non-regression test for issue 7350
dict(
desc='Create ID View "%s"' % idview1,
command=(
'idview_add',
[idview1],
dict(ipadomainresolutionorder=u'%s' % api.env.domain)
),
expected=dict(
value=idview1,
summary=u'Added ID View "%s"' % idview1,
result=dict(
dn=get_idview_dn(idview1),
objectclass=objectclasses.idview +
[u'ipanameresolutiondata'],
cn=[idview1],
ipadomainresolutionorder=[api.env.domain]
)
),
),
]
| 63,549
|
Python
|
.py
| 1,654
| 22.405079
| 87
| 0.462565
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,487
|
xmlrpc_test.py
|
freeipa_freeipa/ipatests/test_xmlrpc/xmlrpc_test.py
|
# Authors:
# Rob Crittenden <rcritten@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/>.
"""
Base class for all XML-RPC tests
"""
from __future__ import print_function
from collections.abc import Sequence
import datetime
import inspect
import contextlib
import pytest
from ipatests.util import assert_deepequal, Fuzzy
from ipalib import api, request as ipa_request, errors
from ipapython.version import API_VERSION
# Matches a gidnumber like '1391016742'
# FIXME: Does it make more sense to return gidnumber, uidnumber, etc. as `int`
# or `long`? If not, we still need to return them as `unicode` instead of `str`.
fuzzy_digits = Fuzzy(r'^\d+$', type=str)
uuid_re = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
# Matches an ipauniqueid like u'784d85fd-eae7-11de-9d01-54520012478b'
fuzzy_uuid = Fuzzy('^%s$' % uuid_re)
# Matches an automember task DN
fuzzy_automember_dn = Fuzzy(
'^cn=%s,cn=automember rebuild membership,cn=tasks,cn=config$' % uuid_re
)
# base64-encoded value
fuzzy_base64 = Fuzzy('^[0-9A-Za-z/+]+={0,2}$')
def fuzzy_sequence_of(fuzzy):
"""Construct a Fuzzy for a Sequence of values matching the given Fuzzy."""
def test(xs):
if not isinstance(xs, Sequence):
return False
else:
return all(fuzzy == x for x in xs)
return Fuzzy(test=test)
# Matches an automember task finish message
fuzzy_automember_message = Fuzzy(
r'^Automember rebuild task finished\. Processed \(\d+\) entries'
)
# Matches trusted domain GUID, like u'463bf2be-3456-4a57-979e-120304f2a0eb'
fuzzy_guid = fuzzy_uuid
# Matches SID of a trusted domain
# SID syntax: http://msdn.microsoft.com/en-us/library/ff632068.aspx
_sid_identifier_authority = '(0x[0-9a-f]{1,12}|[0-9]{1,10})'
fuzzy_domain_sid = Fuzzy(
'^S-1-5-21-%(idauth)s-%(idauth)s-%(idauth)s$' % dict(idauth=_sid_identifier_authority)
)
fuzzy_user_or_group_sid = Fuzzy(
'^S-1-5-21-%(idauth)s-%(idauth)s-%(idauth)s-%(idauth)s$' % dict(idauth=_sid_identifier_authority)
)
# Matches netgroup dn. Note (?i) at the beginning of the regexp is the ingnore case flag
fuzzy_netgroupdn = Fuzzy(
'(?i)ipauniqueid=%s,cn=ng,cn=alt,%s' % (uuid_re, api.env.basedn)
)
# Matches sudocmd dn
fuzzy_sudocmddn = Fuzzy(
'(?i)ipauniqueid=%s,cn=sudocmds,cn=sudo,%s' % (uuid_re, api.env.basedn)
)
# Matches caacl dn
fuzzy_caacldn = Fuzzy(
'(?i)ipauniqueid=%s,cn=caacls,cn=ca,%s' % (uuid_re, api.env.basedn)
)
# Matches internal CA ID
fuzzy_caid = fuzzy_uuid
# Matches fuzzy ipaUniqueID DN group (RDN)
fuzzy_ipauniqueid = Fuzzy('(?i)ipauniqueid=%s' % uuid_re)
# Matches a hash signature, not enforcing length
fuzzy_hash = Fuzzy(r'^([a-f0-9][a-f0-9]:)+[a-f0-9][a-f0-9]$', type=str)
# Matches a date, like Tue Apr 26 17:45:35 2016 UTC
fuzzy_date = Fuzzy(
r'^[a-zA-Z]{3} [a-zA-Z]{3} \d{2} \d{2}:\d{2}:\d{2} \d{4} UTC$'
)
fuzzy_issuer = Fuzzy(type=str)
fuzzy_hex = Fuzzy(r'^0x[0-9a-fA-F]+$', type=str)
# Matches password - password consists of all printable characters without
# whitespaces. The only exception is space, but space cannot be at the
# beginning or end of the pwd.
fuzzy_password = Fuzzy(r'^\S([\S ]*\S)*$')
# Matches generalized time value. Time format is: %Y%m%d%H%M%SZ
fuzzy_dergeneralizedtime = Fuzzy(type=datetime.datetime)
# match any string
fuzzy_string = Fuzzy(type=str)
fuzzy_bytes = Fuzzy(type=bytes)
# case insensitive match of sets
def fuzzy_set_ci(s):
return Fuzzy(test=lambda other: set(x.lower() for x in other) == set(y.lower() for y in s))
def fuzzy_set_optional_oc(s, oc):
return Fuzzy(test=lambda other: set(x.lower() for x in other if x != oc)
== set(y.lower() for y in s if y != oc))
server_available = None
try:
if not api.Backend.rpcclient.isconnected():
api.Backend.rpcclient.connect()
api.Command["user_show"]("notfound")
server_available = True
except (errors.NetworkError, IOError):
server_available = False
except errors.NotFound:
server_available = True
adtrust_is_enabled = api.Command['adtrust_is_enabled']()['result']
sidgen_was_run = api.Command['sidgen_was_run']()['result']
def add_oc(l, oc, check_sidgen=False):
if adtrust_is_enabled and (not check_sidgen or sidgen_was_run):
return l + [oc]
return l
def assert_attr_equal(entry, key, value):
if type(entry) is not dict:
raise AssertionError(
'assert_attr_equal: entry must be a %r; got a %r: %r' % (
dict, type(entry), entry)
)
if key not in entry:
raise AssertionError(
'assert_attr_equal: entry has no key %r: %r' % (key, entry)
)
if value not in entry[key]:
raise AssertionError(
'assert_attr_equal: %r: %r not in %r' % (key, value, entry[key])
)
def assert_is_member(entry, value, key='member'):
if type(entry) is not dict:
raise AssertionError(
'assert_is_member: entry must be a %r; got a %r: %r' % (
dict, type(entry), entry)
)
if key not in entry:
raise AssertionError(
'assert_is_member: entry has no key %r: %r' % (key, entry)
)
for member in entry[key]:
if member.startswith(value):
return
raise AssertionError(
'assert_is_member: %r: %r not in %r' % (key, value, entry[key])
)
# Initialize the API. We do this here so that one can run the tests
# individually instead of at the top-level. If API.bootstrap()
# has already been called we continue gracefully. Other errors will be
# raised.
class XMLRPC_test:
"""
Base class for all XML-RPC plugin tests
"""
@pytest.fixture(autouse=True, scope="class")
def xmlrpc_setup(self, request):
if not server_available:
pytest.skip('%r: Server not available: %r' %
(request.cls.__module__,
api.env.xmlrpc_uri))
if not api.Backend.rpcclient.isconnected():
api.Backend.rpcclient.connect()
def fin():
ipa_request.destroy_context()
request.addfinalizer(fin)
def failsafe_add(self, obj, pk, **options):
"""
Delete possible leftover entry first, then add.
This helps speed us up when a partial test failure has left LDAP in a
dirty state.
:param obj: An Object like api.Object.user
:param pk: The primary key of the entry to be created
:param options: Kwargs to be passed to obj.add()
"""
self.failsafe_del(obj, pk)
return obj.methods['add'](pk, **options)
@classmethod
def failsafe_del(cls, obj, pk):
"""
Delete an entry if it exists
:param obj: An Object like api.Object.user
:param pk: The primary key of the entry to be deleted
"""
try:
obj.methods['del'](pk)
except errors.NotFound:
pass
IGNORE = """Command %r is missing attribute %r in output entry.
args = %r
options = %r
entry = %r"""
EXPECTED = """Expected %r to raise %s.
args = %r
options = %r
output = %r"""
UNEXPECTED = """Expected %r to raise %s, but caught different.
args = %r
options = %r
expected = %s: %s
got = %s: %s"""
KWARGS = """Command %r raised %s with wrong kwargs.
args = %r
options = %r
kw_expected = %r
kw_got = %r"""
class Declarative(XMLRPC_test):
"""A declarative-style test suite
This class is DEPRECATED. Use RPCTest instead.
See host plugin tests for an example.
A Declarative test suite is controlled by the ``tests`` and
``cleanup_commands`` class variables.
The ``tests`` is a list of dictionaries with the following keys:
``desc``
A name/description of the test
``command``
A (command, args, kwargs) triple specifying the command to run
``expected``
Can be either an ``errors.PublicError`` instance, in which case
the command must fail with the given error; or the
expected result.
The result is checked with ``tests.util.assert_deepequal``.
``extra_check`` (optional)
A checking function that is called with the response. It must
return true for the test to pass.
The ``cleanup_commands`` is a list of (command, args, kwargs)
triples. These are commands get run both before and after tests,
and must not fail.
"""
default_version = API_VERSION
cleanup_commands = tuple()
tests = tuple()
@pytest.fixture(autouse=True, scope="class")
def declarative_setup(self, request, xmlrpc_setup):
def fin():
for command in request.cls.cleanup_commands:
request.cls.cleanup(command)
fin()
request.addfinalizer(fin)
@classmethod
def cleanup(cls, command):
(cmd, args, options) = command
print('Cleanup:', cmd, args, options)
if cmd not in api.Command:
pytest.skip(
'cleanup command %r not in api.Command' % cmd
)
try:
api.Command[cmd](*args, **options)
except (errors.NotFound, errors.EmptyModlist) as e:
print(e)
def test_command(self, index, declarative_test_definition):
"""Run an individual test
The arguments are provided by the pytest plugin.
"""
if callable(declarative_test_definition):
declarative_test_definition(self)
else:
self.check(**declarative_test_definition)
def check(self, nice, desc, command, expected, extra_check=None):
(cmd, args, options) = command
options.setdefault('version', self.default_version)
if cmd not in api.Command:
pytest.skip('%r not in api.Command' % cmd)
if isinstance(expected, errors.PublicError):
self.check_exception(nice, cmd, args, options, expected)
elif hasattr(expected, '__call__'):
self.check_callable(nice, cmd, args, options, expected)
else:
self.check_output(nice, cmd, args, options, expected, extra_check)
def check_exception(self, nice, cmd, args, options, expected):
klass = expected.__class__
expected_name = klass.__name__
got = None
try:
output = api.Command[cmd](*args, **options)
except Exception as e:
got = e
else:
raise AssertionError(
EXPECTED % (cmd, expected_name, args, options, output)
)
if not isinstance(got, klass):
raise AssertionError(
UNEXPECTED % (cmd, expected_name, args, options,
expected_name, expected,
got.__class__.__name__, got)
)
# FIXME: the XML-RPC transport doesn't allow us to return structured
# information through the exception, so we can't test the kw on the
# client side. However, if we switch to using JSON-RPC for the default
# transport, the exception is a free-form data structure (dict).
# For now just compare the strings
# pylint: disable=no-member
assert_deepequal(expected.strerror, got.strerror)
# pylint: enable=no-member
def check_callable(self, nice, cmd, args, options, expected):
expected_name = expected.__class__.__name__
try:
expected_text = inspect.getsource(expected).strip()
except TypeError:
expected_text = str(expected)
output = dict()
got = None
try:
output = api.Command[cmd](*args, **options)
except Exception as e:
got = e
if not expected(got, output):
raise AssertionError(
UNEXPECTED % (cmd, expected_name, args, options,
expected_name, expected_text,
got.__class__.__name__, got)
)
def check_output(self, nice, cmd, args, options, expected, extra_check):
got = api.Command[cmd](*args, **options)
assert_deepequal(expected, got, nice)
if extra_check and not extra_check(got):
raise AssertionError('Extra check %s failed' % extra_check)
@contextlib.contextmanager
def raises_exact(expected_exception):
"""Check that a specific PublicError is raised
Both type and message of the error are checked.
>>> with raises_exact(errors.ValidationError(name='x', error='y')):
... raise errors.ValidationError(name='x', error='y')
"""
try:
yield
except errors.PublicError as got_exception:
assert type(expected_exception) is type(got_exception)
# FIXME: We should return error information in a structured way.
# For now just compare the strings
assert expected_exception.strerror == got_exception.strerror
else:
raise AssertionError('did not raise!')
| 13,600
|
Python
|
.py
| 339
| 33.530973
| 101
| 0.645506
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,488
|
test_location_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_location_plugin.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
from __future__ import absolute_import
import pytest
from ipalib import errors, api
from ipaplatform.services import knownservices
from ipatests.test_xmlrpc.tracker.location_plugin import LocationTracker
from ipatests.test_xmlrpc.tracker.server_plugin import ServerTracker
from ipatests.test_xmlrpc.xmlrpc_test import (
XMLRPC_test,
raises_exact
)
from ipapython.dnsutil import DNSName
@pytest.fixture(scope='class', params=[u'location1', u'sk\xfa\u0161ka.idna'])
def location(request, xmlrpc_setup):
tracker = LocationTracker(request.param)
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def location_invalid(request, xmlrpc_setup):
tracker = LocationTracker(u'invalid..location')
return tracker
@pytest.fixture(scope='class')
def location_absolute(request, xmlrpc_setup):
tracker = LocationTracker(u'invalid.absolute.')
return tracker
@pytest.fixture(scope='class')
def server(request, xmlrpc_setup):
tracker = ServerTracker(api.env.host)
return tracker.make_fixture_clean_location(request)
@pytest.mark.tier1
class TestNonexistentIPALocation(XMLRPC_test):
def test_retrieve_nonexistent(self, location):
location.ensure_missing()
command = location.make_retrieve_command()
with raises_exact(errors.NotFound(
reason=u'%s: location not found' % location.idnsname)):
command()
def test_update_nonexistent(self, location):
location.ensure_missing()
command = location.make_update_command(updates=dict(
description=u'Nope'))
with raises_exact(errors.NotFound(
reason=u'%s: location not found' % location.idnsname)):
command()
def test_delete_nonexistent(self, location):
location.ensure_missing()
command = location.make_delete_command()
with raises_exact(errors.NotFound(
reason=u'%s: location not found' % location.idnsname)):
command()
@pytest.mark.tier1
class TestInvalidIPALocations(XMLRPC_test):
def test_invalid_name(self, location_invalid):
command = location_invalid.make_create_command()
with raises_exact(errors.ConversionError(
name=u'name',
error=u"empty DNS label")):
command()
def test_invalid_absolute(self, location_absolute):
command = location_absolute.make_create_command()
with raises_exact(errors.ValidationError(
name=u'name', error=u'must be relative')):
command()
@pytest.mark.tier1
class TestCRUD(XMLRPC_test):
def test_create_duplicate(self, location):
location.ensure_exists()
command = location.make_create_command()
with raises_exact(errors.DuplicateEntry(
message=u'location with name "%s" already exists' %
location.idnsname)):
command()
def test_retrieve_simple(self, location):
location.retrieve()
def test_retrieve_all(self, location):
location.retrieve(all=True)
def test_search_simple(self, location):
location.find()
def test_search_all(self, location):
location.find(all=True)
def test_update_simple(self, location):
location.update(dict(
description=u'Updated description',
),
expected_updates=dict(
description=[u'Updated description'],
))
location.retrieve()
def test_try_rename(self, location):
location.ensure_exists()
command = location.make_update_command(
updates=dict(setattr=u'idnsname=changed'))
with raises_exact(errors.NotAllowedOnRDN()):
command()
def test_delete_location(self, location):
location.delete()
@pytest.mark.tier1
@pytest.mark.skipif(
not api.Command.dns_is_enabled()['result'], reason='DNS not configured')
class TestLocationsServer(XMLRPC_test):
messages = [{
u'data': {u'service': knownservices.named.systemd_name,
u'server': api.env.host},
u'message': (u'Service %s requires restart '
u'on IPA server %s to apply configuration '
u'changes.' % (knownservices.named.systemd_name,
api.env.host)),
u'code': 13025,
u'type': u'warning',
u'name': u'ServiceRestartRequired'}]
def test_add_nonexistent_location_to_server(self, server):
nonexistent_loc = DNSName(u'nonexistent-location')
command = server.make_update_command(
updates=dict(
ipalocation_location=nonexistent_loc,
)
)
with raises_exact(errors.NotFound(
reason=u"{location}: location not found".format(
location=nonexistent_loc
))):
command()
def test_add_location_to_server(self, location, server):
location.ensure_exists()
server.update(
updates={u'ipalocation_location': location.idnsname_obj},
expected_updates={u'ipalocation_location': [location.idnsname_obj],
u'enabled_role_servrole': lambda other: True},
messages=self.messages)
location.add_server_to_location(server.server_name)
location.retrieve()
location.remove_server_from_location(server.server_name)
def test_retrieve(self, server):
server.retrieve()
def test_retrieve_all(self, server):
server.retrieve(all=True)
def test_search_server_with_location(self, location, server):
command = server.make_find_command(
server.server_name, in_location=location.idnsname_obj)
result = command()
server.check_find(result)
def test_search_server_with_location_with_all(self, location, server):
command = server.make_find_command(
server.server_name, in_location=location.idnsname_obj, all=True)
result = command()
server.check_find(result, all=True)
def test_search_server_without_location(self, location, server):
command = server.make_find_command(
server.server_name, not_in_location=location.idnsname_obj)
result = command()
server.check_find_nomatch(result)
def test_add_location_to_server_custom_weight(self, location, server):
location.ensure_exists()
server.update(
updates={u'ipalocation_location': location.idnsname_obj,
u'ipaserviceweight': 200},
expected_updates={u'ipalocation_location': [location.idnsname_obj],
u'enabled_role_servrole': lambda other: True,
u'ipaserviceweight': [u'200']},
messages=self.messages)
# remove invalid data from the previous test
location.remove_server_from_location(server.server_name)
location.add_server_to_location(server.server_name, weight=200)
location.retrieve()
def test_remove_location_from_server(self, location, server):
server.update(
updates={u'ipalocation_location': None},
expected_updates={u'enabled_role_servrole': lambda other: True},
messages=self.messages)
location.remove_server_from_location(server.server_name)
location.retrieve()
def test_remove_service_weight_from_server(self, location, server):
server.update(
updates={u'ipaserviceweight': None},
expected_updates={u'enabled_role_servrole': lambda other: True},
messages=self.messages)
location.retrieve()
| 7,773
|
Python
|
.py
| 178
| 34.359551
| 79
| 0.654401
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,489
|
test_config_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_config_plugin.py
|
# Authors:
# Petr Viktorin <pviktori@redhat.com>
# Lenka Doudova <ldoudova@redhat.com>
#
# Copyright (C) 2010, 2016 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/plugins/config.py` module.
"""
from ipalib import api, errors
from ipaplatform.constants import constants as platformconstants
from ipatests.test_xmlrpc.xmlrpc_test import Declarative
import pytest
domain = api.env.domain
sl_domain = 'singlelabeldomain'
@pytest.mark.tier1
class test_config(Declarative):
cleanup_commands = [
]
tests = [
dict(
desc='Try to add an unrelated objectclass to ipauserobjectclasses',
command=('config_mod', [],
dict(addattr=u'ipauserobjectclasses=ipahost')),
expected=dict(
result=lambda d: 'ipahost' in d['ipauserobjectclasses'],
value=None,
summary=None,
),
),
dict(
desc='Remove the unrelated objectclass from ipauserobjectclasses',
command=('config_mod', [],
dict(delattr=u'ipauserobjectclasses=ipahost')),
expected=dict(
result=lambda d: 'ipahost' not in d['ipauserobjectclasses'],
value=None,
summary=None,
),
),
dict(
desc='Try to remove ipausersearchfields',
command=('config_mod', [],
dict(delattr=u'ipausersearchfields=uid,givenname,sn,telephonenumber,ou,title')),
expected=errors.RequirementError(name='usersearch'),
),
dict(
desc='Add uppercased attribute to ipausersearchfields',
command=('config_mod', [], dict(
ipausersearchfields=
u'uid,givenname,sn,telephonenumber,ou,title,Description')
),
expected=dict(
result=lambda d: (
d['ipausersearchfields'] ==
(u'uid,givenname,sn,telephonenumber,ou,title,description',)
),
value=None,
summary=None,
),
),
dict(
desc='Remove uppercased attribute from ipausersearchfields',
command=('config_mod', [], dict(
ipausersearchfields=
u'uid,givenname,sn,telephonenumber,ou,title',)),
expected=dict(
result=lambda d: (
d['ipausersearchfields'] ==
(u'uid,givenname,sn,telephonenumber,ou,title',)
),
value=None,
summary=None,
),
),
dict(
desc='Try to set ipaselinuxusermapdefault not in selinux order list',
command=('config_mod', [],
dict(ipaselinuxusermapdefault=u'unknown_u:s0')),
expected=errors.ValidationError(name='ipaselinuxusermapdefault',
error='SELinux user map default user not in order list'),
),
dict(
desc='Try to set invalid ipaselinuxusermapdefault',
command=('config_mod', [],
dict(ipaselinuxusermapdefault=u'foo')),
expected=errors.ValidationError(
name='ipaselinuxusermapdefault',
error='Invalid MLS value, must match {}, where max level '
'{}'.format(platformconstants.SELINUX_MLS_REGEX,
platformconstants.SELINUX_MLS_MAX)),
),
dict(
desc='Try to set invalid ipaselinuxusermapdefault with setattr',
command=('config_mod', [],
dict(setattr=u'ipaselinuxusermapdefault=unknown_u:s0')),
expected=errors.ValidationError(name='ipaselinuxusermapdefault',
error='SELinux user map default user not in order list'),
),
dict(
desc='Try to set ipaselinuxusermaporder without ipaselinuxusermapdefault out of it',
command=('config_mod', [],
dict(ipaselinuxusermaporder=u'notfound_u:s0')),
expected=errors.ValidationError(name='ipaselinuxusermaporder',
error='SELinux user map default user not in order list'),
),
dict(
desc='Try to set invalid ipaselinuxusermaporder',
command=('config_mod', [],
dict(ipaselinuxusermaporder=u'$')),
expected=errors.ValidationError(name='ipaselinuxusermaporder',
error='A list of SELinux users delimited by $ expected'),
),
dict(
desc='Try to set invalid selinux user in ipaselinuxusermaporder',
command=('config_mod', [],
dict(ipaselinuxusermaporder=u'baduser')),
expected=errors.ValidationError(
name='ipaselinuxusermaporder',
error='SELinux user \'baduser\' is not valid: Invalid MLS '
'value, must match {}, where max level {}'.format(
platformconstants.SELINUX_MLS_REGEX,
platformconstants.SELINUX_MLS_MAX)),
),
dict(
desc='Try to set new selinux order and invalid default user',
command=(
'config_mod', [],
dict(
ipaselinuxusermaporder=u'foo:s0',
ipaselinuxusermapdefault=u'unknown_u:s0')),
expected=errors.ValidationError(name='ipaselinuxusermapdefault',
error='SELinux user map default user not in order list'),
),
dict(
desc='Set user auth type',
command=('config_mod', [], dict(ipauserauthtype=u'password')),
expected=dict(
result=lambda d: d['ipauserauthtype'] == (u'password',),
value=None,
summary=None,
),
),
dict(
desc='Check user auth type',
command=('config_show', [], {}),
expected=dict(
result=lambda d: d['ipauserauthtype'] == (u'password',),
value=None,
summary=None,
),
),
dict(
desc='Set user auth type to passkey',
command=('config_mod', [], dict(ipauserauthtype=u'passkey')),
expected=dict(
result=lambda d: d['ipauserauthtype'] == (u'passkey',),
value=None,
summary=None,
),
),
dict(
desc='Check user auth type is passkey',
command=('config_show', [], {}),
expected=dict(
result=lambda d: d['ipauserauthtype'] == (u'passkey',),
value=None,
summary=None,
),
),
dict(
desc='Unset user auth type',
command=('config_mod', [], dict(ipauserauthtype=None)),
expected=dict(
result=lambda d: 'ipauserauthtype' not in d,
value=None,
summary=None,
),
),
dict(
desc='Set maximum username length higher than limit of 255',
command=('config_mod', [], dict(ipamaxusernamelength=256)),
expected=errors.ValidationError(
name='maxusername',
error='can be at most 255'),
),
dict(
desc='Set maximum username length equal to limit 255',
command=('config_mod', [], dict(ipamaxusernamelength=255)),
expected=dict(
result=lambda d: d['ipamaxusernamelength'] == (u'255',),
value=None,
summary=None,
),
),
# Cleanup after previous test - returns max username length to 32
dict(
desc='Return maximum username length to default value',
command=('config_mod', [], dict(ipamaxusernamelength=32)),
expected=dict(
result=lambda d: d['ipamaxusernamelength'] == (u'32',),
value=None,
summary=None,
),
),
dict(
desc='Check if domain resolution order does not accept SLD',
command=(
'config_mod', [], {
'ipadomainresolutionorder': u'{domain}:{sl_domain}'.format(
domain=domain, sl_domain=sl_domain)}),
expected=errors.ValidationError(
name=u'ipadomainresolutionorder',
error=(
u"Invalid domain name '{}': "
"single label domains are not supported").format(
sl_domain),
),
),
dict(
desc='Set the number of search records to -1 (unlimited)',
command=(
'config_mod', [], {
'ipasearchrecordslimit': u'-1',
},
),
expected={
'result': lambda d: d['ipasearchrecordslimit'] == (u'-1',),
'summary': None,
'value': None,
},
),
dict(
desc='Set the number of search records to greater than 10',
command=(
'config_mod', [], {
'ipasearchrecordslimit': u'100',
},
),
expected={
'result': lambda d: d['ipasearchrecordslimit'] == (u'100',),
'summary': None,
'value': None,
},
),
dict(
desc='Set the number of search records to lower than -1',
command=(
'config_mod', [], {
'ipasearchrecordslimit': u'-10',
},
),
expected=errors.ValidationError(
name=u'searchrecordslimit',
error=u'must be at least 10',
),
),
dict(
desc='Set the number of search records to lower than 10',
command=(
'config_mod', [], {
'ipasearchrecordslimit': u'1',
},
),
expected=errors.ValidationError(
name=u'searchrecordslimit',
error=u'must be at least 10',
),
),
dict(
desc='Set the number of search records to zero (unlimited)',
command=(
'config_mod', [], {
'ipasearchrecordslimit': u'0',
},
),
expected={
'result': lambda d: d['ipasearchrecordslimit'] == (u'-1',),
'summary': None,
'value': None,
},
),
dict(
desc='Set the number of search records back to 100',
command=(
'config_mod', [], {
'ipasearchrecordslimit': u'100',
},
),
expected={
'result': lambda d: d['ipasearchrecordslimit'] == (u'100',),
'summary': None,
'value': None,
},
),
dict(
desc='Set the value to the already set value, no modifications',
command=(
'config_mod', [], {
'ipasearchrecordslimit': u'100',
},
),
expected=errors.EmptyModlist(),
),
]
| 12,256
|
Python
|
.py
| 318
| 25.18239
| 96
| 0.51087
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,490
|
test_ping_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_ping_plugin.py
|
# Authors:
# Petr Viktorin <pviktori@redhat.com>
# Peter Lacko <placko@redhat.com>
#
# Copyright (C) 2012, 2016 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/plugins/ping.py` module, and XML-RPC in general.
"""
import pytest
from ipalib import errors, _
from ipatests.test_xmlrpc.tracker.base import Tracker
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, raises_exact
from ipatests.util import assert_equal, Fuzzy
@pytest.mark.tier1
class TestPing(XMLRPC_test):
"""Test functionality of the `ipalib/plugins/ping.py` module."""
tracker = Tracker()
def test_ping(self):
"""Ping the server."""
result = self.tracker.run_command('ping')
exp = {'summary': Fuzzy('IPA server version .*. API version .*')}
assert_equal(result, exp)
def test_ping_with_argument(self):
"""Try to ping with an argument."""
with raises_exact(errors.ZeroArgumentError(name='ping')):
self.tracker.run_command('ping', ['argument'])
def test_ping_with_option(self):
"""Try to ping with an option."""
with raises_exact(errors.OptionError(
_('Unknown option: %(option)s'), option='bad_arg')):
self.tracker.run_command('ping', bad_arg=True)
| 1,932
|
Python
|
.py
| 45
| 39
| 73
| 0.711016
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,491
|
test_sudorule_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_sudorule_plugin.py
|
# Authors:
# Jr Aquino <jr.aquino@citrixonline.com>
# Pavel Zuna <pzuna@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 the `ipaserver/plugins/sudorule.py` module.
"""
import pytest
import six
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, assert_attr_equal
from ipatests.test_xmlrpc.xmlrpc_test import assert_deepequal
from ipalib import api
from ipalib import errors
# pylint: disable=unused-variable
if six.PY3:
unicode = str
@pytest.mark.tier1
class test_sudorule(XMLRPC_test):
"""
Test the `sudorule` plugin.
"""
rule_name = u'testing_sudorule1'
rule_name2 = u'testing_sudorule2'
rule_renamed = u'testing_mega_sudorule'
rule_command = u'/usr/bin/testsudocmd1'
rule_desc = u'description'
rule_desc_mod = u'description modified'
test_user = u'sudorule_test_user'
test_external_user = u'external_test_user'
test_group = u'sudorule_test_group'
test_external_group = u'external_test_group'
test_host = u'sudorule.testhost'
test_external_host = u'external.testhost'
test_hostgroup = u'sudorule_test_hostgroup'
test_sudoallowcmdgroup = u'sudorule_test_allowcmdgroup'
test_sudodenycmdgroup = u'sudorule_test_denycmdgroup'
test_command = u'/usr/bin/testsudocmd1'
test_denycommand = u'/usr/bin/testdenysudocmd1'
test_runasuser = u'manager'
test_runasgroup = u'manager'
test_category = u'all'
test_option = u'authenticate'
test_option2 = u'fqdn'
test_option3 = u'log_allowed'
test_invalid_user = u'+invalid#user'
test_invalid_host = u'+invalid&host.nonexist.com'
test_invalid_group = u'+invalid#group'
def test_0_sudorule_add(self):
"""
Test adding a new Sudo rule using `xmlrpc.sudorule_add`.
"""
ret = self.failsafe_add(api.Object.sudorule,
self.rule_name,
description=self.rule_desc,
)
entry = ret['result']
assert_attr_equal(entry, 'cn', self.rule_name)
assert_attr_equal(entry, 'description', self.rule_desc)
def test_1_sudorule_add(self):
"""
Test adding an duplicate Sudo rule using `xmlrpc.sudorule_add'.
"""
with pytest.raises(errors.DuplicateEntry):
api.Command['sudorule_add'](
self.rule_name
)
def test_2_sudorule_show(self):
"""
Test displaying a Sudo rule using `xmlrpc.sudorule_show`.
"""
entry = api.Command['sudorule_show'](self.rule_name)['result']
assert_attr_equal(entry, 'cn', self.rule_name)
assert_attr_equal(entry, 'description', self.rule_desc)
def test_3_sudorule_mod(self):
"""
Test modifying a Sudo rule using `xmlrpc.sudorule_mod`.
"""
ret = api.Command['sudorule_mod'](
self.rule_name, description=self.rule_desc_mod
)
entry = ret['result']
assert_attr_equal(entry, 'description', self.rule_desc_mod)
def test_6_sudorule_find(self):
"""
Test searching for Sudo rules using `xmlrpc.sudorule_find`.
"""
ret = api.Command['sudorule_find'](
cn=self.rule_name,
description=self.rule_desc_mod
)
assert ret['truncated'] is False
entries = ret['result']
assert_attr_equal(entries[0], 'cn', self.rule_name)
assert_attr_equal(entries[0], 'description', self.rule_desc_mod)
def test_7_sudorule_init_testing_data(self):
"""
Initialize data for more Sudo rule plugin testing.
"""
self.failsafe_add(api.Object.user,
self.test_user, givenname=u'first', sn=u'last'
)
self.failsafe_add(api.Object.user,
self.test_runasuser, givenname=u'first', sn=u'last'
)
self.failsafe_add(api.Object.group,
self.test_group, description=u'description'
)
self.failsafe_add(api.Object.host,
self.test_host, force=True
)
self.failsafe_add(api.Object.hostgroup,
self.test_hostgroup, description=u'description'
)
self.failsafe_add(api.Object.sudocmdgroup,
self.test_sudoallowcmdgroup, description=u'desc'
)
self.failsafe_add(api.Object.sudocmdgroup,
self.test_sudodenycmdgroup, description=u'desc'
)
self.failsafe_add(api.Object.sudocmd,
self.test_command, description=u'desc'
)
def test_8_sudorule_add_user(self):
"""
Test adding user and group to Sudo rule using
`xmlrpc.sudorule_add_user`.
"""
ret = api.Command['sudorule_add_user'](
self.rule_name, user=self.test_user, group=self.test_group
)
assert ret['completed'] == 2
failed = ret['failed']
assert 'memberuser' in failed
assert 'user' in failed['memberuser']
assert not failed['memberuser']['user']
assert 'group' in failed['memberuser']
assert not failed['memberuser']['group']
entry = ret['result']
assert_attr_equal(entry, 'memberuser_user', self.test_user)
assert_attr_equal(entry, 'memberuser_group', self.test_group)
def test_9_a_show_user(self):
"""
Test showing a user to verify Sudo rule membership
`xmlrpc.user_show`.
"""
ret = api.Command['user_show'](self.test_user, all=True)
entry = ret['result']
assert_attr_equal(entry, 'memberof_sudorule', self.rule_name)
def test_9_b_show_group(self):
"""
Test showing a group to verify Sudo rule membership
`xmlrpc.group_show`.
"""
ret = api.Command['group_show'](self.test_group, all=True)
entry = ret['result']
assert_attr_equal(entry, 'memberof_sudorule', self.rule_name)
def test_9_sudorule_remove_user(self):
"""
Test removing user and group from Sudo rule using
`xmlrpc.sudorule_remove_user'.
"""
ret = api.Command['sudorule_remove_user'](
self.rule_name, user=self.test_user, group=self.test_group
)
assert ret['completed'] == 2
failed = ret['failed']
assert 'memberuser' in failed
assert 'user' in failed['memberuser']
assert not failed['memberuser']['user']
assert 'group' in failed['memberuser']
assert not failed['memberuser']['group']
entry = ret['result']
assert 'memberuser_user' not in entry
assert 'memberuser_group' not in entry
def test_a_sudorule_add_runasuser(self):
"""
Test adding run as user to Sudo rule using
`xmlrpc.sudorule_add_runasuser`.
"""
ret = api.Command['sudorule_add_runasuser'](
self.rule_name, user=self.test_runasuser
)
assert ret['completed'] == 1
failed = ret['failed']
assert 'ipasudorunas' in failed
assert 'user' in failed['ipasudorunas']
assert not failed['ipasudorunas']['user']
entry = ret['result']
assert_attr_equal(entry, 'ipasudorunas_user', self.test_runasuser)
def test_a_sudorule_add_runasuser_invalid(self):
"""
Test adding run as invalid user to Sudo rule using
`xmlrpc.sudorule_add_runasuser`.
"""
try:
api.Command['sudorule_add_runasuser'](
self.rule_name, user=self.test_invalid_user
)
except errors.ValidationError:
pass
else:
assert False
def test_b_sudorule_remove_runasuser(self):
"""
Test removing run as user to Sudo rule using
`xmlrpc.sudorule_remove_runasuser'.
"""
ret = api.Command['sudorule_remove_runasuser'](
self.rule_name, user=self.test_runasuser
)
assert ret['completed'] == 1
failed = ret['failed']
assert 'ipasudorunas' in failed
assert 'user' in failed['ipasudorunas']
assert not failed['ipasudorunas']['user']
entry = ret['result']
assert 'ipasudorunas_user' not in entry
def test_a_sudorule_add_runasgroup(self):
"""
Test adding run as group to Sudo rule using
`xmlrpc.sudorule_add_runasgroup`.
"""
ret = api.Command['sudorule_add_runasgroup'](
self.rule_name, group=self.test_runasgroup
)
assert ret['completed'] == 1
failed = ret['failed']
assert 'ipasudorunasgroup' in failed
assert 'group' in failed['ipasudorunasgroup']
assert not failed['ipasudorunasgroup']['group']
entry = ret['result']
assert_attr_equal(entry, 'ipasudorunasgroup_group',
self.test_runasgroup)
def test_a_sudorule_add_runasgroup_invalid(self):
"""
Test adding run as invalid user to Sudo rule using
`xmlrpc.sudorule_add_runasuser`.
"""
try:
api.Command['sudorule_add_runasgroup'](
self.rule_name, group=self.test_invalid_group
)
except errors.ValidationError:
pass
else:
assert False
def test_b_sudorule_remove_runasgroup(self):
"""
Test removing run as group to Sudo rule using
`xmlrpc.sudorule_remove_runasgroup'.
"""
ret = api.Command['sudorule_remove_runasgroup'](
self.rule_name, group=self.test_runasgroup
)
assert ret['completed'] == 1
failed = ret['failed']
assert 'ipasudorunasgroup' in failed
assert 'group' in failed['ipasudorunasgroup']
assert not failed['ipasudorunasgroup']['group']
entry = ret['result']
assert 'ipasudorunasgroup_group' not in entry
def test_a_sudorule_add_externaluser(self):
"""
Test adding an external user to Sudo rule using
`xmlrpc.sudorule_add_user`.
"""
ret = api.Command['sudorule_add_user'](
self.rule_name, user=self.test_external_user
)
assert ret['completed'] == 1
failed = ret['failed']
entry = ret['result']
assert_attr_equal(entry, 'externaluser', self.test_external_user)
def test_a_sudorule_add_externaluser_invalid(self):
"""
Test adding an invalid external user to Sudo rule using
`xmlrpc.sudorule_add_user`.
"""
try:
api.Command['sudorule_add_user'](
self.rule_name, user=self.test_invalid_user
)
except errors.ValidationError:
pass
else:
assert False
def test_b_sudorule_remove_externaluser(self):
"""
Test removing an external user from Sudo rule using
`xmlrpc.sudorule_remove_user'.
"""
ret = api.Command['sudorule_remove_user'](
self.rule_name, user=self.test_external_user
)
assert ret['completed'] == 1
failed = ret['failed']
entry = ret['result']
assert entry['externaluser'] == ()
def test_a_sudorule_add_runasexternaluser(self):
"""
Test adding an external runasuser to Sudo rule using
`xmlrpc.sudorule_add_runasuser`.
"""
ret = api.Command['sudorule_add_runasuser'](
self.rule_name, user=self.test_external_user
)
assert ret['completed'] == 1
failed = ret['failed']
entry = ret['result']
assert_attr_equal(entry, 'ipasudorunasextuser', self.test_external_user)
def test_b_sudorule_remove_runasexternaluser(self):
"""
Test removing an external runasuser from Sudo rule using
`xmlrpc.sudorule_remove_runasuser'.
"""
ret = api.Command['sudorule_remove_runasuser'](
self.rule_name, user=self.test_external_user
)
assert ret['completed'] == 1
failed = ret['failed']
entry = ret['result']
assert entry['ipasudorunasextuser'] == ()
def test_a_sudorule_add_runasexternalgroup(self):
"""
Test adding an external runasgroup to Sudo rule using
`xmlrpc.sudorule_add_runasgroup`.
"""
ret = api.Command['sudorule_add_runasgroup'](
self.rule_name, group=self.test_external_group
)
assert ret['completed'] == 1
failed = ret['failed']
entry = ret['result']
assert_attr_equal(entry, 'ipasudorunasextgroup', self.test_external_group)
def test_b_sudorule_remove_runasexternalgroup(self):
"""
Test removing an external runasgroup from Sudo rule using
`xmlrpc.sudorule_remove_runasgroup'.
"""
ret = api.Command['sudorule_remove_runasgroup'](
self.rule_name, group=self.test_external_group
)
assert ret['completed'] == 1
failed = ret['failed']
entry = ret['result']
assert entry['ipasudorunasextgroup'] == ()
def test_a_sudorule_add_option(self):
"""
Test adding an option to Sudo rule using
`xmlrpc.sudorule_add_option`.
"""
# Add a user and group to the sudorule so we can test that
# membership is properly translated in add_option.
ret = api.Command['sudorule_add_user'](
self.rule_name, user=self.test_user, group=self.test_group
)
assert ret['completed'] == 2
ret = api.Command['sudorule_add_option'](
self.rule_name, ipasudoopt=self.test_option
)
entry = ret['result']
assert_attr_equal(entry, 'ipasudoopt', self.test_option)
assert_attr_equal(entry, 'memberuser_user', self.test_user)
assert_attr_equal(entry, 'memberuser_group', self.test_group)
def test_b_sudorule_remove_option(self):
"""
Test removing an option from Sudo rule using
`xmlrpc.sudorule_remove_option'.
"""
ret = api.Command['sudorule_remove_option'](
self.rule_name, ipasudoopt=self.test_option
)
entry = ret['result']
assert 'ipasudoopt' not in entry
# Verify that membership is properly converted in remove_option
assert_attr_equal(entry, 'memberuser_user', self.test_user)
assert_attr_equal(entry, 'memberuser_group', self.test_group)
# Clean up by removing the user and group added in add_option
ret = api.Command['sudorule_remove_user'](
self.rule_name, user=self.test_user, group=self.test_group
)
assert ret['completed'] == 2
def test_c_sudorule_add_multiple_options(self):
"""
Test adding two options to Sudo rule using
`xmlrpc.sudorule_add_option`.
"""
ret = api.Command['sudorule_add_option'](
self.rule_name,
ipasudoopt=(self.test_option, self.test_option2, self.test_option3)
)
entry = ret['result']
assert_deepequal(entry.get('ipasudoopt'),
(self.test_option, self.test_option2,
self.test_option3))
def test_d_sudorule_add_duplicate_option(self):
"""
Test adding a duplicate option to Sudo rule using
`xmlrpc.sudorule_add_option`.
"""
with pytest.raises(errors.DuplicateEntry):
api.Command['sudorule_add_option'](
self.rule_name,
ipasudoopt=(self.test_option,)
)
def test_e_sudorule_remove_one_option(self):
"""
Test removing an option from Sudo rule using
`xmlrpc.sudorule_remove_option'.
"""
ret = api.Command['sudorule_remove_option'](
self.rule_name, ipasudoopt=self.test_option
)
entry = ret['result']
assert_deepequal(entry.get('ipasudoopt'),
(self.test_option2, self.test_option3))
def test_f_sudorule_remove_multiple_options(self):
"""
Test removing an option from Sudo rule using
`xmlrpc.sudorule_remove_option'.
"""
ret = api.Command['sudorule_remove_option'](
self.rule_name, ipasudoopt=(self.test_option2, self.test_option3)
)
entry = ret['result']
assert len(entry.get('ipasudoopt', [])) == 0
def test_g_sudorule_remove_unknown_option(self):
"""
Test removing an unknown option from Sudo rule using
`xmlrpc.sudorule_remove_option'.
"""
with pytest.raises(errors.AttrValueNotFound):
api.Command['sudorule_remove_option'](
self.rule_name,
ipasudoopt=(self.test_option,)
)
def test_a_sudorule_add_host(self):
"""
Test adding host and hostgroup to Sudo rule using
`xmlrpc.sudorule_add_host`.
"""
ret = api.Command['sudorule_add_host'](
self.rule_name, host=self.test_host, hostgroup=self.test_hostgroup
)
assert ret['completed'] == 2
failed = ret['failed']
assert 'memberhost' in failed
assert 'host' in failed['memberhost']
assert not failed['memberhost']['host']
assert 'hostgroup' in failed['memberhost']
assert not failed['memberhost']['hostgroup']
entry = ret['result']
assert_attr_equal(entry, 'memberhost_host', self.test_host)
assert_attr_equal(entry, 'memberhost_hostgroup', self.test_hostgroup)
def test_a_sudorule_show_host(self):
"""
Test showing host to verify Sudo rule membership
`xmlrpc.host_show`.
"""
ret = api.Command['host_show'](self.test_host, all=True)
entry = ret['result']
assert_attr_equal(entry, 'memberof_sudorule', self.rule_name)
def test_a_sudorule_show_hostgroup(self):
"""
Test showing hostgroup to verify Sudo rule membership
`xmlrpc.hostgroup_show`.
"""
ret = api.Command['hostgroup_show'](self.test_hostgroup, all=True)
entry = ret['result']
assert_attr_equal(entry, 'memberof_sudorule', self.rule_name)
def test_b_sudorule_remove_host(self):
"""
Test removing host and hostgroup from Sudo rule using
`xmlrpc.sudorule_remove_host`.
"""
ret = api.Command['sudorule_remove_host'](
self.rule_name, host=self.test_host, hostgroup=self.test_hostgroup
)
assert ret['completed'] == 2
failed = ret['failed']
assert 'memberhost' in failed
assert 'host' in failed['memberhost']
assert not failed['memberhost']['host']
assert 'hostgroup' in failed['memberhost']
assert not failed['memberhost']['hostgroup']
entry = ret['result']
assert 'memberhost_host' not in entry
assert 'memberhost_hostgroup' not in entry
def test_a_sudorule_add_externalhost(self):
"""
Test adding an external host to Sudo rule using
`xmlrpc.sudorule_add_host`.
"""
ret = api.Command['sudorule_add_host'](
self.rule_name, host=self.test_external_host
)
assert ret['completed'] == 1
failed = ret['failed']
entry = ret['result']
assert_attr_equal(entry, 'externalhost', self.test_external_host)
def test_a_sudorule_add_externalhost_invalid(self):
"""
Test adding an invalid external host to Sudo rule using
`xmlrpc.sudorule_add_host`.
"""
try:
api.Command['sudorule_add_host'](
self.rule_name, host=self.test_invalid_host
)
except errors.ValidationError:
pass
else:
assert False
def test_a_sudorule_mod_externalhost_invalid_addattr(self):
"""
Test adding an invalid external host to Sudo rule using
`xmlrpc.sudorule_mod --addattr`.
"""
try:
api.Command['sudorule_mod'](
self.rule_name,
addattr='externalhost=%s' % self.test_invalid_host
)
except errors.ValidationError as e:
assert unicode(e) == ("invalid 'externalhost': only letters, " +
"numbers, '_', '-' are allowed. " +
"DNS label may not start or end with '-'")
else:
assert False
def test_b_sudorule_remove_externalhost(self):
"""
Test removing an external host from Sudo rule using
`xmlrpc.sudorule_remove_host`.
"""
ret = api.Command['sudorule_remove_host'](
self.rule_name, host=self.test_external_host
)
assert ret['completed'] == 1
failed = ret['failed']
entry = ret['result']
assert len(entry['externalhost']) == 0
def test_a_sudorule_add_allow_command(self):
"""
Test adding allow command and cmdgroup to Sudo rule using
`xmlrpc.sudorule_add_allow_command`.
"""
ret = api.Command['sudorule_add_allow_command'](
self.rule_name, sudocmd=self.test_command,
sudocmdgroup=self.test_sudoallowcmdgroup
)
assert ret['completed'] == 2
failed = ret['failed']
assert 'memberallowcmd' in failed
assert 'sudocmd' in failed['memberallowcmd']
assert not failed['memberallowcmd']['sudocmd']
assert 'sudocmdgroup' in failed['memberallowcmd']
assert not failed['memberallowcmd']['sudocmdgroup']
entry = ret['result']
assert_attr_equal(entry, 'memberallowcmd_sudocmd', self.test_command)
assert_attr_equal(entry, 'memberallowcmd_sudocmdgroup',
self.test_sudoallowcmdgroup)
def test_a_sudorule_remove_allow_command(self):
"""
Test removing allow command and sudocmdgroup from Sudo rule using
`xmlrpc.sudorule_remove_command`.
"""
ret = api.Command['sudorule_remove_allow_command'](
self.rule_name, sudocmd=self.test_command,
sudocmdgroup=self.test_sudoallowcmdgroup
)
assert ret['completed'] == 2
failed = ret['failed']
assert 'memberallowcmd' in failed
assert 'sudocmd' in failed['memberallowcmd']
assert not failed['memberallowcmd']['sudocmd']
assert 'sudocmdgroup' in failed['memberallowcmd']
assert not failed['memberallowcmd']['sudocmdgroup']
entry = ret['result']
assert 'memberallowcmd_sudocmd' not in entry
assert 'memberallowcmd_sudocmdgroup' not in entry
def test_b_sudorule_add_deny_command(self):
"""
Test adding deny command and cmdgroup to Sudo rule using
`xmlrpc.sudorule_add_deny_command`.
"""
ret = api.Command['sudorule_add_deny_command'](
self.rule_name, sudocmd=self.test_command,
sudocmdgroup=self.test_sudodenycmdgroup
)
assert ret['completed'] == 2
failed = ret['failed']
assert 'memberdenycmd' in failed
assert 'sudocmd' in failed['memberdenycmd']
assert not failed['memberdenycmd']['sudocmd']
assert 'sudocmdgroup' in failed['memberdenycmd']
assert not failed['memberdenycmd']['sudocmdgroup']
entry = ret['result']
assert_attr_equal(entry, 'memberdenycmd_sudocmd', self.test_command)
assert_attr_equal(entry, 'memberdenycmd_sudocmdgroup',
self.test_sudodenycmdgroup)
def test_b_sudorule_remove_deny_command(self):
"""
Test removing deny command and sudocmdgroup from Sudo rule using
`xmlrpc.sudorule_remove_deny_command`.
"""
ret = api.Command['sudorule_remove_deny_command'](
self.rule_name, sudocmd=self.test_command,
sudocmdgroup=self.test_sudodenycmdgroup
)
assert ret['completed'] == 2
failed = ret['failed']
assert 'memberdenycmd' in failed
assert 'sudocmd' in failed['memberdenycmd']
assert not failed['memberdenycmd']['sudocmd']
assert 'sudocmdgroup' in failed['memberdenycmd']
assert not failed['memberdenycmd']['sudocmdgroup']
entry = ret['result']
assert 'memberdenycmd_sudocmd' not in entry
assert 'memberdenycmd_sudocmdgroup' not in entry
def test_c_sudorule_exclusiveuser(self):
"""
Test adding a user to an Sudo rule when usercat='all'
"""
api.Command['sudorule_mod'](self.rule_name, usercategory=u'all')
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['sudorule_add_user'](
self.rule_name, user=u'admin'
)
finally:
api.Command['sudorule_mod'](self.rule_name, usercategory=u'')
def test_d_sudorule_exclusiveuser(self):
"""
Test setting usercat='all' in an Sudo rule when there are users
"""
api.Command['sudorule_add_user'](self.rule_name, user=u'admin')
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['sudorule_mod'](
self.rule_name, usercategory=u'all'
)
finally:
api.Command['sudorule_remove_user'](self.rule_name, user=u'admin')
def test_e_sudorule_exclusivehost(self):
"""
Test adding a host to an Sudo rule when hostcat='all'
"""
api.Command['sudorule_mod'](self.rule_name, hostcategory=u'all')
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['sudorule_add_host'](
self.rule_name, host=self.test_host
)
finally:
api.Command['sudorule_mod'](self.rule_name, hostcategory=u'')
def test_f_sudorule_exclusivehost(self):
"""
Test setting hostcat='all' in an Sudo rule when there are hosts
"""
api.Command['sudorule_add_host'](self.rule_name, host=self.test_host)
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['sudorule_mod'](
self.rule_name, hostcategory=u'all'
)
finally:
api.Command['sudorule_remove_host'](self.rule_name, host=self.test_host)
def test_g_sudorule_exclusivecommand(self):
"""
Test adding a command to an Sudo rule when cmdcategory='all'
"""
api.Command['sudorule_mod'](self.rule_name, cmdcategory=u'all')
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['sudorule_add_allow_command'](
self.rule_name, sudocmd=self.test_command
)
finally:
api.Command['sudorule_mod'](self.rule_name, cmdcategory=u'')
def test_h_sudorule_exclusivecommand(self):
"""
Test setting cmdcategory='all' in an Sudo rule when there are commands
"""
api.Command['sudorule_add_allow_command'](self.rule_name, sudocmd=self.test_command)
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['sudorule_mod'](
self.rule_name, cmdcategory=u'all'
)
finally:
api.Command['sudorule_remove_allow_command'](self.rule_name, sudocmd=self.test_command)
def test_i_sudorule_exclusiverunas(self):
"""
Test adding a runasuser to an Sudo rule when ipasudorunasusercategory='all'
"""
api.Command['sudorule_mod'](self.rule_name, ipasudorunasusercategory=u'all')
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['sudorule_add_runasuser'](
self.rule_name, user=self.test_user
)
finally:
api.Command['sudorule_mod'](self.rule_name, ipasudorunasusercategory=u'')
def test_j_1_sudorule_exclusiverunas(self):
"""
Test setting ipasudorunasusercategory='all' in an Sudo rule when there are runas users
"""
api.Command['sudorule_add_runasuser'](self.rule_name, user=self.test_user)
try:
with pytest.raises(errors.MutuallyExclusiveError):
api.Command['sudorule_mod'](
self.rule_name, ipasudorunasusercategory=u'all'
)
finally:
api.Command['sudorule_remove_runasuser'](self.rule_name,
user=self.test_user)
def test_j_2_sudorule_referential_integrity(self):
"""
Test adding various links to Sudo rule
"""
api.Command['sudorule_add_user'](self.rule_name, user=self.test_user)
api.Command['sudorule_add_runasuser'](self.rule_name, user=self.test_runasuser,
group=self.test_group)
api.Command['sudorule_add_runasgroup'](self.rule_name, group=self.test_group)
api.Command['sudorule_add_host'](self.rule_name, host=self.test_host)
api.Command['sudorule_add_allow_command'](self.rule_name,
sudocmd=self.test_command)
api.Command['sudorule_add_deny_command'](self.rule_name,
sudocmdgroup=self.test_sudodenycmdgroup)
entry = api.Command['sudorule_show'](self.rule_name)['result']
assert_attr_equal(entry, 'cn', self.rule_name)
assert_attr_equal(entry, 'memberuser_user', self.test_user)
assert_attr_equal(entry, 'memberallowcmd_sudocmd', self.test_command)
assert_attr_equal(entry, 'memberdenycmd_sudocmdgroup',
self.test_sudodenycmdgroup)
assert_attr_equal(entry, 'memberhost_host', self.test_host)
assert_attr_equal(entry, 'ipasudorunas_user', self.test_runasuser)
assert_attr_equal(entry, 'ipasudorunas_group', self.test_group)
assert_attr_equal(entry, 'ipasudorunasgroup_group', self.test_group)
def test_k_1_sudorule_clear_testing_data(self):
"""
Clear data for Sudo rule plugin testing.
"""
api.Command['user_del'](self.test_user)
api.Command['user_del'](self.test_runasuser)
api.Command['group_del'](self.test_group)
api.Command['host_del'](self.test_host)
api.Command['hostgroup_del'](self.test_hostgroup)
api.Command['sudorule_remove_allow_command'](self.rule_name,
sudocmd=self.test_command)
api.Command['sudocmd_del'](self.test_command)
api.Command['sudocmdgroup_del'](self.test_sudoallowcmdgroup)
api.Command['sudocmdgroup_del'](self.test_sudodenycmdgroup)
def test_k_2_sudorule_referential_integrity(self):
"""
Test that links in Sudo rule were removed by referential integrity plugin
"""
entry = api.Command['sudorule_show'](self.rule_name)['result']
assert_attr_equal(entry, 'cn', self.rule_name)
assert 'memberuser_user' not in entry
assert 'memberallowcmd_sudocmd' not in entry
assert 'memberdenycmd_sudocmdgroup' not in entry
assert 'memberhost_host' not in entry
assert 'ipasudorunas_user' not in entry
assert 'ipasudorunas_group' not in entry
assert 'ipasudorunasgroup_group' not in entry
def test_l_sudorule_order(self):
"""
Test that order uniqueness is maintained
"""
api.Command['sudorule_mod'](self.rule_name, sudoorder=1)
api.Command['sudorule_add'](self.rule_name2)
# mod of rule that has no order and set a duplicate
try:
api.Command['sudorule_mod'](self.rule_name2, sudoorder=1)
except errors.ValidationError:
pass
# Remove the rule so we can re-add it
api.Command['sudorule_del'](self.rule_name2)
# add a new rule with a duplicate order
with pytest.raises(errors.ValidationError):
api.Command['sudorule_add'](self.rule_name2, sudoorder=1)
# add a new rule with a unique order
api.Command['sudorule_add'](self.rule_name2, sudoorder=2)
with pytest.raises(errors.ValidationError):
api.Command['sudorule_mod'](self.rule_name2, sudoorder=1)
# Try setting both to 0
api.Command['sudorule_mod'](self.rule_name2, sudoorder=0)
with pytest.raises(errors.ValidationError):
api.Command['sudorule_mod'](self.rule_name, sudoorder=0)
# Try unsetting sudoorder from both rules
api.Command['sudorule_mod'](self.rule_name, sudoorder=None)
api.Command['sudorule_mod'](self.rule_name2, sudoorder=None)
def test_l_1_sudorule_rename(self):
"""
Test renaming an HBAC rule, rename it back afterwards
"""
api.Command['sudorule_mod'](
self.rule_name, rename=self.rule_renamed
)
entry = api.Command['sudorule_show'](self.rule_renamed)['result']
assert_attr_equal(entry, 'cn', self.rule_renamed)
# clean up by renaming the rule back
api.Command['sudorule_mod'](
self.rule_renamed, rename=self.rule_name
)
def test_m_sudorule_del(self):
"""
Test deleting a Sudo rule using `xmlrpc.sudorule_del`.
"""
api.Command['sudorule_del'](self.rule_name)
# verify that it's gone
with pytest.raises(errors.NotFound):
api.Command['sudorule_show'](self.rule_name)
api.Command['sudorule_del'](self.rule_name2)
| 34,263
|
Python
|
.py
| 830
| 31.727711
| 99
| 0.615
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,492
|
objectclasses.py
|
freeipa_freeipa/ipatests/test_xmlrpc/objectclasses.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/>.
"""
Defines the expected objectclass for various entries.
"""
user_base = [
u'top',
u'person',
u'organizationalperson',
u'inetorgperson',
u'inetuser',
u'posixaccount',
u'krbprincipalaux',
u'krbticketpolicyaux',
u'ipaobject',
u'ipasshuser',
u'ipaSshGroupOfPubKeys',
]
user = user_base + [u'mepOriginEntry', 'ipantuserattrs',]
group = [
u'top',
u'groupofnames',
u'nestedgroup',
u'ipausergroup',
u'ipaobject',
]
externalgroup = group + [u'ipaexternalgroup']
posixgroup = group + [u'posixgroup', 'ipantgroupattrs']
host = [
u'ipasshhost',
u'ipaSshGroupOfPubKeys',
u'ieee802device',
u'ipaobject',
u'nshost',
u'ipahost',
u'pkiuser',
u'ipaservice',
u'krbprincipalaux',
u'krbprincipal',
u'top',
]
hostgroup = [
u'ipaobject',
u'ipahostgroup',
u'nestedGroup',
u'groupOfNames',
u'top',
u'mepOriginEntry',
]
role = [
u'groupofnames',
u'nestedgroup',
u'top',
]
system_permission = [
u'groupofnames',
u'ipapermission',
u'top'
]
permission = system_permission + [
u'ipapermissionv2',
]
privilege = [
u'nestedgroup',
u'groupofnames',
u'top'
]
service = [
u'krbprincipal',
u'krbprincipalaux',
u'krbticketpolicyaux',
u'ipaobject',
u'ipaservice',
u'pkiuser',
u'ipakrbprincipal',
u'top',
]
hbacsvc = [
u'ipaobject',
u'ipahbacservice',
]
hbacsvcgroup = [
u'ipaobject',
u'ipahbacservicegroup',
u'groupOfNames',
u'top',
]
sudocmd = [
u'ipaobject',
u'ipasudocmd',
]
sudocmdgroup = [
u'ipaobject',
u'ipasudocmdgrp',
u'groupOfNames',
u'top',
]
netgroup = [
u'ipaobject',
u'ipaassociation',
u'ipanisnetgroup',
]
automember = [
u'top',
u'automemberregexrule',
]
selinuxusermap = [
u'ipaassociation',
u'ipaselinuxusermap',
]
hbacrule = [
u'ipaassociation',
u'ipahbacrule',
]
dnszone = [
u'top',
u'idnsrecord',
u'idnszone',
]
dnsforwardzone = [
u'top',
u'idnsforwardzone',
]
dnsrecord = [
u'top',
u'idnsrecord',
]
realmdomains = [
u'top',
u'nsContainer',
u'domainRelatedObject',
]
radiusproxy = [
u'ipatokenradiusconfiguration',
u'top',
]
pwpolicy = [
u'krbpwdpolicy',
u'ipapwdpolicy',
u'nscontainer',
u'top',
]
idview = [
u'ipaIDView',
u'nsContainer',
u'top'
]
idoverrideuser = [
u'ipaOverrideAnchor',
u'top',
u'ipaUserOverride',
u'ipasshuser',
u'ipaSshGroupOfPubKeys'
]
idoverridegroup = [
u'ipaOverrideAnchor',
u'top',
u'ipaGroupOverride',
]
servicedelegationrule = [
u'top',
u'groupofprincipals',
u'ipakrb5delegationacl',
]
servicedelegationtarget = [
u'top',
u'groupofprincipals',
]
certprofile = [
u'top',
u'ipacertprofile',
]
caacl = [
u'ipaassociation',
u'ipacaacl'
]
ca = [
u'top',
u'ipaca',
]
certmaprule = [
u'top',
u'ipacertmaprule',
]
certmapconfig = [
u'top',
u'nsContainer',
u'ipaCertMapConfigObject',
]
idp = [
'top',
'ipaidp',
]
passkeyconfig = [
'top',
'nscontainer',
'ipapasskeyconfigobject',
]
| 3,980
|
Python
|
.py
| 214
| 15.17757
| 71
| 0.667114
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,493
|
test_env_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_env_plugin.py
|
#
# Copyright (C) 2021 FreeIPA Contributors see COPYING for license
#
"""Test `env` plugin
"""
import pytest
from ipalib import api, errors
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test
@pytest.mark.tier1
class TestEnv(XMLRPC_test):
"""Test `env` plugin
"""
EXPECTED_KEYS = ("result", "count", "total", "summary")
def run_env(self, *args, **options):
cmd = api.Command.env
cmd_result = cmd(*args, **options)
return cmd_result
def assert_result(self, cmd_result):
assert tuple(cmd_result.keys()) == self.EXPECTED_KEYS
result = cmd_result["result"]
assert isinstance(result, dict)
total_count = cmd_result["total"]
assert isinstance(total_count, int)
actual_count = cmd_result["count"]
assert isinstance(actual_count, int)
assert actual_count <= total_count
assert len(result) == actual_count
if actual_count > 1:
assert cmd_result["summary"] == f"{actual_count} variables"
else:
assert cmd_result["summary"] is None
@pytest.mark.parametrize(
"server", [True, False, None], ids=["server", "local", "local_default"]
)
def test_env(self, server):
options = {}
if server is not None:
options = {"server": server}
cmd_result = self.run_env(**options)
self.assert_result(cmd_result)
actual_count = cmd_result["count"]
assert actual_count >= 1
assert cmd_result["total"] == actual_count
assert cmd_result["result"]["in_server"] is (server is True)
@pytest.mark.parametrize(
"args, kwargs",
[(("in_server",), {}), ((), {"variables": "in_server"})],
ids=["var_as_pos_arg", "var_as_known_arg"],
)
@pytest.mark.parametrize(
"server", [True, False], ids=["server", "local"]
)
def test_env_with_variables_one(self, args, kwargs, server):
kwargs["server"] = server
cmd_result = self.run_env(*args, **kwargs)
self.assert_result(cmd_result)
result = cmd_result["result"]
assert result["in_server"] is server
assert cmd_result["count"] == 1
@pytest.mark.parametrize(
"args, kwargs",
[
(("in_server", "version"), {}),
((), {"variables": ("in_server", "version")}),
],
ids=["vars_as_pos_args", "vars_as_known_args"],
)
@pytest.mark.parametrize(
"server", [True, False], ids=["server", "local"]
)
def test_env_with_variables_several(self, args, kwargs, server):
kwargs["server"] = server
cmd_result = self.run_env(*args, **kwargs)
self.assert_result(cmd_result)
result = cmd_result["result"]
assert result["in_server"] is server
assert cmd_result["count"] == 2
@pytest.mark.parametrize("server", [True, False], ids=["server", "local"])
def test_env_with_variables_missing_var(self, server):
cmd_result = self.run_env("nonexistentvariable", server=server)
self.assert_result(cmd_result)
assert cmd_result["count"] == 0
@pytest.mark.parametrize("server", [True, False], ids=["server", "local"])
def test_env_with_nonexistent_option(self, server):
with pytest.raises(errors.OptionError) as e:
self.run_env(nonexistentoption="nonexistentoption", server=server)
assert "Unknown option: nonexistentoption" in str(e.value)
| 3,473
|
Python
|
.py
| 87
| 32.413793
| 79
| 0.610617
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,494
|
test_attr.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_attr.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Filip Skola <fskola@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 --setattr and --addattr and other attribute-specific issues
"""
from ipalib.constants import LDAP_GENERALIZED_TIME_FORMAT
from ipalib import errors
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, raises_exact
from ipatests.test_xmlrpc.tracker.user_plugin import UserTracker
import pytest
from datetime import datetime
@pytest.fixture(scope='class')
def user(request, xmlrpc_setup):
tracker = UserTracker(name=u'user1', givenname=u'Test', sn=u'User1')
return tracker.make_fixture(request)
@pytest.fixture(scope='class')
def manager(request, xmlrpc_setup):
tracker = UserTracker(name=u'manager', givenname=u'Test', sn=u'Manager')
return tracker.make_fixture(request)
@pytest.mark.tier1
class TestAttrOnUser(XMLRPC_test):
def test_add_user_with_singlevalue_addattr(self):
""" Try to add a user with single-value attribute
set via option and --addattr """
user = UserTracker(name=u'user', givenname=u'Test', sn=u'User1',
addattr=u'sn=User2')
command = user.make_create_command()
with raises_exact(errors.OnlyOneValueAllowed(attr='sn')):
command()
def test_create_user(self, user):
""" Create a test user """
user.ensure_exists()
def test_change_givenname_add_mail_user(self, user):
""" Change givenname, add mail to user """
user.ensure_exists()
user.update(
dict(setattr=(u'givenname=Finkle', u'mail=test@example.com')),
dict(givenname=[u'Finkle'], mail=[u'test@example.com'], setattr='')
)
def test_add_another_mail_user(self, user):
""" Add another mail to user """
user.ensure_exists()
update = u'test2@example.com'
user.attrs['mail'].append(update)
user.update(dict(addattr='mail='+update),
dict(addattr=''))
def test_add_two_phone_numbers_at_once_user(self, user):
""" Add two phone numbers at once to user """
user.ensure_exists()
update1 = u'410-555-1212'
update2 = u'301-555-1212'
user.update(
dict(setattr=u'telephoneNumber='+update1,
addattr=u'telephoneNumber='+update2),
dict(addattr='', setattr='',
telephonenumber=[update1, update2]))
def test_go_from_two_phone_numbers_to_one(self, user):
""" Go from two phone numbers to one for user """
update = u'301-555-1212'
user.ensure_exists()
user.update(dict(setattr=u'telephoneNumber='+update),
dict(setattr='', telephonenumber=[update]))
def test_add_two_more_phone_numbers(self, user):
""" Add two more phone numbers to user """
user.ensure_exists()
update1 = u'703-555-1212'
update2 = u'202-888-9833'
user.attrs['telephonenumber'].extend([update1, update2])
user.update(dict(addattr=(u'telephoneNumber='+update1,
u'telephoneNumber='+update2)),
dict(addattr=''))
def test_delete_one_phone_number(self, user):
""" Delete one phone number for user """
user.ensure_exists()
update = u'301-555-1212'
user.attrs['telephonenumber'].remove(update)
user.update(dict(delattr=u'telephoneNumber='+update), dict(delattr=''))
def test_delete_the_number_again(self, user):
""" Try deleting the number again for user """
user.ensure_exists()
update = u'301-555-1212'
command = user.make_update_command(
dict(delattr=u'telephoneNumber='+update))
with raises_exact(errors.AttrValueNotFound(
attr=u'telephonenumber', value=update)):
command()
def test_add_and_delete_one_phone_number(self, user):
""" Add and delete one phone number for user """
user.ensure_exists()
update1 = u'202-888-9833'
update2 = u'301-555-1212'
user.attrs['telephonenumber'].remove(update1)
user.attrs['telephonenumber'].append(update2)
user.update(dict(addattr=u'telephoneNumber='+update2,
delattr=u'telephoneNumber='+update1),
dict(addattr='', delattr=''))
def test_add_and_delete_the_same_phone_number(self, user):
""" Add and delete the same phone number for user """
user.ensure_exists()
update1 = u'301-555-1212'
update2 = u'202-888-9833'
user.attrs['telephonenumber'].append(update2)
user.update(dict(addattr=(u'telephoneNumber='+update1,
u'telephoneNumber='+update2),
delattr=u'telephoneNumber='+update1),
dict(addattr='', delattr=''))
def test_set_and_delete_a_phone_number(self, user):
""" Set and delete a phone number for user """
user.ensure_exists()
update1 = u'301-555-1212'
update2 = u'202-888-9833'
user.attrs.update(telephonenumber=[update2])
user.update(dict(setattr=(u'telephoneNumber='+update1,
u'telephoneNumber='+update2),
delattr=u'telephoneNumber='+update1),
dict(setattr='', delattr=''))
def test_set_givenname_to_none_with_setattr(self, user):
""" Try setting givenname to None with setattr in user """
user.ensure_exists()
command = user.make_update_command(dict(setattr=(u'givenname=')))
with raises_exact(errors.RequirementError(name='first')):
command()
def test_set_givenname_to_none_with_option(self, user):
""" Try setting givenname to None with option in user """
user.ensure_exists()
command = user.make_update_command(dict(givenname=None))
with raises_exact(errors.RequirementError(name='first')):
command()
def test_set_givenname_with_option_in_user(self, user):
""" Make sure setting givenname works with option in user """
user.ensure_exists()
user.update(dict(givenname=u'Fred'))
def test_set_givenname_with_setattr_in_user(self, user):
""" Make sure setting givenname works with setattr in user """
user.ensure_exists()
user.update(dict(setattr=u'givenname=Finkle'),
dict(givenname=[u'Finkle'], setattr=''))
def test_remove_empty_location_from_user(self, user):
""" Try to "remove" empty location from user """
user.ensure_exists()
command = user.make_update_command(dict(l=None))
with raises_exact(errors.EmptyModlist()):
command()
def test_lock_user_using_setattr(self, user):
""" Lock user using setattr """
user.ensure_exists()
user.update(dict(setattr=u'nsaccountlock=TrUe'),
dict(nsaccountlock=True, setattr=''))
def test_unlock_user_using_addattr_delattr(self, user):
""" Unlock user using addattr&delattr """
user.ensure_exists()
user.update(dict(addattr=u'nsaccountlock=FaLsE',
delattr=u'nsaccountlock=TRUE'),
dict(addattr='', delattr='', nsaccountlock=False))
def test_add_and_delete_datetime(self, user):
""" Delete a datetime data type """
user.ensure_exists()
# Set to a known value, then delete that value
expdate = u'20220210144006Z'
user.update(
dict(setattr=u'krbpasswordexpiration=' + expdate),
dict(krbpasswordexpiration=[
datetime.strptime(expdate, LDAP_GENERALIZED_TIME_FORMAT)
], setattr='')
)
user.update(
dict(delattr=u'krbpasswordexpiration=' + expdate),
dict(delattr='')
)
def test_delete_nonexistent_datetime(self, user):
""" Delete a datetime data type that isn't in the entry """
user.ensure_exists()
expdate = u'20220210144006Z'
bad_expdate = u'20280210144006Z'
user.update(
dict(setattr=u'krbpasswordexpiration=' + expdate),
dict(krbpasswordexpiration=[
datetime.strptime(expdate, LDAP_GENERALIZED_TIME_FORMAT)
], setattr='')
)
command = user.make_update_command(
dict(delattr=u'krbpasswordexpiration=' + bad_expdate),
)
with raises_exact(errors.AttrValueNotFound(
attr='krbpasswordexpiration', value=bad_expdate)):
command()
def test_add_and_delete_DN(self, user, manager):
""" Delete a DN data type """
user.ensure_exists()
manager.ensure_exists()
user.update(
dict(setattr=u'manager=manager'),
dict(manager=['manager'], setattr='')
)
command = user.make_update_command(
dict(delattr=u'manager=manager'),
)
# Setting works because the user plugin knows the container
# to convert a string to a DN. Passing in just the uid we
# don't have the context in ldap.decode() to know the entry
# type so `ipa user-mod someuser --delattr manager=foo` will
# fail.
with raises_exact(errors.AttrValueNotFound(
attr='manager', value='manager')):
command()
@pytest.mark.tier1
class TestAttrOnConfigs(XMLRPC_test):
def test_add_new_group_search_fields_config_entry(self, user):
""" Try adding a new group search fields config entry """
command = user.make_command(
'config_mod', **dict(addattr=u'ipagroupsearchfields=newattr')
)
with raises_exact(errors.OnlyOneValueAllowed(
attr='ipagroupsearchfields')):
command()
def test_add_a_new_cert_subject_base_config_entry(self, user):
""" Try adding a new cert subject base config entry """
command = user.make_command(
'config_mod',
**dict(
addattr=u'ipacertificatesubjectbase=0=DOMAIN.COM')
)
with raises_exact(errors.ValidationError(
name='ipacertificatesubjectbase',
error='attribute is not configurable')):
command()
def test_delete_required_config_entry(self, user):
""" Try deleting a required config entry """
command = user.make_command(
'config_mod',
**dict(delattr=u'ipasearchrecordslimit=100')
)
with raises_exact(errors.RequirementError(
name='searchrecordslimit')):
command()
def test_set_nonexistent_attribute(self, user):
""" Try setting a nonexistent attribute """
command = user.make_command(
'config_mod', **dict(setattr=u'invalid_attr=false')
)
with raises_exact(errors.ObjectclassViolation(
info='attribute "invalid_attr" not allowed')):
command()
def test_set_outofrange_krbpwdmaxfailure(self, user):
""" Try setting out-of-range krbpwdmaxfailure """
command = user.make_command(
'pwpolicy_mod', **dict(setattr=u'krbpwdmaxfailure=-1')
)
with raises_exact(errors.ValidationError(
name='krbpwdmaxfailure', error='must be at least 0')):
command()
def test_set_outofrange_maxfail(self, user):
""" Try setting out-of-range maxfail """
command = user.make_command(
'pwpolicy_mod', **dict(krbpwdmaxfailure=u'-1')
)
with raises_exact(errors.ValidationError(
name='maxfail', error='must be at least 0')):
command()
def test_set_nonnumeric_krbpwdmaxfailure(self, user):
""" Try setting non-numeric krbpwdmaxfailure """
command = user.make_command(
'pwpolicy_mod', **dict(setattr=u'krbpwdmaxfailure=abc')
)
with raises_exact(errors.ConversionError(
name='krbpwdmaxfailure', error='must be an integer')):
command()
def test_set_nonnumeric_maxfail(self, user):
""" Try setting non-numeric maxfail """
command = user.make_command(
'pwpolicy_mod', **dict(krbpwdmaxfailure=u'abc')
)
with raises_exact(errors.ConversionError(
name='maxfail', error='must be an integer')):
command()
def test_delete_bogus_attribute(self, user):
""" Try deleting bogus attribute """
command = user.make_command(
'config_mod', **dict(delattr=u'bogusattribute=xyz')
)
with raises_exact(errors.ValidationError(
name='bogusattribute',
error='No such attribute on this entry')):
command()
def test_delete_empty_attribute(self, user):
""" Try deleting empty attribute """
command = user.make_command(
'config_mod',
**dict(delattr=u'ipaCustomFields=See Also,seealso,false')
)
with raises_exact(errors.ValidationError(
name='ipacustomfields',
error='No such attribute on this entry')):
command()
def test_set_and_del_value_and_del_missing_one(self, user):
""" Set and delete one value, plus try deleting a missing one """
command = user.make_command(
'config_mod', **dict(
delattr=[u'ipaCustomFields=See Also,seealso,false',
u'ipaCustomFields=Country,c,false'],
addattr=u'ipaCustomFields=See Also,seealso,false')
)
with raises_exact(errors.AttrValueNotFound(
attr='ipacustomfields', value='Country,c,false')):
command()
def test_delete_an_operational_attribute_with_delattr(self, user):
""" Try to delete an operational attribute with --delattr """
command = user.make_command(
'config_mod', **dict(
delattr=u'creatorsName=cn=directory manager')
)
with raises_exact(errors.DatabaseError(
desc='Server is unwilling to perform', info='')):
command()
| 14,931
|
Python
|
.py
| 331
| 35.169184
| 79
| 0.617641
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,495
|
test_automount_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/test_automount_plugin.py
|
# Authors:
# Rob Crittenden <rcritten@redhat.com>
# Pavel Zuna <pzuna@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/plugins/automount.py' module.
"""
import textwrap
import tempfile
import shutil
from ipalib import api
from ipalib import errors
from ipapython.dn import DN
import pytest
import six
from ipatests.test_xmlrpc.xmlrpc_test import XMLRPC_test, assert_attr_equal
from ipatests.util import assert_deepequal
if six.PY3:
unicode = str
class MockTextui(list):
"""Collects output lines"""
# Extend the mock object if other textui methods are called
def print_plain(self, line):
self.append(unicode(line))
class AutomountTest(XMLRPC_test):
"""Provides common functionality for automount tests"""
locname = u'testlocation'
tofiles_output = '' # To be overridden
def check_tofiles(self):
"""Check automountlocation_tofiles output against self.tofiles_output
"""
res = api.Command['automountlocation_tofiles'](self.locname)
mock_ui = MockTextui()
command = api.Command['automountlocation_tofiles']
command.output_for_cli(mock_ui, res, self.locname, version=u'2.88')
expected_output = self.tofiles_output
assert_deepequal(expected_output, u'\n'.join(mock_ui))
def check_import_roundtrip(self):
"""Check automountlocation_tofiles/automountlocation_import roundtrip
Loads self.tofiles_output (which should correspond to
automountlocation_tofiles output), then checks the resulting map
against tofiles_output again.
Do not use this if the test creates maps that aren't connected to
auto.master -- these can't be imported successfully.
"""
conf_directory = tempfile.mkdtemp()
# Parse the tofiles_output into individual files, replace /etc/ by
# our temporary directory name
current_file = None
for line in self.tofiles_output.splitlines():
line = line.replace('/etc/', '%s/' % conf_directory)
if line.startswith(conf_directory) and line.endswith(':'):
current_file = open(line.rstrip(':'), 'w')
elif '--------' in line:
current_file.close()
elif line.startswith('maps not connected to '):
break
else:
current_file.write(line + '\n')
assert current_file is not None, ('The input file does not contain any'
'records of files to be opened.')
current_file.close()
self.failsafe_add(api.Object.automountlocation, self.locname)
try:
# Feed the files to automountlocation_import & check
master_file = u'%s/auto.master' % conf_directory
automountlocation_import = api.Command['automountlocation_import']
res = automountlocation_import(self.locname, master_file,
version=u'2.88')
assert_deepequal(dict(
result=dict(
keys=lambda k: k,
maps=lambda m: m,
skipped=(),
duplicatemaps=(),
duplicatekeys=(),
)), res)
self.check_tofiles()
finally:
res = api.Command['automountlocation_del'](self.locname)['result']
assert res
assert not res['failed']
# Success; delete the temporary directory
shutil.rmtree(conf_directory)
@pytest.mark.tier1
class test_automount(AutomountTest):
"""
Test the `automount` plugin.
"""
mapname = u'testmap'
keyname = u'testkey'
keyname_rename = u'testkey_rename'
keyname2 = u'testkey2'
description = u'description of map'
info = u'ro'
newinfo = u'rw'
map_kw = {'automountmapname': mapname, 'description': description, 'raw': True}
key_kw = {'automountkey': keyname, 'automountinformation': info, 'raw': True}
key_kw2 = {'automountkey': keyname2, 'automountinformation': info, 'raw': True}
tofiles_output = textwrap.dedent(u"""
/etc/auto.master:
/-\t/etc/auto.direct
---------------------------
/etc/auto.direct:
maps not connected to /etc/auto.master:
---------------------------
/etc/testmap:
testkey2\tro
testkey_rename\trw
""").strip()
def test_0_automountlocation_add(self):
"""
Test adding a location `xmlrpc.automountlocation_add` method.
"""
ret = self.failsafe_add(
api.Object.automountlocation, self.locname
)
entry = ret['result']
assert_attr_equal(entry, 'cn', self.locname)
def test_1_automountmap_add(self):
"""
Test adding a map `xmlrpc.automountmap_add` method.
"""
res = api.Command['automountmap_add'](self.locname, **self.map_kw)['result']
assert res
assert_attr_equal(res, 'automountmapname', self.mapname)
def test_2_automountkey_add(self):
"""
Test adding a key using `xmlrpc.automountkey_add` method.
"""
res = api.Command['automountkey_add'](self.locname, self.mapname, **self.key_kw2)['result']
assert res
assert_attr_equal(res, 'automountkey', self.keyname2)
def test_3_automountkey_add(self):
"""
Test adding a key using `xmlrpc.automountkey_add` method.
"""
res = api.Command['automountkey_add'](self.locname, self.mapname, **self.key_kw)['result']
assert res
assert_attr_equal(res, 'automountkey', self.keyname)
def test_4_automountkey_add(self):
"""
Test adding a duplicate key using `xmlrpc.automountkey_add` method.
"""
with pytest.raises(errors.DuplicateEntry):
api.Command['automountkey_add'](
self.locname, self.mapname, **self.key_kw)
def test_5_automountmap_show(self):
"""
Test the `xmlrpc.automountmap_show` method.
"""
res = api.Command['automountmap_show'](self.locname, self.mapname, raw=True)['result']
assert res
assert_attr_equal(res, 'automountmapname', self.mapname)
def test_6_automountmap_find(self):
"""
Test the `xmlrpc.automountmap_find` method.
"""
res = api.Command['automountmap_find'](self.locname, self.mapname, raw=True)['result']
assert_attr_equal(res[0], 'automountmapname', self.mapname)
def test_7_automountkey_show(self):
"""
Test the `xmlrpc.automountkey_show` method.
"""
showkey_kw={'automountkey': self.keyname, 'automountinformation' : self.info, 'raw': True}
res = api.Command['automountkey_show'](self.locname, self.mapname, **showkey_kw)['result']
assert res
assert_attr_equal(res, 'automountkey', self.keyname)
assert_attr_equal(res, 'automountinformation', self.info)
def test_8_automountkey_find(self):
"""
Test the `xmlrpc.automountkey_find` method.
"""
res = api.Command['automountkey_find'](self.locname, self.mapname, raw=True)['result']
assert res
assert len(res) == 2
assert_attr_equal(res[0], 'automountkey', self.keyname)
assert_attr_equal(res[0], 'automountinformation', self.info)
def test_9_automountkey_mod(self):
"""
Test the `xmlrpc.automountkey_mod` method.
"""
self.key_kw['newautomountinformation'] = self.newinfo
self.key_kw['rename'] = self.keyname_rename
res = api.Command['automountkey_mod'](self.locname, self.mapname, **self.key_kw)['result']
assert res
assert_attr_equal(res, 'automountinformation', self.newinfo)
assert_attr_equal(res, 'automountkey', self.keyname_rename)
def test_a1_automountmap_mod(self):
"""
Test the `xmlrpc.automountmap_mod` method.
"""
mod_kw = {'description': u'new description'}
res = api.Command['automountmap_mod'](self.locname, self.mapname, **mod_kw)['result']
assert res
assert_attr_equal(res, 'description', 'new description')
def test_a2_automountmap_tofiles(self):
"""
Test the `automountlocation_tofiles` command.
"""
res = api.Command['automountlocation_tofiles'](self.locname,
version=u'2.88')
assert_deepequal(dict(
result=dict(
keys={'auto.direct': ()},
orphanmaps=(dict(
dn=DN(('automountmapname', self.mapname),
('cn', self.locname),
('cn', 'automount'), api.env.basedn),
description=(u'new description',),
automountmapname=(u'testmap',)),),
orphankeys=[(
dict(
dn=DN(('description', self.keyname2),
('automountmapname', 'testmap'),
('cn', self.locname),
('cn', 'automount'), api.env.basedn),
automountkey=(self.keyname2,),
description=(self.keyname2,),
automountinformation=(u'ro',),
),
dict(
dn=DN(('description', self.keyname_rename),
('automountmapname', 'testmap'),
('cn', self.locname),
('cn', 'automount'), api.env.basedn),
automountkey=(self.keyname_rename,),
description=(self.keyname_rename,),
automountinformation=(u'rw',),
))],
maps=(
dict(
dn=DN(('description', '/- auto.direct'),
('automountmapname', 'auto.master'),
('cn', self.locname),
('cn', 'automount'), api.env.basedn),
automountkey=(u'/-',),
description=(u'/- auto.direct',),
automountinformation=(u'auto.direct',)
),
))), res)
# Also check the CLI output
self.check_tofiles()
def test_b_automountkey_del(self):
"""
Test the `xmlrpc.automountkey_del` method.
"""
delkey_kw={'automountkey': self.keyname_rename, 'automountinformation' : self.newinfo}
res = api.Command['automountkey_del'](self.locname, self.mapname, **delkey_kw)['result']
assert res
assert not res['failed']
# Verify that it is gone
with pytest.raises(errors.NotFound):
api.Command['automountkey_show'](self.locname, self.mapname, **delkey_kw)
def test_c_automountlocation_del(self):
"""
Test the `xmlrpc.automountlocation_del` method.
"""
res = api.Command['automountlocation_del'](self.locname)['result']
assert res
assert not res['failed']
# Verify that it is gone
with pytest.raises(errors.NotFound):
api.Command['automountlocation_show'](self.locname)
def test_d_automountmap_del(self):
"""
Test that the `xmlrpc.automountlocation_del` method removes all maps and keys
"""
# Verify that the second key we added is gone
key_kw = {'automountkey': self.keyname2, 'automountinformation': self.info, 'raw': True}
with pytest.raises(errors.NotFound):
api.Command['automountkey_show'](self.locname, self.mapname, **key_kw)
@pytest.mark.tier1
class test_automount_direct(AutomountTest):
"""
Test the `automount` plugin indirect map functionality.
"""
mapname = u'auto.direct2'
keyname = u'/-'
direct_kw = { 'key' : keyname }
tofiles_output = textwrap.dedent(u"""
/etc/auto.master:
/-\t/etc/auto.direct
/-\t/etc/auto.direct2
---------------------------
/etc/auto.direct:
---------------------------
/etc/auto.direct2:
maps not connected to /etc/auto.master:
""").strip()
def test_0_automountlocation_add(self):
"""
Test adding a location.
"""
res = api.Command['automountlocation_add'](self.locname, raw=True)['result']
assert res
assert_attr_equal(res, 'cn', self.locname)
def test_1_automountmap_add_direct(self):
"""
Test adding a second direct map with a different info
"""
res = api.Command['automountmap_add_indirect'](self.locname, self.mapname, **self.direct_kw)['result']
assert res
assert_attr_equal(res, 'automountmapname', self.mapname)
def test_2_automountmap_add_duplicate(self):
"""
Test adding a duplicate direct map.
"""
with pytest.raises(errors.DuplicateEntry):
api.Command['automountmap_add_indirect'](
self.locname, self.mapname, **self.direct_kw)
def test_2a_automountmap_tofiles(self):
"""Test the `automountmap_tofiles` command"""
self.check_tofiles()
def test_3_automountlocation_del(self):
"""
Remove the location.
"""
res = api.Command['automountlocation_del'](self.locname)['result']
assert res
assert not res['failed']
# Verity that it is gone
with pytest.raises(errors.NotFound):
api.Command['automountlocation_show'](self.locname)
def test_z_import_roundtrip(self):
"""Check automountlocation_tofiles/automountlocation_import roundtrip
"""
self.check_import_roundtrip()
@pytest.mark.tier1
class test_automount_indirect(AutomountTest):
"""
Test the `automount` plugin indirect map functionality.
"""
mapname = u'auto.home'
keyname = u'/home'
parentmap = u'auto.master'
map_kw = {'key': keyname, 'parentmap': parentmap, 'raw': True}
key_kw = {'automountkey': keyname, 'automountinformation': mapname}
tofiles_output = textwrap.dedent(u"""
/etc/auto.master:
/-\t/etc/auto.direct
/home\t/etc/auto.home
---------------------------
/etc/auto.direct:
---------------------------
/etc/auto.home:
maps not connected to /etc/auto.master:
""").strip()
def test_0_automountlocation_add(self):
"""
Test adding a location.
"""
res = api.Command['automountlocation_add'](self.locname, raw=True)['result']
assert res
assert_attr_equal(res, 'cn', self.locname)
def test_1_automountmap_add_indirect(self):
"""
Test adding an indirect map.
"""
res = api.Command['automountmap_add_indirect'](self.locname, self.mapname, **self.map_kw)['result']
assert res
assert_attr_equal(res, 'automountmapname', self.mapname)
def test_1a_automountmap_add_indirect(self):
"""
Test adding a duplicate indirect map.
"""
with pytest.raises(errors.DuplicateEntry):
api.Command['automountmap_add_indirect'](
self.locname, self.mapname, **self.map_kw
)
def test_2_automountmap_show(self):
"""
Test the `xmlrpc.automountmap_show` method.
"""
res = api.Command['automountmap_show'](self.locname, self.mapname, raw=True)['result']
assert res
assert_attr_equal(res, 'automountmapname', self.mapname)
def test_2a_automountmap_tofiles(self):
"""Test the `automountmap_tofiles` command"""
self.check_tofiles()
def test_3_automountkey_del(self):
"""
Remove the indirect key /home.
"""
res = api.Command['automountkey_del'](self.locname, self.parentmap, **self.key_kw)['result']
assert res
assert not res['failed']
# Verify that it is gone
with pytest.raises(errors.NotFound):
api.Command['automountkey_show'](self.locname, self.parentmap, **self.key_kw)
def test_4_automountmap_del(self):
"""
Remove the indirect map for auto.home.
"""
res = api.Command['automountmap_del'](self.locname, self.mapname)['result']
assert res
assert not res['failed']
# Verify that it is gone
with pytest.raises(errors.NotFound):
api.Command['automountmap_show'](self.locname, self.mapname)
def test_5_automountmap_add_indirect(self):
"""
Add back the indirect map
"""
res = api.Command['automountmap_add_indirect'](
self.locname, self.mapname, **self.map_kw)['result']
assert res
assert_attr_equal(res, 'automountmapname', self.mapname)
def test_6_automountmap_del(self):
"""
Remove the indirect map without removing the key first.
"""
res = api.Command['automountmap_del'](
self.locname, self.mapname)['result']
assert res
assert not res['failed']
# Verify that it is gone
with pytest.raises(errors.NotFound):
api.Command['automountmap_show'](self.locname, self.mapname)
# automountlocation-tofiles should succeed if the map was removed
api.Command['automountlocation_tofiles'](self.locname)
def test_7_automountlocation_del(self):
"""
Remove the location.
"""
res = api.Command['automountlocation_del'](self.locname)['result']
assert res
assert not res['failed']
# Verity that it is gone
with pytest.raises(errors.NotFound):
api.Command['automountlocation_show'](self.locname)
def test_z_import_roundtrip(self):
"""Check automountlocation_tofiles/automountlocation_import roundtrip
"""
self.check_import_roundtrip()
@pytest.mark.tier1
class test_automount_indirect_no_parent(AutomountTest):
"""
Test the `automount` plugin Indirect map function.
"""
mapname = u'auto.home'
keyname = u'/home'
mapname2 = u'auto.direct2'
keyname2 = u'direct2'
parentmap = u'auto.master'
map_kw = {'key': keyname, 'raw': True}
map_kw2 = {'key': keyname2, 'raw': True}
tofiles_output = textwrap.dedent(u"""
/etc/auto.master:
/-\t/etc/auto.direct
/home\t/etc/auto.home
---------------------------
/etc/auto.direct:
---------------------------
/etc/auto.home:
direct2\t-fstype=autofs ldap:auto.direct2
maps not connected to /etc/auto.master:
---------------------------
/etc/auto.direct2:
""").strip()
def test_0_automountlocation_add(self):
"""
Test adding a location.
"""
res = api.Command['automountlocation_add'](self.locname, raw=True)['result']
assert res
assert_attr_equal(res, 'cn', self.locname)
def test_1_automountmap_add_indirect(self):
"""
Test adding an indirect map with default parent.
"""
res = api.Command['automountmap_add_indirect'](self.locname, self.mapname, **self.map_kw)['result']
assert res
assert_attr_equal(res, 'automountmapname', self.mapname)
def test_2_automountkey_show(self):
"""
Test the `xmlrpc.automountkey_show` method with default parent.
"""
showkey_kw = {'automountkey': self.keyname, 'automountinformation': self.mapname, 'raw': True}
res = api.Command['automountkey_show'](self.locname, self.parentmap, **showkey_kw)['result']
assert res
assert_attr_equal(res, 'automountkey', self.keyname)
def test_2a_automountmap_add_indirect(self):
"""
Test adding an indirect map with default parent.
"""
res = api.Command['automountmap_add_indirect'](self.locname,
u'auto.direct2', parentmap=self.mapname, **self.map_kw2)['result']
assert res
assert_attr_equal(res, 'automountmapname', self.mapname2)
def test_2b_automountmap_tofiles(self):
"""Test the `automountmap_tofiles` command"""
self.check_tofiles()
def test_3_automountkey_del(self):
"""
Remove the indirect key /home.
"""
delkey_kw={'automountkey': self.keyname, 'automountinformation': self.mapname}
res = api.Command['automountkey_del'](self.locname, self.parentmap, **delkey_kw)['result']
assert res
assert not res['failed']
# Verify that it is gone
with pytest.raises(errors.NotFound):
api.Command['automountkey_show'](self.locname, self.parentmap, **delkey_kw)
def test_4_automountmap_del(self):
"""
Remove the indirect map for auto.home.
"""
res = api.Command['automountmap_del'](self.locname, self.mapname)['result']
assert res
assert not res['failed']
# Verify that it is gone
with pytest.raises(errors.NotFound):
api.Command['automountmap_show'](self.locname, self.mapname)
def test_5_automountlocation_del(self):
"""
Remove the location.
"""
res = api.Command['automountlocation_del'](self.locname)['result']
assert res
assert not res['failed']
# Verity that it is gone
with pytest.raises(errors.NotFound):
api.Command['automountlocation_show'](self.locname)
| 22,354
|
Python
|
.py
| 539
| 31.847866
| 110
| 0.597064
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,496
|
sudocmd_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/tracker/sudocmd_plugin.py
|
#
# Copyright (C) 2015 FreeIPA Contributors see COPYING for license
#
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_uuid, fuzzy_sudocmddn
from ipatests.test_xmlrpc.tracker.base import Tracker
from ipatests.util import assert_deepequal
class SudoCmdTracker(Tracker):
""" Class for tracking sudo commands """
retrieve_keys = {u'dn', u'sudocmd', u'description',
u'memberof_sudocmdgroup'}
retrieve_all_keys = retrieve_keys | {u'ipauniqueid', u'objectclass'}
create_keys = retrieve_all_keys
update_keys = retrieve_keys - {u'dn'}
find_keys = {u'dn', u'sudocmd', u'description'}
find_all_keys = retrieve_all_keys
def __init__(self, command, description="Test sudo command"):
super(SudoCmdTracker, self).__init__(default_version=None)
self.cmd = command
self.dn = fuzzy_sudocmddn
self.description = description
@property
def name(self):
""" Property holding the name of the entry in LDAP """
return self.cmd
def make_create_command(self):
""" Make function that creates a sudocmd using 'sudocmd-add' """
return self.make_command('sudocmd_add', self.cmd,
description=self.description)
def make_delete_command(self):
""" Make function that deletes a sudocmd using 'sudocmd-del' """
return self.make_command('sudocmd_del', self.cmd)
def make_retrieve_command(self, all=False, raw=False):
""" Make function that retrieves a sudocmd using 'sudocmd-show' """
return self.make_command('sudocmd_show', self.cmd, all=all)
def make_find_command(self, *args, **kwargs):
""" Make function that searches for a sudocmd using 'sudocmd-find' """
return self.make_command('sudocmd_find', *args, **kwargs)
def make_update_command(self, updates):
""" Make function that updates a sudocmd using 'sudocmd-mod' """
return self.make_command('sudocmd_mod', self.cmd, **updates)
def track_create(self):
""" Updates expected state for sudocmd creation"""
self.attrs = dict(
dn=self.dn,
sudocmd=[self.cmd],
description=[self.description],
ipauniqueid=[fuzzy_uuid],
objectclass=objectclasses.sudocmd,
)
self.exists = True
def check_create(self, result):
""" Checks 'sudocmd_add' command result """
assert_deepequal(dict(
value=self.cmd,
summary=u'Added Sudo Command "%s"' % self.cmd,
result=self.filter_attrs(self.create_keys)
), result)
def check_delete(self, result):
""" Checks 'sudocmd_del' command result """
assert_deepequal(dict(
value=[self.cmd],
summary=u'Deleted Sudo Command "%s"' % self.cmd,
result=dict(failed=[]),
), result)
def check_retrieve(self, result, all=False, raw=False):
""" Checks 'sudocmd_show' command result """
if all:
expected = self.filter_attrs(self.retrieve_all_keys)
else:
expected = self.filter_attrs(self.retrieve_keys)
assert_deepequal(dict(
value=self.cmd,
summary=None,
result=expected
), result)
def check_find(self, result, all=False, raw=False):
""" Checks 'sudocmd_find' command result """
if all:
expected = self.filter_attrs(self.find_all_keys)
else:
expected = self.filter_attrs(self.find_keys)
assert_deepequal(dict(
count=1,
truncated=False,
summary=u'1 Sudo Command matched',
result=[expected],
), result)
def check_update(self, result, extra_keys={}):
""" Checks 'sudocmd_mod' command result """
assert_deepequal(dict(
value=self.cmd,
summary=u'Modified Sudo Command "%s"' % self.cmd,
result=self.filter_attrs(self.update_keys | set(extra_keys))
), result)
| 4,111
|
Python
|
.py
| 95
| 33.989474
| 78
| 0.618273
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,497
|
server_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/tracker/server_plugin.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
from __future__ import absolute_import
from ipalib import errors
from ipapython.dn import DN
from ipatests.util import assert_deepequal
from ipatests.test_xmlrpc.tracker.base import Tracker
class ServerTracker(Tracker):
"""Tracker for IPA Location tests"""
retrieve_keys = {
'cn', 'dn', 'ipamaxdomainlevel', 'ipamindomainlevel',
'iparepltopomanagedsuffix_topologysuffix', 'ipalocation_location',
'ipaserviceweight', 'enabled_role_servrole'
}
retrieve_all_keys = retrieve_keys | {'objectclass'}
create_keys = retrieve_keys | {'objectclass'}
find_keys = {
'cn', 'dn', 'ipamaxdomainlevel', 'ipamindomainlevel',
'ipaserviceweight',
}
find_all_keys = retrieve_all_keys
update_keys = {
'cn', 'ipamaxdomainlevel', 'ipamindomainlevel',
'ipalocation_location', 'ipaserviceweight',
}
def __init__(self, name):
super(ServerTracker, self).__init__(default_version=None)
self.server_name = name
self.dn = DN(
('cn', self.server_name),
'cn=masters,cn=ipa,cn=etc',
self.api.env.basedn
)
self.exists = True # we cannot add server manually using server-add
self.attrs = dict(
dn=self.dn,
cn=[self.server_name],
iparepltopomanagedsuffix_topologysuffix=[u'domain', u'ca'],
objectclass=[
u"ipalocationmember",
u"ipaReplTopoManagedServer",
u"top",
u"ipaConfigObject",
u"nsContainer",
u"ipaSupportedDomainLevelConfig"
],
ipamaxdomainlevel=[u"1"],
ipamindomainlevel=[u"1"],
)
self.exists = True
def make_retrieve_command(self, all=False, raw=False):
"""Make function that retrieves this server using server-show"""
return self.make_command(
'server_show', self.name, all=all, raw=raw
)
def make_find_command(self, *args, **kwargs):
"""Make function that finds servers using server-find"""
return self.make_command('server_find', *args, **kwargs)
def make_update_command(self, updates):
"""Make function that modifies the server using server-mod"""
return self.make_command('server_mod', self.name, **updates)
def check_retrieve(self, result, all=False, raw=False):
"""Check `server-show` command result"""
if all:
expected = self.filter_attrs(self.retrieve_all_keys)
else:
expected = self.filter_attrs(self.retrieve_keys)
assert_deepequal(dict(
value=self.server_name,
summary=None,
result=expected,
), result)
def check_find(self, result, all=False, raw=False):
"""Check `server-find` command result"""
if all:
expected = self.filter_attrs(self.find_all_keys)
else:
expected = self.filter_attrs(self.find_keys)
assert_deepequal(dict(
count=1,
truncated=False,
summary=u'1 IPA server matched',
result=[expected],
), result)
def check_find_nomatch(self, result):
""" Check 'server-find' command result when no match is expected """
assert_deepequal(dict(
count=0,
truncated=False,
summary=u'0 IPA servers matched',
result=[],
), result)
def check_update(self, result, extra_keys=(), messages=None):
"""Check `server-update` command result"""
expected = dict(
value=self.server_name,
summary=u'Modified IPA server "{server}"'.format(
server=self.name),
result=self.filter_attrs(self.update_keys | set(extra_keys))
)
if messages:
expected['messages'] = messages
assert_deepequal(expected, result)
def update(self, updates, expected_updates=None, messages=None):
if expected_updates is None:
expected_updates = {}
self.ensure_exists()
command = self.make_update_command(updates)
result = command()
self.attrs.update(updates)
self.attrs.update(expected_updates)
for key, value in list(self.attrs.items()):
if value is None:
del self.attrs[key]
self.check_update(
result,
extra_keys=set(updates.keys()) | set(expected_updates.keys()),
messages=messages)
def make_fixture_clean_location(self, request):
command = self.make_update_command({u'ipalocation_location': None})
try:
command()
except errors.EmptyModlist:
pass
def cleanup():
try:
command()
except errors.EmptyModlist:
pass
request.addfinalizer(cleanup)
return self
| 5,027
|
Python
|
.py
| 132
| 28.287879
| 76
| 0.596351
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,498
|
certmap_plugin.py
|
freeipa_freeipa/ipatests/test_xmlrpc/tracker/certmap_plugin.py
|
#
# Copyright (C) 2017 FreeIPA Contributors see COPYING for license
#
from ipapython.dn import DN
from ipatests.test_xmlrpc.tracker.base import Tracker
from ipatests.test_xmlrpc.tracker.base import ConfigurationTracker, EnableTracker
from ipatests.test_xmlrpc import objectclasses
from ipatests.test_xmlrpc.xmlrpc_test import fuzzy_string
from ipatests.util import assert_deepequal
class CertmapruleTracker(Tracker, EnableTracker):
""" Tracker for testin certmaprule plugin """
retrieve_keys = {
u'dn',
u'cn',
u'description',
u'ipacertmapmaprule',
u'ipacertmapmatchrule',
u'associateddomain',
u'ipacertmappriority',
u'ipaenabledflag'
}
retrieve_all_keys = retrieve_keys | {u'objectclass'}
create_keys = retrieve_keys | {u'objectclass'}
update_keys = retrieve_keys - {u'dn'}
def __init__(self, cn, description, ipacertmapmaprule,
ipacertmapmatchrule, associateddomain, ipacertmappriority,
default_version=None):
super(CertmapruleTracker, self).__init__(
default_version=default_version)
self.dn = DN((u'cn', cn,),
self.api.env.container_certmaprules,
self.api.env.basedn)
self.options = {
u'description': description,
u'ipacertmapmaprule': ipacertmapmaprule,
u'ipacertmapmatchrule': ipacertmapmatchrule,
u'associateddomain': associateddomain,
u'ipacertmappriority': ipacertmappriority,
}
def make_create_command(self, dont_fill=()):
kwargs = {k: v for k, v in self.options.items() if k not in dont_fill}
return self.make_command('certmaprule_add', self.name, **kwargs)
def track_create(self, dont_fill=()):
self.attrs = {
'dn': self.dn,
'cn': [self.name],
'ipaenabledflag': [True],
'objectclass': objectclasses.certmaprule,
}
self.attrs.update({
k: [v] for k, v in self.options.items() if k not in dont_fill
})
self.exists = True
def check_create(self, result):
assert_deepequal(dict(
value=self.name,
summary=u'Added Certificate Identity Mapping Rule "{}"'
u''.format(self.name),
result=self.filter_attrs(self.create_keys),
), result)
def create(self, dont_fill=()):
self.track_create(dont_fill)
command = self.make_create_command(dont_fill)
result = command()
self.check_create(result)
def make_delete_command(self):
return self.make_command('certmaprule_del', self.name)
def check_delete(self, result):
assert_deepequal(
dict(
value=[self.name],
summary=u'Deleted Certificate Identity Mapping Rule "{}"'
''.format(self.name),
result=dict(failed=[]),
),
result
)
def make_retrieve_command(self, all=False, raw=False):
return self.make_command('certmaprule_show', self.name, all=all,
raw=raw)
def check_retrieve(self, result, all=False, raw=False):
if all:
expected = self.filter_attrs(self.retrieve_all_keys)
else:
expected = self.filter_attrs(self.retrieve_keys)
assert_deepequal(
dict(
value=self.name,
summary=None,
result=expected,
),
result
)
def make_find_command(self, *args, **kwargs):
return self.make_command('certmaprule_find', *args, **kwargs)
def check_find(self, result, all=False, raw=False):
if all:
expected = self.filter_attrs(self.retrieve_all_keys)
else:
expected = self.filter_attrs(self.retrieve_keys)
assert_deepequal(
dict(
count=1,
truncated=False,
summary=u'1 Certificate Identity Mapping Rule matched',
result=[expected],
),
result
)
def make_update_command(self, updates):
return self.make_command('certmaprule_mod', self.name, **updates)
def check_update(self, result, extra_keys=()):
assert_deepequal(
dict(
value=self.name,
summary=u'Modified Certificate Identity Mapping Rule "{}"'
u''.format(self.name),
result=self.filter_attrs(self.update_keys | set(extra_keys)),
),
result
)
def make_enable_command(self):
return self.make_command('certmaprule_enable', self.name)
def check_enable(self, result):
assert_deepequal(
dict(
value=self.name,
summary=u'Enabled Certificate Identity Mapping Rule "{}"'
u''.format(self.name),
result=True,
),
result
)
def make_disable_command(self):
return self.make_command('certmaprule_disable', self.name)
def check_disable(self, result):
assert_deepequal(
dict(
value=self.name,
summary=u'Disabled Certificate Identity Mapping Rule "{}"'
u''.format(self.name),
result=True,
),
result
)
class CertmapconfigTracker(ConfigurationTracker):
retrieve_keys = {
u'dn',
u'ipacertmappromptusername',
}
retrieve_all_keys = retrieve_keys | {
u'cn',
u'objectclass',
u'aci',
}
update_keys = retrieve_keys - {u'dn'}
singlevalue_keys = {u'ipacertmappromptusername'}
def __init__(self, default_version=None):
super(CertmapconfigTracker, self).__init__(
default_version=default_version)
self.attrs = {
u'dn': DN(self.api.env.container_certmap, self.api.env.basedn),
u'cn': [self.api.env.container_certmap[0].value],
u'objectclass': objectclasses.certmapconfig,
u'aci': [fuzzy_string],
u'ipacertmappromptusername': self.api.Command.certmapconfig_show(
)[u'result'][u'ipacertmappromptusername']
}
def make_update_command(self, updates):
return self.make_command('certmapconfig_mod', **updates)
def check_update(self, result, extra_keys=()):
assert_deepequal(
dict(
value=None,
summary=None,
result=self.filter_attrs(self.update_keys | set(extra_keys)),
),
result
)
def make_retrieve_command(self, all=False, raw=False):
return self.make_command('certmapconfig_show', all=all, raw=raw)
def check_retrieve(self, result, all=False, raw=False):
if all:
expected = self.filter_attrs(self.retrieve_all_keys)
else:
expected = self.filter_attrs(self.retrieve_keys)
assert_deepequal(
dict(
value=None,
summary=None,
result=expected,
),
result
)
| 7,295
|
Python
|
.py
| 194
| 26.747423
| 81
| 0.576096
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|
16,499
|
kerberos_aliases.py
|
freeipa_freeipa/ipatests/test_xmlrpc/tracker/kerberos_aliases.py
|
#
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
"""kerberos_aliases
The module implements a mixin class that provides an interface
to the Kerberos Aliases feature of freeIPA.
In order to use the class the child class must implement the
`_make_add_alias_cmd` and `_make_remove_alias_cmd` methods that
are different for each entity type.
The KerberosAliasMixin class then provides the implementation
of the manipulation of the kerberos alias in general.
It is up to the child class or the user to validate the
alias being added for a particular type of an entry.
"""
class KerberosAliasError(Exception):
pass
class KerberosAliasMixin:
"""KerberosAliasMixin"""
def _make_add_alias_cmd(self):
raise NotImplementedError("The _make_add_alias_cmd method "
"is not implemented.")
def _make_remove_alias_cmd(self):
raise NotImplementedError("The _make_remove_alias_cmd method "
"is not implemented.")
def _check_for_krbprincipalname_attr(self):
# Check if the tracker has a principal name
# Each compatible entry has at least one kerberos
# principal matching the canonical principal name
principals = self.attrs.get('krbprincipalname')
if self.exists:
if not principals:
raise KerberosAliasError(
"{} doesn't have krbprincipalname attribute"
.format(self.__class__.__name__))
else:
raise ValueError("The entry {} doesn't seem to exist"
.format(self.name))
def _normalize_principal_list(self, principal_list):
"""Normalize the list for further manipulation."""
if not isinstance(principal_list, (list, tuple)):
return [principal_list]
else:
return principal_list
def _normalize_principal_value(self, principal):
"""Normalize principal value by appending the realm string."""
return u'@'.join((principal, self.api.env.realm))
def add_principal(self, principal_list, **options):
"""Add kerberos principal alias to the entity.
Add principal alias to the underlying entry and
update the attributes in the Tracker instance.
"""
self._check_for_krbprincipalname_attr()
principal_list = self._normalize_principal_list(principal_list)
cmd = self._make_add_alias_cmd()
cmd(principal_list, **options)
tracker_principals = self.attrs.get('krbprincipalname')
tracker_principals.extend((
self._normalize_principal_value(item) for item in principal_list))
def remove_principal(self, principal_list, **options):
"""Remove kerberos principal alias from an entry.
Remove principal alias from the tracked entry.
"""
self._check_for_krbprincipalname_attr()
principal_list = self._normalize_principal_list(principal_list)
cmd = self._make_remove_alias_cmd()
cmd(principal_list, **options)
# Make a copy of the list so the tracker instance is not modified
# if there is an error deleting the aliases
# This can happen when deleting multiple aliases and at least
# one of them doesn't exist, raising ValueError
tracker_principals = self.attrs.get('krbprincipalname')[:]
for item in principal_list:
tracker_principals.remove(self._normalize_principal_value(item))
self.attrs['krbprincipalname'] = tracker_principals
| 3,589
|
Python
|
.py
| 74
| 39.635135
| 78
| 0.671633
|
freeipa/freeipa
| 975
| 339
| 31
|
GPL-3.0
|
9/5/2024, 5:12:14 PM (Europe/Amsterdam)
|