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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
25,300 | test_iscsi.py | truenas_middleware/tests/api2/test_iscsi.py | import pytest
from middlewared.service_exception import ValidationErrors
from middlewared.test.integration.assets.iscsi import iscsi_extent
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.utils import call
def test__iscsi_extent__disk_choices(request):
with dataset("test zvol", {"type": "VOLUME", "volsize": 1048576}) as ds:
# Make snapshots available for devices
call("zfs.dataset.update", ds, {"properties": {"snapdev": {"parsed": "visible"}}})
call("zfs.snapshot.create", {"dataset": ds, "name": "snap-1"})
assert call("iscsi.extent.disk_choices") == {
f'zvol/{ds.replace(" ", "+")}': f'{ds} (1 MiB)',
f'zvol/{ds.replace(" ", "+")}@snap-1': f'{ds}@snap-1 [ro]',
}
# Create new extent
with iscsi_extent({
"name": "test_extent",
"type": "DISK",
"disk": f"zvol/{ds.replace(' ', '+')}",
}):
# Verify that zvol is not available in iscsi disk choices
assert call("iscsi.extent.disk_choices") == {
f'zvol/{ds.replace(" ", "+")}@snap-1': f'{ds}@snap-1 [ro]',
}
# Verify that zvol is not availabe in VM disk choices
# (and snapshot zvol is not available too as it is read-only)
assert call("vm.device.disk_choices") == {}
def test__iscsi_extent__create_with_invalid_disk_with_whitespace(request):
with dataset("test zvol", {
"type": "VOLUME",
"volsize": 1048576,
}) as ds:
with pytest.raises(ValidationErrors) as e:
with iscsi_extent({
"name": "test_extent",
"type": "DISK",
"disk": f"zvol/{ds}",
}):
pass
assert str(e.value) == (
f"[EINVAL] iscsi_extent_create.disk: Device '/dev/zvol/{ds}' for volume '{ds}' does not exist\n"
)
def test__iscsi_extent__locked(request):
with dataset("test zvol", {
"type": "VOLUME",
"volsize": 1048576,
"inherit_encryption": False,
"encryption": True,
"encryption_options": {"passphrase": "testtest"},
}) as ds:
with iscsi_extent({
"name": "test_extent",
"type": "DISK",
"disk": f"zvol/{ds.replace(' ', '+')}",
}) as extent:
assert not extent["locked"]
call("pool.dataset.lock", ds, job=True)
extent = call("iscsi.extent.get_instance", extent["id"])
assert extent["locked"]
| 2,573 | Python | .py | 59 | 33.745763 | 108 | 0.55853 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,301 | test_003_network_global.py | truenas_middleware/tests/api2/test_003_network_global.py | import sys
import os
apifolder = os.getcwd()
sys.path.append(apifolder)
import pytest
from pytest_dependency import depends
from auto_config import ha, interface, hostname, domain, gateway
from middlewared.test.integration.utils.client import client, truenas_server
@pytest.fixture(scope='module')
def ws_client():
with client(host_ip=truenas_server.ip) as c:
yield c
@pytest.fixture(scope='module')
def netinfo(ws_client):
domain_to_use = domain
hosts = ['192.168.1.150 fakedomain.doesnt.exist', '172.16.50.100 another.fakeone']
if ha and (domain_to_use := os.environ.get('domain', None)) is not None:
info = {
'domain': domain_to_use,
'ipv4gateway': gateway,
'hostname': os.environ['hostname'],
'hostname_b': os.environ['hostname_b'],
'hostname_virtual': os.environ['hostname_virtual'],
'nameserver1': os.environ['primary_dns'],
'nameserver2': os.environ.get('secondary_dns', ''),
'hosts': hosts,
}
else:
# NOTE: on a non-HA system, this method is assuming
# that the machine has been handed a default route
# and nameserver(s) from a DHCP server. That's why
# we're getting this information.
ans = ws_client.call('network.general.summary')
assert isinstance(ans, dict)
assert isinstance(ans['default_routes'], list) and ans['default_routes']
assert isinstance(ans['nameservers'], list) and ans['nameservers']
info = {'domain': domain_to_use, 'hostname': hostname, 'ipv4gateway': ans['default_routes'][0], 'hosts': hosts}
for idx, nameserver in enumerate(ans['nameservers'], start=1):
if idx > 3:
# only 3 nameservers allowed via the API
break
info[f'nameserver{idx}'] = nameserver
return info
@pytest.mark.dependency(name='NET_CONFIG')
def test_001_set_and_verify_network_global_settings_database(ws_client, netinfo):
config = ws_client.call('network.configuration.update', netinfo)
assert all(config[k] == netinfo[k] for k in netinfo)
def test_002_verify_network_global_settings_state(request, ws_client, netinfo):
depends(request, ['NET_CONFIG'])
state = ws_client.call('network.configuration.config')['state']
assert set(state['hosts']) == set(netinfo['hosts'])
assert state['ipv4gateway'] == netinfo['ipv4gateway']
for key in filter(lambda x: x.startswith('nameserver'), netinfo):
assert state[key] == netinfo[key]
"""
HA isn't fully operational by the time this test runs so testing
the functionality on the remote node is guaranteed to fail. We
should probably rearrange order of tests and fix this at some point.
if ha:
state = ws_client.call('failover.call_remote', 'network.configuration.config')['state']
assert set(state['hosts']) == set(netinfo['hosts'])
assert state['ipv4gateway'] == netinfo['ipv4gateway']
for key in filter(lambda x: x.startswith('nameserver'), netinfo):
assert state[key] == netinfo[key]
"""
@pytest.mark.dependency(name='GENERAL')
def test_003_verify_network_general_summary(request, ws_client, netinfo):
depends(request, ['NET_CONFIG'])
summary = ws_client.call('network.general.summary')
assert any(i.startswith(truenas_server.ip) for i in summary['ips'][interface]['IPV4'])
| 3,424 | Python | .py | 70 | 42.057143 | 119 | 0.671257 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,302 | test_virt_002_instance.py | truenas_middleware/tests/api2/test_virt_002_instance.py | from threading import Event
from middlewared.test.integration.assets.filesystem import mkfile
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.utils.client import client
from middlewared.test.integration.utils.call import call
from middlewared.test.integration.utils.ssh import ssh
from auto_config import pool_name
def clean():
call('virt.global.update', {'pool': None}, job=True)
ssh(f'zfs destroy -r {pool_name}/.ix-virt || true')
call('virt.global.update', {'pool': 'tank'}, job=True)
def test_virt_instance_create():
clean()
wait_agent = Event()
def wait_debian(*args, **kwargs):
wait_agent.set()
with client() as c:
c.subscribe('virt.instance.agent_running', wait_debian, sync=True)
# Create first so there is time for the agent to start
call('virt.instance.create', {'name': 'debian', 'image': 'debian/trixie', 'instance_type': 'VM'}, job=True)
call('virt.instance.create', {'name': 'void', 'image': 'voidlinux/musl'}, job=True)
ssh('incus exec void cat /etc/os-release | grep "Void Linux"')
call('virt.instance.create', {
'name': 'arch',
'image': 'archlinux/current/default',
'devices': [
{'name': 'tpm', 'dev_type': 'TPM', 'path': '/dev/tpm0', 'pathrm': '/dev/tmprm0'},
],
}, job=True)
ssh('incus exec arch cat /etc/os-release | grep "Arch Linux"')
devices = call('virt.instance.device_list', 'arch')
assert any(i for i in devices if i['name'] == 'tpm'), devices
assert wait_agent.wait(timeout=60)
ssh('incus exec debian cat /etc/os-release | grep "Debian"')
def test_virt_instance_update():
call('virt.instance.update', 'void', {'cpu': '1', 'memory': 500 * 1024 * 1024, 'environment': {'FOO': 'BAR'}}, job=True)
ssh('incus exec void grep MemTotal: /proc/meminfo|grep 512000')
# Checking CPUs seems to cause a racing condition (perhaps CPU currently in use in the container?)
# rv = ssh('incus exec void cat /proc/cpuinfo |grep processor|wc -l')
# assert rv.strip() == '1'
rv = ssh('incus exec void env | grep ^FOO=')
assert rv.strip() == 'FOO=BAR'
def test_virt_instance_stop():
# Stop only one of them so the others are stopped during delete
assert ssh('incus list void -f json| jq ".[].status"').strip() == '"Running"'
instance = call('virt.instance.query', [['id', '=', 'void']], {'get': True})
assert instance['status'] == 'RUNNING'
call('virt.instance.stop', 'void', {'force': True}, job=True)
instance = call('virt.instance.query', [['id', '=', 'void']], {'get': True})
assert instance['status'] == 'STOPPED'
assert ssh('incus list void -f json| jq ".[].status"').strip() == '"Stopped"'
def test_virt_instance_device_add():
assert ssh('incus list debian -f json| jq ".[].status"').strip() == '"Running"'
call('virt.instance.stop', 'debian', {'force': True}, job=True)
call('virt.instance.device_add', 'debian', {
'name': 'tpm',
'dev_type': 'TPM',
})
call('virt.instance.device_add', 'arch', {
'name': 'proxy',
'dev_type': 'PROXY',
'source_proto': 'TCP',
'source_port': 8005,
'dest_proto': 'TCP',
'dest_port': 80,
})
# TODO: adding to a VM causes start to hang at the moment (zombie process)
# call('virt.instance.device_add', 'debian', {
# 'name': 'disk1',
# 'dev_type': 'DISK',
# 'source': f'/mnt/{pool_name}',
# 'destination': '/host',
# })
devices = call('virt.instance.device_list', 'debian')
assert any(i for i in devices if i['name'] == 'tpm'), devices
devices = call('virt.instance.device_list', 'arch')
assert any(i for i in devices if i['name'] == 'proxy'), devices
# assert 'disk1' in devices, devices
wait_agent = Event()
def wait_debian(*args, **kwargs):
wait_agent.set()
with client() as c:
c.subscribe('virt.instance.agent_running', wait_debian, sync=True)
call('virt.instance.start', 'debian', job=True)
assert wait_agent.wait(timeout=30)
ssh('incus exec debian ls /dev/tpm0')
# ssh('incus exec debian ls /host')
with dataset('virtshare') as ds:
call('virt.instance.device_add', 'arch', {
'name': 'disk1',
'dev_type': 'DISK',
'source': f'/mnt/{ds}',
'destination': '/host',
})
devices = call('virt.instance.device_list', 'arch')
assert any(i for i in devices if i['name'] == 'disk1'), devices
with mkfile(f'/mnt/{ds}/testfile'):
ssh('incus exec arch ls /host/testfile')
call('virt.instance.device_delete', 'arch', 'disk1')
def test_virt_instance_proxy():
ssh('incus exec arch -- pacman -S --noconfirm openbsd-netcat')
ssh('incus exec -T arch -- bash -c "nohup nc -l 0.0.0.0 80 > /tmp/nc 2>&1 &"')
ssh('echo "foo" | nc -w 1 localhost 8005 || true')
rv = ssh('incus exec arch -- cat /tmp/nc')
assert rv.strip() == 'foo'
def test_virt_instance_device_delete():
call('virt.instance.stop', 'debian', {'force': True}, job=True)
call('virt.instance.device_delete', 'debian', 'tpm')
devices = call('virt.instance.device_list', 'debian')
assert not any(i for i in devices if i['name'] == 'tpm'), devices
def test_virt_instance_delete():
call('virt.instance.delete', 'void', job=True)
ssh('incus config show void 2>&1 | grep "not found"')
call('virt.instance.delete', 'arch', job=True)
ssh('incus config show arch 2>&1 | grep "not found"')
call('virt.instance.delete', 'debian', job=True)
ssh('incus config show debian 2>&1 | grep "not found"')
assert len(call('virt.instance.query')) == 0
| 5,832 | Python | .py | 118 | 42.838983 | 124 | 0.615859 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,303 | test_pool_replace_disk_settings_description.py | truenas_middleware/tests/api2/test_pool_replace_disk_settings_description.py | import pytest
from middlewared.test.integration.assets.pool import _2_disk_mirror_topology, another_pool
from middlewared.test.integration.utils import call
@pytest.fixture(scope="module")
def pool():
with another_pool(topology=_2_disk_mirror_topology) as pool:
yield pool
@pytest.mark.parametrize("preserve_description", [True, False])
def test_pool_replace_disk(pool, preserve_description):
pool = call("pool.get_instance", pool["id"])
flat_top = call("pool.flatten_topology", pool["topology"])
pool_top = [vdev for vdev in flat_top if vdev["type"] == "DISK"]
to_replace_vdev = pool_top[0]
to_replace_disk = call("disk.query", [["name", "=", to_replace_vdev["disk"]]], {"get": True})
new_disk = call("disk.get_unused")[0]
call("disk.update", to_replace_disk["identifier"], {"description": "Preserved disk description"})
call("disk.update", new_disk["identifier"], {"description": "Unchanged disk description"})
call("pool.replace", pool["id"], {
"label": to_replace_vdev["guid"],
"disk": new_disk["identifier"],
"force": True,
"preserve_description": preserve_description,
}, job=True)
new_disk = call("disk.get_instance", new_disk["identifier"])
if preserve_description:
assert new_disk["description"] == "Preserved disk description"
else:
assert new_disk["description"] == "Unchanged disk description"
| 1,427 | Python | .py | 28 | 45.642857 | 101 | 0.681295 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,304 | test_cloud_sync_credentials.py | truenas_middleware/tests/api2/test_cloud_sync_credentials.py | from middlewared.test.integration.assets.cloud_sync import local_ftp_credential_data
from middlewared.test.integration.utils import call
def test_verify_cloud_credential():
with local_ftp_credential_data() as data:
assert call("cloudsync.credentials.verify", data)["valid"]
def test_verify_cloud_credential_fail():
with local_ftp_credential_data() as data:
data["attributes"]["user"] = "root"
assert not call("cloudsync.credentials.verify", data)["valid"]
| 492 | Python | .py | 9 | 49.666667 | 84 | 0.745303 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,305 | test_account_privilege_role.py | truenas_middleware/tests/api2/test_account_privilege_role.py | import errno
import logging
from time import sleep
import pytest
from middlewared.service_exception import CallError
from middlewared.test.integration.assets.account import unprivileged_user_client
from middlewared.test.integration.assets.pool import dataset, snapshot
from middlewared.test.integration.utils import client
logger = logging.getLogger(__name__)
@pytest.mark.parametrize("role", ["SNAPSHOT_READ", "SNAPSHOT_WRITE"])
def test_can_read_with_read_or_write_role(role):
with dataset("test_snapshot_read") as ds:
with snapshot(ds, "test"):
with unprivileged_user_client([role]) as c:
assert len(c.call("zfs.snapshot.query", [["dataset", "=", ds]])) == 1
def test_can_not_write_with_read_role():
with dataset("test_snapshot_write1") as ds:
with unprivileged_user_client(["SNAPSHOT_READ"]) as c:
with pytest.raises(CallError) as ve:
c.call("zfs.snapshot.create", {
"dataset": ds,
"name": "test",
})
assert ve.value.errno == errno.EACCES
def test_write_with_write_role():
with dataset("test_snapshot_write2") as ds:
with unprivileged_user_client(["SNAPSHOT_WRITE"]) as c:
c.call("zfs.snapshot.create", {
"dataset": ds,
"name": "test",
})
def test_can_delete_with_write_role_with_separate_delete():
with dataset("test_snapshot_delete1") as ds:
with snapshot(ds, "test") as id:
with unprivileged_user_client(["SNAPSHOT_DELETE"]) as c:
c.call("zfs.snapshot.delete", id)
def test_can_not_delete_with_write_role_with_separate_delete():
with dataset("test_snapshot_delete2") as ds:
with snapshot(ds, "test") as id:
with unprivileged_user_client(["SNAPSHOT_WRITE"]) as c:
with pytest.raises(CallError) as ve:
c.call("zfs.snapshot.delete", id)
assert ve.value.errno == errno.EACCES
def test_works_for_redefined_crud_method():
with unprivileged_user_client(["SHARING_ADMIN"]) as c:
c.call("service.update", "cifs", {"enable": False})
def test_full_admin_role():
with unprivileged_user_client(["FULL_ADMIN"]) as c:
c.call("system.general.config")
# User with FULL_ADMIN role should have something in jobs list
assert len(c.call("core.get_jobs")) != 0
# attempt to wait / cancel job should not fail
jid = c.call("core.job_test", {"sleep": 1})
c.call("core.job_wait", jid, job=True)
c.call("core.job_abort", jid)
@pytest.mark.parametrize("role,method,params", [
("DATASET_READ", "pool.dataset.checksum_choices", []),
])
def test_read_role_can_call_method(role, method, params):
with unprivileged_user_client([role]) as c:
c.call(method, *params)
@pytest.mark.parametrize("method,params", [
("system.general.config", []),
("user.get_instance", [1]),
("user.query", []),
("user.shell_choices", []),
("auth.me", []),
("filesystem.listdir", ["/"]),
("filesystem.stat", ["/"]),
("filesystem.getacl", ["/"]),
("filesystem.acltemplate.by_path", [{"path": "/"}]),
("pool.dataset.details", []),
("core.get_jobs", []),
])
def test_readonly_can_call_method(method, params):
with unprivileged_user_client(["READONLY_ADMIN"]) as c:
c.call(method, *params)
def test_readonly_can_not_call_method():
with unprivileged_user_client(["READONLY_ADMIN"]) as c:
with pytest.raises(CallError) as ve:
c.call("user.create")
assert ve.value.errno == errno.EACCES
with pytest.raises(CallError) as ve:
# fails with EPERM if API access granted
c.call("filesystem.mkdir", "/foo")
assert ve.value.errno == errno.EACCES
def test_limited_user_can_set_own_attributes():
with unprivileged_user_client(["READONLY_ADMIN"]) as c:
c.call("auth.set_attribute", "foo", "bar")
attrs = c.call("auth.me")["attributes"]
assert "foo" in attrs
assert attrs["foo"] == "bar"
def test_limited_user_auth_token_behavior():
with unprivileged_user_client(["READONLY_ADMIN"]) as c:
auth_token = c.call("auth.generate_token")
with client(auth=None) as c2:
assert c2.call("auth.login_with_token", auth_token)
c2.call("auth.me")
c2.call("core.get_jobs")
def test_sharing_manager_jobs():
with unprivileged_user_client(["SHARING_ADMIN"]) as c:
auth_token = c.call("auth.generate_token")
jid = c.call("core.job_test", {"sleep": 1})
with client(auth=None) as c2:
#c.call("core.job_wait", jid, job=True)
assert c2.call("auth.login_with_token", auth_token)
wait_job_id = c2.call("core.job_wait", jid)
sleep(2)
result = c2.call("core.get_jobs", [["id", "=", wait_job_id]], {"get": True})
assert result["state"] == "SUCCESS"
c2.call("core.job_abort", wait_job_id)
def test_foreign_job_access():
with unprivileged_user_client(["READONLY_ADMIN"]) as unprivileged:
with client() as c:
job = c.call("core.job_test")
wait_job_id = unprivileged.call("core.job_wait", job)
sleep(2)
result = unprivileged.call("core.get_jobs", [["id", "=", wait_job_id]], {"get": True})
assert result["state"] != "SUCCESS"
jobs = unprivileged.call("core.get_jobs", [["id", "=", job]])
assert jobs == []
with unprivileged_user_client(["FULL_ADMIN"]) as unprivileged:
with client() as c:
job = c.call("core.job_test")
wait_job_id = unprivileged.call("core.job_wait", job)
sleep(2)
result = unprivileged.call("core.get_jobs", [["id", "=", wait_job_id]], {"get": True})
assert result["state"] == "SUCCESS"
def test_can_not_subscribe_to_event():
with unprivileged_user_client() as unprivileged:
with pytest.raises(CallError) as ve:
unprivileged.subscribe("alert.list", lambda *args, **kwargs: None)
assert ve.value.errno == errno.EACCES
def test_can_subscribe_to_event():
with unprivileged_user_client(["READONLY_ADMIN"]) as unprivileged:
unprivileged.subscribe("alert.list", lambda *args, **kwargs: None)
| 6,418 | Python | .py | 136 | 38.727941 | 98 | 0.616113 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,306 | test_smb_null_empty_dacl.py | truenas_middleware/tests/api2/test_smb_null_empty_dacl.py | import json
import os
import pytest
from middlewared.test.integration.assets.smb import smb_share
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.utils import call, ssh
from middlewared.test.integration.utils.smb import security, smb_connection
from samba import ntstatus, NTSTATUSError
ADV_PERMS_FIELDS = [
'READ_DATA', 'WRITE_DATA', 'APPEND_DATA',
'READ_NAMED_ATTRS', 'WRITE_NAMED_ATTRS',
'EXECUTE',
'DELETE_CHILD', 'DELETE',
'READ_ATTRIBUTES', 'WRITE_ATTRIBUTES',
'READ_ACL', 'WRITE_ACL',
'WRITE_OWNER',
'SYNCHRONIZE'
]
NULL_DACL_PERMS = {'BASIC': 'FULL_CONTROL'}
EMPTY_DACL_PERMS = {perm: False for perm in ADV_PERMS_FIELDS}
@pytest.fixture(scope='function')
def share():
with dataset('null_dacl_test', {'share_type': 'SMB'}) as ds:
with smb_share(f'/mnt/{ds}', 'DACL_TEST_SHARE') as s:
yield {'ds': ds, 'share': s}
def set_special_acl(path, special_acl_type):
match special_acl_type:
case 'NULL_DACL':
permset = NULL_DACL_PERMS
case 'EMPTY_DACL':
permset = EMPTY_DACL_PERMS
case _:
raise TypeError(f'[EDOOFUS]: {special_acl_type} unexpected special ACL type')
payload = json.dumps({'acl': [{
'tag': 'everyone@',
'id': -1,
'type': 'ALLOW',
'perms': permset,
'flags': {'BASIC': 'NOINHERIT'},
}]})
ssh(f'touch {path}')
# Use SSH to write to avoid middleware ACL normalization and validation
# that prevents writing these specific ACLs.
ssh(f"nfs4xdr_setfacl -j '{payload}' {path}")
def test_null_dacl_set(unprivileged_user_fixture, share):
""" verify that setting NULL DACL results in expected ZFS ACL """
with smb_connection(
share=share['share']['name'],
username=unprivileged_user_fixture.username,
password=unprivileged_user_fixture.password,
) as c:
fh = c.create_file('test_null_dacl', 'w')
current_sd = c.get_sd(fh, security.SECINFO_OWNER | security.SECINFO_GROUP)
current_sd.dacl = None
c.set_sd(fh, current_sd, security.SECINFO_OWNER | security.SECINFO_GROUP | security.SECINFO_DACL)
new_sd = c.get_sd(fh, security.SECINFO_OWNER | security.SECINFO_GROUP | security.SECINFO_DACL)
assert new_sd.dacl is None
theacl = call('filesystem.getacl', os.path.join(share['share']['path'], 'test_null_dacl'))
assert len(theacl['acl']) == 1
assert theacl['acl'][0]['perms'] == NULL_DACL_PERMS
assert theacl['acl'][0]['type'] == 'ALLOW'
assert theacl['acl'][0]['tag'] == 'everyone@'
def test_null_dacl_functional(unprivileged_user_fixture, share):
""" verify that NULL DACL grants write privileges """
testfile = os.path.join(share['share']['path'], 'test_null_dacl_write')
set_special_acl(testfile, 'NULL_DACL')
data = b'canary'
with smb_connection(
share=share['share']['name'],
username=unprivileged_user_fixture.username,
password=unprivileged_user_fixture.password,
) as c:
fh = c.create_file('test_null_dacl_write', 'w')
current_sd = c.get_sd(fh, security.SECINFO_OWNER | security.SECINFO_GROUP)
assert current_sd.dacl is None
c.write(fh, data)
assert c.read(fh, 0, cnt=len(data)) == data
def test_empty_dacl_set(unprivileged_user_fixture, share):
""" verify that setting empty DACL results in expected ZFS ACL """
with smb_connection(
share=share['share']['name'],
username=unprivileged_user_fixture.username,
password=unprivileged_user_fixture.password,
) as c:
fh = c.create_file('test_empty_dacl', 'w')
current_sd = c.get_sd(fh, security.SECINFO_OWNER | security.SECINFO_GROUP)
current_sd.dacl = security.acl()
c.set_sd(fh, current_sd, security.SECINFO_OWNER | security.SECINFO_GROUP | security.SECINFO_DACL)
new_sd = c.get_sd(fh, security.SECINFO_OWNER | security.SECINFO_GROUP | security.SECINFO_DACL)
assert new_sd.dacl.num_aces == 0
theacl = call('filesystem.getacl', os.path.join(share['share']['path'], 'test_empty_dacl'))
assert len(theacl['acl']) == 1
assert theacl['acl'][0]['perms'] == EMPTY_DACL_PERMS
assert theacl['acl'][0]['type'] == 'ALLOW'
assert theacl['acl'][0]['tag'] == 'everyone@'
def test_empty_dacl_functional(unprivileged_user_fixture, share):
testfile = os.path.join(share['share']['path'], 'test_empty_dacl_write')
set_special_acl(testfile, 'EMPTY_DACL')
with smb_connection(
share=share['share']['name'],
username=unprivileged_user_fixture.username,
password=unprivileged_user_fixture.password,
) as c:
# File has empty ACL and is not owned by this user
with pytest.raises(NTSTATUSError) as nt_err:
c.create_file('test_empty_dacl_write', 'w')
assert nt_err.value.args[0] == ntstatus.NT_STATUS_ACCESS_DENIED
| 5,012 | Python | .py | 107 | 40.009346 | 105 | 0.655731 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,307 | test_530_ups.py | truenas_middleware/tests/api2/test_530_ups.py | import os
from tempfile import NamedTemporaryFile
from time import sleep
import pytest
from assets.websocket.service import ensure_service_enabled, ensure_service_started
from auto_config import password, user
from functions import send_file
from middlewared.test.integration.utils import call, mock, ssh
from middlewared.test.integration.utils.client import truenas_server
DUMMY_FAKEDATA_DEV = '/tmp/fakedata.dev'
SHUTDOWN_MARKER_FILE = '/tmp/is_shutdown'
first_ups_payload = {
'rmonitor': True,
'mode': 'MASTER',
'shutdown': 'BATT',
'port': '655',
'remotehost': '127.0.0.1',
'identifier': 'ups',
'driver': 'usbhid-ups$PROTECT NAS',
'monpwd': 'mypassword'
}
second_ups_payload = {
'rmonitor': False,
'mode': 'SLAVE',
'shutdown': 'LOWBATT',
'port': '65535',
'identifier': 'foo',
'monpwd': 'secondpassword'
}
default_dummy_data = {
'battery.charge': 100,
'driver.parameter.pollinterval': 2,
'input.frequency': 49.9,
'input.frequency.nominal': 50.0,
'input.voltage': 230,
'input.voltage.nominal': 240,
'ups.status': 'OL',
'ups.timer.shutdown': -1,
'ups.timer.start': -1,
}
def get_service_state():
return call('service.query', [['service', '=', 'ups']], {'get': True})
def remove_file(filepath):
ssh(f'rm {filepath}', check=False)
def did_shutdown():
return ssh(f'cat {SHUTDOWN_MARKER_FILE}', check=False) == "done\n"
def write_fake_data(data=None):
data = data or {}
all_data = default_dummy_data | data
with NamedTemporaryFile() as f:
for k, v in all_data.items():
f.write(f'{k}: {v}\n'.encode('utf-8'))
f.flush()
os.fchmod(f.fileno(), 0o644)
results = send_file(f.name, DUMMY_FAKEDATA_DEV, user, password, truenas_server.ip)
assert results['result'], str(results['output'])
def wait_for_alert(klass, retries=10):
assert retries > 0
while retries:
alerts = call('alert.list')
for alert in alerts:
if alert['klass'] == klass:
return alert
sleep(1)
retries -= 1
@pytest.fixture(scope='module')
def ups_running():
with ensure_service_enabled('ups'):
with ensure_service_started('ups'):
yield
@pytest.fixture(scope='module')
def dummy_ups_driver_configured():
write_fake_data()
remove_file(SHUTDOWN_MARKER_FILE)
old_config = call('ups.config')
del old_config['complete_identifier']
del old_config['id']
payload = {
'mode': 'MASTER',
'driver': 'dummy-ups',
'port': DUMMY_FAKEDATA_DEV,
'description': 'dummy-ups in dummy-once mode',
'shutdowncmd': f'echo done > {SHUTDOWN_MARKER_FILE}'
}
with mock('ups.driver_choices', return_value={'dummy-ups': 'Driver for multi-purpose UPS emulation',
'usbhid-ups$PROTECT NAS': 'AEG Power Solutions ups 3 PROTECT NAS (usbhid-ups)'}):
call('ups.update', payload)
try:
yield
finally:
call('ups.update', old_config)
remove_file(SHUTDOWN_MARKER_FILE)
remove_file(DUMMY_FAKEDATA_DEV)
def test__enable_ups_service():
results = get_service_state()
assert results['state'] == 'STOPPED', results
assert results['enable'] is False, results
call('service.update', 'ups', {'enable': True})
results = get_service_state()
assert results['enable'] is True, results
def test__set_ups_options():
results = call('ups.update', first_ups_payload)
for data in first_ups_payload.keys():
assert first_ups_payload[data] == results[data], results
def test__start_ups_service():
call('service.start', 'ups')
results = get_service_state()
assert results['state'] == 'RUNNING', results
def test__get_reports_configuration_as_saved():
results = call('ups.config')
for data in first_ups_payload.keys():
assert first_ups_payload[data] == results[data], results
def test__change_ups_options_while_service_is_running():
payload = {
'port': '65545',
'identifier': 'boo'
}
results = call('ups.update', payload)
for data in ['port', 'identifier']:
assert payload[data] == results[data], results
results = call('ups.config')
for data in ['port', 'identifier']:
assert payload[data] == results[data], results
def test__stop_ups_service():
results = get_service_state()
assert results['state'] == 'RUNNING', results
call('service.stop', 'ups')
results = get_service_state()
assert results['state'] == 'STOPPED', results
def test__change_ups_options():
results = call('ups.update', second_ups_payload)
for data in second_ups_payload.keys():
assert second_ups_payload[data] == results[data], results
call('service.start', 'ups')
results = get_service_state()
assert results['state'] == 'RUNNING', results
results = call('ups.config')
for data in second_ups_payload.keys():
assert second_ups_payload[data] == results[data], results
def test__get_ups_driver_choice():
results = call('ups.driver_choices')
assert isinstance(results, dict) is True, results
def test__get_ups_port_choice():
results = call('ups.port_choices')
assert isinstance(results, list) is True, results
assert isinstance(results[0], str) is True, results
def test__disable_and_stop_ups_service():
call('service.update', 'ups', {'enable': False})
results = get_service_state()
assert results['enable'] is False, results
call('service.stop', 'ups')
results = get_service_state()
assert results['state'] == 'STOPPED', results
def test__ups_online_to_online_lowbattery(ups_running, dummy_ups_driver_configured):
results = get_service_state()
assert results['state'] == 'RUNNING', results
sleep(2)
assert 'UPSBatteryLow' not in [alert['klass'] for alert in call('alert.list')]
write_fake_data({'battery.charge': 20, 'ups.status': 'OL LB'})
alert = wait_for_alert('UPSBatteryLow')
assert alert
assert 'battery.charge: 20' in alert['formatted'], alert
assert not did_shutdown()
def test__ups_online_to_onbatt(ups_running, dummy_ups_driver_configured):
assert 'UPSOnBattery' not in [alert['klass'] for alert in call('alert.list')]
write_fake_data({'battery.charge': 40, 'ups.status': 'OB'})
alert = wait_for_alert('UPSOnBattery')
assert alert
assert 'battery.charge: 40' in alert['formatted'], alert
assert not did_shutdown()
def test__ups_onbatt_to_online(ups_running, dummy_ups_driver_configured):
assert 'UPSOnline' not in [alert['klass'] for alert in call('alert.list')]
write_fake_data({'battery.charge': 100, 'ups.status': 'OL'})
alert = wait_for_alert('UPSOnline')
assert alert
assert 'battery.charge: 100' in alert['formatted'], alert
assert not did_shutdown()
def test__ups_online_to_onbatt_lowbattery(ups_running, dummy_ups_driver_configured):
assert 'UPSOnBattery' not in [alert['klass'] for alert in call('alert.list')]
write_fake_data({'battery.charge': 90, 'ups.status': 'OB'})
alert = wait_for_alert('UPSOnBattery')
assert alert
assert 'battery.charge: 90' in alert['formatted'], alert
write_fake_data({'battery.charge': 10, 'ups.status': 'OB LB'})
alert = wait_for_alert('UPSBatteryLow')
assert alert
assert 'battery.charge: 10' in alert['formatted'], alert
assert did_shutdown()
| 7,505 | Python | .py | 188 | 34.351064 | 131 | 0.660429 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,308 | test_account_privilege_authentication.py | truenas_middleware/tests/api2/test_account_privilege_authentication.py | import errno
import json
import logging
import pytest
import websocket
from middlewared.service_exception import CallError
from middlewared.test.integration.assets.account import user, unprivileged_user as unprivileged_user_template
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.utils import call, client, ssh, websocket_url
from middlewared.test.integration.utils.shell import assert_shell_works
logger = logging.getLogger(__name__)
@pytest.fixture(scope="module")
def unprivileged_user():
with unprivileged_user_template(
username="unprivileged",
group_name="unprivileged_users",
privilege_name="Unprivileged users",
allowlist=[{"method": "CALL", "resource": "system.info"}],
web_shell=False,
) as t:
yield t
@pytest.fixture()
def unprivileged_user_token(unprivileged_user):
with client(auth=(unprivileged_user.username, unprivileged_user.password)) as c:
return c.call("auth.generate_token", 300, {}, True)
@pytest.fixture(scope="module")
def unprivileged_user_with_web_shell():
with unprivileged_user_template(
username="unprivilegedws",
group_name="unprivileged_users_ws",
privilege_name="Unprivileged users with web shell",
allowlist=[],
web_shell=True,
) as t:
yield t
@pytest.fixture()
def unprivileged_user_with_web_shell_token(unprivileged_user_with_web_shell):
with client(auth=(unprivileged_user_with_web_shell.username, unprivileged_user_with_web_shell.password)) as c:
return c.call("auth.generate_token", 300, {}, True)
def test_libpam_auth(unprivileged_user):
pam_resp = call('auth.libpam_authenticate', unprivileged_user.username, unprivileged_user.password)
assert pam_resp['code'] == 0
assert pam_resp['reason'] == 'Success'
pam_resp = call('auth.libpam_authenticate', unprivileged_user.username, 'CANARY')
assert pam_resp['code'] == 7
assert pam_resp['reason'] == 'Authentication failure'
def test_websocket_auth_session_list_terminate(unprivileged_user):
with client(auth=(unprivileged_user.username, unprivileged_user.password)) as c:
sessions = call("auth.sessions")
my_sessions = [
s for s in sessions
if s["credentials"] == "LOGIN_PASSWORD" and s["credentials_data"]["username"] == unprivileged_user.username
]
assert len(my_sessions) == 1, sessions
call("auth.terminate_session", my_sessions[0]["id"])
with pytest.raises(Exception):
c.call("system.info")
sessions = call("auth.sessions")
assert not [
s for s in sessions
if s["credentials"] == "LOGIN_PASSWORD" and s["credentials_data"]["username"] == unprivileged_user.username
], sessions
def test_websocket_auth_terminate_all_other_sessions(unprivileged_user):
with client(auth=(unprivileged_user.username, unprivileged_user.password)) as c:
call("auth.terminate_other_sessions")
with pytest.raises(Exception):
c.call("system.info")
def test_websocket_auth_get_methods(unprivileged_user):
with client(auth=(unprivileged_user.username, unprivileged_user.password)) as c:
methods = c.call("core.get_methods")
assert "system.info" in methods
assert "pool.create" not in methods
def test_websocket_auth_calls_allowed_method(unprivileged_user):
with client(auth=(unprivileged_user.username, unprivileged_user.password)) as c:
c.call("system.info")
def test_websocket_auth_fails_to_call_forbidden_method(unprivileged_user):
with client(auth=(unprivileged_user.username, unprivileged_user.password)) as c:
with pytest.raises(CallError) as ve:
c.call("pool.create")
assert ve.value.errno == errno.EACCES
def test_unix_socket_auth_get_methods(unprivileged_user):
methods = json.loads(ssh(f"sudo -u {unprivileged_user.username} midclt call core.get_methods"))
assert "system.info" in methods
assert "pool.create" not in methods
def test_unix_socket_auth_calls_allowed_method(unprivileged_user):
ssh(f"sudo -u {unprivileged_user.username} midclt call system.info")
def test_unix_socket_auth_fails_to_call_forbidden_method(unprivileged_user):
result = ssh(f"sudo -u {unprivileged_user.username} midclt call pool.create", check=False, complete_response=True)
assert "Not authorized" in result["stderr"]
def test_unix_socket_auth_fails_when_user_has_no_privilege():
with dataset(f"noconnect_homedir") as homedir:
with user({
"username": "noconnect",
"full_name": "Noconnect",
"group_create": True,
"groups": [],
"home": f"/mnt/{homedir}",
"password": "test1234",
}):
result = ssh(f"sudo -u noconnect midclt call pool.create", check=False, complete_response=True)
assert "Not authenticated" in result["stderr"]
def test_token_auth_session_list_terminate(unprivileged_user, unprivileged_user_token):
with client(auth=None) as c:
assert c.call("auth.login_with_token", unprivileged_user_token)
sessions = call("auth.sessions")
my_sessions = [
s for s in sessions
if (
s["credentials"] == "TOKEN" and
s["credentials_data"]["parent"]["credentials"] == "LOGIN_PASSWORD" and
s["credentials_data"]["parent"]["credentials_data"]["username"] == unprivileged_user.username
)
]
assert len(my_sessions) == 1, sessions
call("auth.terminate_session", my_sessions[0]["id"])
with pytest.raises(Exception):
c.call("system.info")
def test_token_auth_calls_allowed_method(unprivileged_user_token):
with client(auth=None) as c:
assert c.call("auth.login_with_token", unprivileged_user_token)
c.call("system.info")
def test_token_auth_fails_to_call_forbidden_method(unprivileged_user_token):
with client(auth=None) as c:
assert c.call("auth.login_with_token", unprivileged_user_token)
with pytest.raises(CallError) as ve:
c.call("pool.create")
assert ve.value.errno == errno.EACCES
def test_drop_privileges(unprivileged_user_token):
with client() as c:
# This should drop privileges for the current root session
assert c.call("auth.login_with_token", unprivileged_user_token)
with pytest.raises(CallError) as ve:
c.call("pool.create")
assert ve.value.errno == errno.EACCES
def test_token_auth_working_not_working_web_shell(unprivileged_user_token):
ws = websocket.create_connection(websocket_url() + "/websocket/shell")
try:
ws.send(json.dumps({"token": unprivileged_user_token}))
resp_opcode, msg = ws.recv_data()
assert json.loads(msg.decode())["msg"] == "failed"
finally:
ws.close()
@pytest.mark.timeout(30)
def test_token_auth_working_web_shell(unprivileged_user_with_web_shell_token):
assert_shell_works(unprivileged_user_with_web_shell_token, "unprivilegedws")
| 7,142 | Python | .py | 145 | 42.165517 | 119 | 0.69213 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,309 | test_nfsv4_top_level_dataset.py | truenas_middleware/tests/api2/test_nfsv4_top_level_dataset.py | import pytest
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.utils import call, pool
@pytest.fixture(scope='module')
def set_nfsv4_top_level():
call('pool.dataset.update', pool, {'acltype': 'NFSV4', 'aclmode': 'PASSTHROUGH'})
try:
yield
finally:
call('pool.dataset.update', pool, {'acltype': 'POSIX', 'aclmode': 'DISCARD'})
def test__acltype_inherit(set_nfsv4_top_level):
with dataset('v4inherit') as ds:
entry = call('pool.dataset.query', [['name', '=', ds]], {'get': True})
assert entry['acltype']['value'] == 'NFSV4'
assert entry['aclmode']['value'] == 'PASSTHROUGH'
| 681 | Python | .py | 15 | 40.2 | 85 | 0.666161 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,310 | test_webui_crypto_service.py | truenas_middleware/tests/api2/test_webui_crypto_service.py | import errno
import pytest
from middlewared.service_exception import CallError
from middlewared.test.integration.assets.account import unprivileged_user_client
from middlewared.test.integration.utils import call
@pytest.mark.parametrize('role,endpoint,valid_role', (
('READONLY_ADMIN', 'webui.crypto.certificate_profiles', True),
('READONLY_ADMIN', 'webui.crypto.certificateauthority_profiles', True),
('NETWORK_INTERFACE_WRITE', 'webui.crypto.certificate_profiles', False),
('NETWORK_INTERFACE_WRITE', 'webui.crypto.certificateauthority_profiles', False),
))
def test_ui_crypto_profiles_readonly_role(role, endpoint, valid_role):
with unprivileged_user_client(roles=[role]) as c:
if valid_role:
c.call(endpoint)
else:
with pytest.raises(CallError) as ve:
c.call(endpoint)
assert ve.value.errno == errno.EACCES
assert ve.value.errmsg == 'Not authorized'
@pytest.mark.parametrize('role,valid_role', (
('READONLY_ADMIN', True),
('NETWORK_INTERFACE_WRITE', False),
))
def test_ui_crypto_domain_names_readonly_role(role, valid_role):
default_certificate = call('certificate.query', [('name', '=', 'truenas_default')])
if not default_certificate:
pytest.skip('Default certificate does not exist which is required for this test')
else:
default_certificate = default_certificate[0]
with unprivileged_user_client(roles=[role]) as c:
if valid_role:
c.call('webui.crypto.get_certificate_domain_names', default_certificate['id'])
else:
with pytest.raises(CallError) as ve:
c.call('webui.crypto.get_certificate_domain_names', default_certificate['id'])
assert ve.value.errno == errno.EACCES
assert ve.value.errmsg == 'Not authorized'
| 1,850 | Python | .py | 38 | 41.684211 | 94 | 0.695676 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,311 | test_simple_share.py | truenas_middleware/tests/api2/test_simple_share.py | # -*- coding=utf-8 -*-
import pytest
import secrets
import string
from middlewared.service_exception import ValidationErrors
from middlewared.test.integration.assets.account import user
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.assets.smb import smb_share
from middlewared.test.integration.utils import call
PASSWD = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(10))
def test__smb_simple_share_validation():
existing_smb_users = [x['username'] for x in call('user.query', [['smb', '=', True]])]
assert len(existing_smb_users) == 0, str(existing_smb_users)
with pytest.raises(ValidationErrors):
call('sharing.smb.share_precheck')
with user({
"username": "simple_share_user",
"full_name": "simple_share_user",
"group_create": True,
"password": PASSWD,
"smb": True,
}):
# First check that basic call of this endpoint succeeds
call('sharing.smb.share_precheck')
# Verify works with basic share name
call('sharing.smb.share_precheck', {'name': 'test_share'})
# Verify raises error if share name invalid
with pytest.raises(ValidationErrors):
call('sharing.smb.share_precheck', {'name': 'test_share*'})
# Another variant of invalid name
with pytest.raises(ValidationErrors):
call('sharing.smb.share_precheck', {'name': 'gLobaL'})
with dataset('test_smb') as ds:
with smb_share(f'/mnt/{ds}', 'test_share'):
with pytest.raises(ValidationErrors):
call('sharing.smb.share_precheck', {'name': 'test_share'})
| 1,703 | Python | .py | 36 | 40.111111 | 90 | 0.670894 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,312 | test_ipa_leave.py | truenas_middleware/tests/api2/test_ipa_leave.py | import errno
import pytest
from middlewared.service_exception import CallError
from middlewared.test.integration.assets.directory_service import ipa
from middlewared.test.integration.utils import call
@pytest.fixture(scope="module")
def ipa_config():
""" join then leave IPA domain so that we can evaluate server after leaving the IPA domain """
with ipa() as config:
ipa_config = config['ipa_config']
yield ipa_config
def test_cache_cleared(ipa_config):
ipa_users_cnt = call('user.query', [['local', '=', False]], {'count': True})
assert ipa_users_cnt == 0
ipa_groups_cnt = call('group.query', [['local', '=', False]], {'count': True})
assert ipa_groups_cnt == 0
@pytest.mark.parametrize('keytab_name', [
'IPA_MACHINE_ACCOUNT',
'IPA_NFS_KEYTAB',
'IPA_SMB_KEYTAB'
])
def test_keytabs_deleted(ipa_config, keytab_name):
kt = call('kerberos.keytab.query', [['name', '=', keytab_name]])
assert len(kt) == 0
def test_check_no_kerberos_ticket(ipa_config):
with pytest.raises(CallError) as ce:
call('kerberos.check_ticket')
assert ce.value.errno == errno.ENOKEY
def test_check_no_kerberos_realm(ipa_config):
realms = call('kerberos.realm.query')
assert len(realms) == 0, str(realms)
def test_system_keytab_has_no_nfs_principal(ipa_config):
assert not call('kerberos.keytab.has_nfs_principal')
def test_smb_keytab_does_not_exist(ipa_config):
with pytest.raises(CallError) as ce:
call('filesystem.stat', '/etc/ipa/smb.keytab')
assert ce.value.errno == errno.ENOENT
def test_no_admin_privilege(ipa_config):
priv = call('privilege.query', [['name', '=', ipa_config['domain'].upper()]])
assert priv == []
def test_no_certificate(ipa_config):
certs = call('certificateauthority.query', [['name', '=', 'IPA_DOMAIN_CACERT']])
assert len(certs) == 0, str(certs)
def test_no_dns_resolution(ipa_config):
try:
results = call('dnsclient.forward_lookup', {'names': [ipa_config['host']]})
assert len(results) == 0
except Exception:
pass
| 2,088 | Python | .py | 49 | 38.081633 | 98 | 0.688679 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,313 | test_schema_private.py | truenas_middleware/tests/api2/test_schema_private.py | import pytest
from middlewared.test.integration.utils import call, client, mock, ssh
def test_private_params_do_not_leak_to_logs():
with mock("test.test1", """
from middlewared.service import accepts
from middlewared.schema import Dict, Str
@accepts(Dict("test", Str("password", private=True)))
async def mock(self, args):
raise Exception()
"""):
log_before = ssh("cat /var/log/middlewared.log")
with client(py_exceptions=False) as c:
with pytest.raises(Exception):
c.call("test.test1", {"password": "secret"})
log = ssh("cat /var/log/middlewared.log")[len(log_before):]
assert "Exception while calling test.test1(*[{'password': '********'}])" in log
def test_private_params_do_not_leak_to_core_get_jobs():
with mock("test.test1", """
from middlewared.service import accepts, job
from middlewared.schema import Dict, Str
@accepts(Dict("test", Str("password", private=True)))
@job()
async def mock(self, job, args):
return 42
"""):
job_id = call("test.test1", {"password": "secret"})
job_descr = call("core.get_jobs", [["id", "=", job_id]], {"get": True})
assert job_descr["arguments"] == [{"password": "********"}]
| 1,330 | Python | .py | 28 | 38.821429 | 87 | 0.597986 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,314 | test_smb_client.py | truenas_middleware/tests/api2/test_smb_client.py | import os
import pytest
from middlewared.test.integration.assets.account import user, group
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.assets.smb import (
del_stream, get_stream, list_stream, set_stream, set_xattr_compat,
smb_share, smb_mount
)
from middlewared.test.integration.utils import call, client, ssh
PERMSET = {
"READ_DATA": False,
"WRITE_DATA": False,
"APPEND_DATA": False,
"READ_NAMED_ATTRS": False,
"WRITE_NAMED_ATTRS": False,
"EXECUTE": False,
"DELETE_CHILD": False,
"READ_ATTRIBUTES": False,
"WRITE_ATTRIBUTES": False,
"DELETE": False,
"READ_ACL": False,
"WRITE_ACL": False,
"WRITE_OWNER": False,
"SYNCHRONIZE": True
}
SAMPLE_ENTRY = {
"tag": "GROUP",
"id": 666,
"type": "ALLOW",
"perms": PERMSET,
"flags": {"BASIC": "INHERIT"}
}
PERSISTENT_ACL = [
{
"tag": "GROUP",
"id": 545,
"type": "ALLOW",
"perms": {"BASIC": "FULL_CONTROL"},
"flags": {"BASIC": "INHERIT"}
}
]
TMP_SMB_USER_PASSWORD = 'Abcd1234$'
@pytest.fixture(scope='module')
def setup_smb_tests(request):
with dataset('smbclient-testing', data={'share_type': 'SMB'}) as ds:
with user({
'username': 'smbuser',
'full_name': 'smbuser',
'group_create': True,
'password': TMP_SMB_USER_PASSWORD
}) as u:
with smb_share(os.path.join('/mnt', ds), 'client_share') as s:
try:
call('service.start', 'cifs')
yield {'dataset': ds, 'share': s, 'user': u}
finally:
call('service.stop', 'cifs')
@pytest.fixture(scope='module')
def mount_share(setup_smb_tests):
with smb_mount(setup_smb_tests['share']['name'], 'smbuser', TMP_SMB_USER_PASSWORD) as mp:
yield setup_smb_tests | {'mountpoint': mp}
def compare_acls(local_path, share_path):
local_acl = call('filesystem.getacl', local_path)
local_acl.pop('path')
smb_acl = call('filesystem.getacl', share_path)
smb_acl.pop('path')
assert local_acl == smb_acl
def test_smb_mount(request, mount_share):
assert call('filesystem.statfs', mount_share['mountpoint'])['fstype'] == 'cifs'
def test_acl_share_root(request, mount_share):
compare_acls(mount_share['share']['path'], mount_share['mountpoint'])
def test_acl_share_subdir(request, mount_share):
call('filesystem.mkdir', {
'path': os.path.join(mount_share['share']['path'], 'testdir'),
'options': {'raise_chmod_error': False},
})
compare_acls(
os.path.join(mount_share['share']['path'], 'testdir'),
os.path.join(mount_share['mountpoint'], 'testdir')
)
def test_acl_share_file(request, mount_share):
ssh(f'touch {os.path.join(mount_share["share"]["path"], "testfile")}')
compare_acls(
os.path.join(mount_share['share']['path'], 'testfile'),
os.path.join(mount_share['mountpoint'], 'testfile')
)
@pytest.mark.parametrize('perm', PERMSET.keys())
def test_acl_share_permissions(request, mount_share, perm):
assert call('filesystem.statfs', mount_share['mountpoint'])['fstype'] == 'cifs'
SAMPLE_ENTRY['perms'] | {perm: True}
payload = {
'path': mount_share['share']['path'],
'dacl': [SAMPLE_ENTRY] + PERSISTENT_ACL
}
call('filesystem.setacl', payload, job=True)
compare_acls(mount_share['share']['path'], mount_share['mountpoint'])
@pytest.mark.parametrize('flagset', [
{
'FILE_INHERIT': True,
'DIRECTORY_INHERIT': True,
'NO_PROPAGATE_INHERIT': False,
'INHERIT_ONLY': False,
'INHERITED': False,
},
{
'FILE_INHERIT': True,
'DIRECTORY_INHERIT': False,
'NO_PROPAGATE_INHERIT': False,
'INHERIT_ONLY': False,
'INHERITED': False,
},
{
'FILE_INHERIT': False,
'DIRECTORY_INHERIT': True,
'NO_PROPAGATE_INHERIT': False,
'INHERIT_ONLY': False,
'INHERITED': False,
},
{
'FILE_INHERIT': False,
'DIRECTORY_INHERIT': False,
'NO_PROPAGATE_INHERIT': False,
'INHERIT_ONLY': False,
'INHERITED': False,
},
{
'FILE_INHERIT': True,
'DIRECTORY_INHERIT': False,
'NO_PROPAGATE_INHERIT': False,
'INHERIT_ONLY': True,
'INHERITED': False,
},
{
'FILE_INHERIT': False,
'DIRECTORY_INHERIT': True,
'NO_PROPAGATE_INHERIT': False,
'INHERIT_ONLY': True,
'INHERITED': False,
},
{
'FILE_INHERIT': True,
'DIRECTORY_INHERIT': False,
'NO_PROPAGATE_INHERIT': True,
'INHERIT_ONLY': True,
'INHERITED': False,
},
{
'FILE_INHERIT': False,
'DIRECTORY_INHERIT': True,
'NO_PROPAGATE_INHERIT': True,
'INHERIT_ONLY': True,
'INHERITED': False,
}
])
def test_acl_share_flags(request, mount_share, flagset):
assert call('filesystem.statfs', mount_share['mountpoint'])['fstype'] == 'cifs'
SAMPLE_ENTRY['flags'] = flagset
payload = {
'path': mount_share['share']['path'],
'dacl': [SAMPLE_ENTRY] + PERSISTENT_ACL
}
call('filesystem.setacl', payload, job=True)
compare_acls(mount_share['share']['path'], mount_share['mountpoint'])
def do_stream_ops(fname, samba_compat):
set_xattr_compat(samba_compat)
assert list_stream(fname) == []
data_to_write = b'canary'
if samba_compat:
data_to_write += b'\x00'
# test basic get / set
set_stream(fname, 'teststream', data_to_write)
assert list_stream(fname) == ['teststream']
xat_data = get_stream(fname, 'teststream')
assert xat_data == data_to_write
data_to_write = b'can'
if samba_compat:
data_to_write += b'\x00'
# test that stream is appropriately truncated
set_stream(fname, 'teststream', data_to_write)
xat_data = get_stream(fname, 'teststream')
assert xat_data == data_to_write
# test that stream can be deleted
del_stream(fname, 'teststream')
assert list_stream(fname) == []
@pytest.mark.parametrize("is_dir", [True, False])
@pytest.mark.parametrize("samba_compat", [True, False])
def test_get_set_del_stream(request, mount_share, is_dir, samba_compat):
assert call('filesystem.statfs', mount_share['mountpoint'])['fstype'] == 'cifs'
if is_dir:
fname = os.path.join(mount_share['mountpoint'], 'testdirstream')
call('filesystem.mkdir', {'path': fname, 'options': {'raise_chmod_error': False}})
cleanup = f'rmdir {fname}'
else:
fname = os.path.join(mount_share['mountpoint'], 'testfilestream')
ssh(f'touch {fname}')
cleanup = f'rm {fname}'
try:
do_stream_ops(fname, samba_compat)
finally:
ssh(cleanup)
| 6,891 | Python | .py | 200 | 27.96 | 93 | 0.611161 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,315 | test_009_fenced.py | truenas_middleware/tests/api2/test_009_fenced.py | import pytest
from auto_config import ha
from middlewared.test.integration.utils import call
@pytest.mark.skipif(not ha, reason='HA only test')
def test_01_verify_fenced_is_running():
assert call('failover.fenced.run_info')['running']
| 242 | Python | .py | 6 | 38.166667 | 54 | 0.7897 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,316 | test_iscsi_global_crud_roles.py | truenas_middleware/tests/api2/test_iscsi_global_crud_roles.py | import pytest
from middlewared.test.integration.assets.roles import common_checks
@pytest.mark.parametrize("role", ["SHARING_READ", "SHARING_ISCSI_READ", "SHARING_ISCSI_GLOBAL_READ"])
def test_read_role_can_read(unprivileged_user_fixture, role):
common_checks(unprivileged_user_fixture, "iscsi.global.config", role, True, valid_role_exception=False)
common_checks(unprivileged_user_fixture, "iscsi.global.sessions", role, True, valid_role_exception=False)
common_checks(unprivileged_user_fixture, "iscsi.global.client_count", role, True, valid_role_exception=False)
common_checks(unprivileged_user_fixture, "iscsi.global.alua_enabled", role, True, valid_role_exception=False)
@pytest.mark.parametrize("role", ["SHARING_READ", "SHARING_ISCSI_READ", "SHARING_ISCSI_GLOBAL_READ"])
def test_read_role_cant_write(unprivileged_user_fixture, role):
common_checks(unprivileged_user_fixture, "iscsi.global.update", role, False)
@pytest.mark.parametrize("role", ["SHARING_WRITE", "SHARING_ISCSI_WRITE", "SHARING_ISCSI_GLOBAL_WRITE"])
def test_write_role_can_write(unprivileged_user_fixture, role):
common_checks(unprivileged_user_fixture, "iscsi.global.update", role, True)
| 1,195 | Python | .py | 14 | 82.142857 | 113 | 0.776831 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,317 | test_zpool_capacity_alert.py | truenas_middleware/tests/api2/test_zpool_capacity_alert.py | import pytest
from pytest_dependency import depends
from middlewared.service_exception import CallError
from middlewared.test.integration.utils import call, mock, pool
def test__does_not_emit_alert(request):
with mock("zfs.pool.query", return_value=[
{
"name": pool,
"properties": {
"capacity": {
"parsed": "50",
}
},
}
]):
assert call("alert.run_source", "ZpoolCapacity") == []
def test__emits_alert(request):
with mock("zfs.pool.query", return_value=[
{
"name": pool,
"properties": {
"capacity": {
"parsed": "85",
}
},
}
]):
alerts = call("alert.run_source", "ZpoolCapacity")
assert len(alerts) == 1
assert alerts[0]["klass"] == "ZpoolCapacityWarning"
assert alerts[0]["key"] == f'["{pool}"]'
assert alerts[0]["args"] == {"volume": pool, "capacity": 85}
def test__does_not_flap_alert(request):
with mock("zfs.pool.query", return_value=[
{
"name": pool,
"properties": {
"capacity": {
"parsed": "79",
}
},
}
]):
with pytest.raises(CallError) as e:
call("alert.run_source", "ZpoolCapacity")
assert e.value.errno == CallError.EALERTCHECKERUNAVAILABLE
| 1,469 | Python | .py | 46 | 21.804348 | 68 | 0.50742 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,318 | test_core_bulk.py | truenas_middleware/tests/api2/test_core_bulk.py | from unittest.mock import ANY
import pytest
from middlewared.test.integration.assets.account import unprivileged_user_client
from middlewared.test.integration.utils import call, mock
from middlewared.test.integration.utils.audit import expect_audit_log
from truenas_api_client import ClientException
def test_core_bulk_reports_job_id():
with mock("test.test1", """\
from middlewared.service import job, CallError
@job()
def mock(self, job, *args):
if args[0] == 0:
raise CallError("Error")
else:
return args[0]
"""):
result = call("core.bulk", "test.test1", [[0], [10]], job=True)
assert result == [
{"job_id": ANY, "result": None, "error": "[EFAULT] Error"},
{"job_id": ANY, "result": 10, "error": None},
]
job_0 = call("core.get_jobs", [["id", "=", result[0]["job_id"]]], {"get": True})
assert job_0["arguments"] == [0]
job_1 = call("core.get_jobs", [["id", "=", result[1]["job_id"]]], {"get": True})
assert job_1["arguments"] == [10]
def test_authorized():
with unprivileged_user_client(allowlist=[{"method": "CALL", "resource": "test.test1"}]) as c:
with mock("test.test1", """
from middlewared.service import pass_app
@pass_app()
async def mock(self, app):
return app.authenticated_credentials.dump()["username"].startswith("unprivileged")
"""):
assert c.call("core.bulk", "test.test1", [[]], job=True) == [{"result": True, "error": None}]
def test_authorized_audit():
with unprivileged_user_client(allowlist=[{"method": "CALL", "resource": "test.test1"}]) as c:
with mock("test.test1", """
from middlewared.schema import Int
from middlewared.service import accepts
@accepts(Int("param"), audit="Mock", audit_extended=lambda param: str(param))
async def mock(self, param):
return
"""):
with expect_audit_log([
{
"event": "METHOD_CALL",
"event_data": {
"authenticated": True,
"authorized": True,
"method": "test.test1",
"params": [42],
"description": "Mock 42",
},
"success": True,
}
]):
c.call("core.bulk", "test.test1", [[42]], job=True)
def test_not_authorized():
with unprivileged_user_client(allowlist=[]) as c:
with pytest.raises(ClientException) as ve:
c.call("core.bulk", "test.test1", [[]], job=True)
assert ve.value.error == "[EPERM] Not authorized"
def test_not_authorized_audit():
with unprivileged_user_client() as c:
with expect_audit_log([
{
"event": "METHOD_CALL",
"event_data": {
"authenticated": True,
"authorized": False,
"method": "user.create",
"params": [{"username": "sergey", "full_name": "Sergey"}],
"description": "Create user sergey",
},
"success": False,
}
]):
with pytest.raises(ClientException):
c.call("core.bulk", "user.create", [[{"username": "sergey", "full_name": "Sergey"}]], job=True)
| 3,521 | Python | .py | 79 | 32.240506 | 111 | 0.521612 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,319 | test_vmware_state.py | truenas_middleware/tests/api2/test_vmware_state.py | from unittest.mock import ANY
from middlewared.test.integration.utils import call, mock
def test_vmware_state_lifetime():
vmsnapobj = {
"hostname": "host",
"username": "user",
"password": "pass",
}
with mock("vmware.validate_data", return_value=None):
vmware = call("vmware.create", {
"datastore": "ds",
"filesystem": "fs",
**vmsnapobj,
})
try:
assert vmware["state"] == {"state": "PENDING"}
call("vmware.alert_vmware_login_failed", vmsnapobj, "Unknown error")
vmware = call("vmware.get_instance", vmware["id"])
assert vmware["state"] == {"state": "ERROR", "error": "Unknown error", "datetime": ANY}
call("vmware.delete_vmware_login_failed_alert", vmsnapobj)
vmware = call("vmware.get_instance", vmware["id"])
assert vmware["state"] == {"state": "SUCCESS", "datetime": ANY}
call("vmware.update", vmware["id"], {})
vmware = call("vmware.get_instance", vmware["id"])
assert vmware["state"] == {"state": "PENDING"}
finally:
call("vmware.delete", vmware["id"])
| 1,199 | Python | .py | 27 | 34.444444 | 99 | 0.562607 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,320 | test_job_events.py | truenas_middleware/tests/api2/test_job_events.py | import pprint
from middlewared.test.integration.assets.account import unprivileged_user_client
from middlewared.test.integration.utils import call, client, mock
def test_successful_job_events():
with mock("test.test1", """
from middlewared.service import job
@job()
def mock(self, job, *args):
return 42
"""):
with client() as c:
events = []
def callback(type, **message):
events.append((type, message))
c.subscribe("core.get_jobs", callback, sync=True)
c.call("test.test1", job=True)
# FIXME: Sometimes an equal message for `SUCCESS` state is being sent (or received) twice, we were not able
# to understand why and this does not break anything so we are not willing to waste our time investigating
# this.
if len(events) == 4 and events[2] == events[3]:
events = events[:3]
assert len(events) == 3, pprint.pformat(events, indent=2)
assert events[0][0] == "ADDED"
assert events[0][1]["fields"]["state"] == "WAITING"
assert events[1][0] == "CHANGED"
assert events[1][1]["fields"]["state"] == "RUNNING"
assert events[2][0] == "CHANGED"
assert events[2][1]["fields"]["state"] == "SUCCESS"
assert events[2][1]["fields"]["result"] == 42
def test_unprivileged_user_only_sees_its_own_jobs_events():
with mock("test.test1", """
from middlewared.service import job
@job()
def mock(self, job, *args):
return 42
"""):
with unprivileged_user_client(allowlist=[{"method": "CALL", "resource": "test.test1"}]) as c:
events = []
def callback(type, **message):
events.append((type, message))
c.subscribe("core.get_jobs", callback, sync=True)
call("test.test1", "secret", job=True)
c.call("test.test1", "not secret", job=True)
assert all(event[1]["fields"]["arguments"] == ["not secret"]
for event in events), pprint.pformat(events, indent=2)
| 2,184 | Python | .py | 45 | 37.355556 | 119 | 0.573446 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,321 | test_pool_dataset_unlock_recursive.py | truenas_middleware/tests/api2/test_pool_dataset_unlock_recursive.py | from middlewared.test.integration.utils import call, ssh
from middlewared.test.integration.assets.pool import pool
def test_pool_dataset_unlock_recursive():
key = "0" * 32
try:
ssh(f"echo -n '{key}' > /tmp/key")
ssh(f"zfs create -o encryption=on -o keyformat=raw -o keylocation=file:///tmp/key {pool}/test")
ssh(f"zfs create -o encryption=on -o keyformat=raw -o keylocation=file:///tmp/key {pool}/test/nested")
ssh(f"echo TEST > /mnt/{pool}/test/nested/file")
ssh("rm /tmp/key")
ssh(f"zfs set readonly=on {pool}/test")
ssh(f"zfs set readonly=on {pool}/test/nested")
ssh(f"zfs unmount {pool}/test")
ssh(f"zfs unload-key -r {pool}/test")
result = call("pool.dataset.unlock", f"{pool}/test", {
"recursive": True,
"datasets": [
{
"name": f"{pool}/test",
"key": key.encode("ascii").hex(),
"recursive": True,
},
],
}, job=True)
assert not result["failed"]
assert not call("pool.dataset.get_instance", f"{pool}/test")["locked"]
assert not call("pool.dataset.get_instance", f"{pool}/test/nested")["locked"]
# Ensure the child dataset is mounted
assert ssh(f"cat /mnt/{pool}/test/nested/file") == "TEST\n"
# Ensure the keys are stored in the database to be able to unlock the datasets after reboot
assert call("datastore.query", "storage.encrypteddataset", [["name", "=", f"{pool}/test"]])
assert call("datastore.query", "storage.encrypteddataset", [["name", "=", f"{pool}/test/nested"]])
finally:
call("pool.dataset.delete", f"{pool}/test", {"recursive": True})
| 1,760 | Python | .py | 34 | 41.764706 | 110 | 0.587209 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,322 | test_iscsi_targetextent_crud_roles.py | truenas_middleware/tests/api2/test_iscsi_targetextent_crud_roles.py | import pytest
from middlewared.test.integration.assets.roles import common_checks
@pytest.mark.parametrize("role", ["SHARING_READ", "SHARING_ISCSI_READ", "SHARING_ISCSI_TARGETEXTENT_READ"])
def test_read_role_can_read(unprivileged_user_fixture, role):
common_checks(unprivileged_user_fixture, "iscsi.targetextent.query", role, True, valid_role_exception=False)
@pytest.mark.parametrize("role", ["SHARING_READ", "SHARING_ISCSI_READ", "SHARING_ISCSI_TARGETEXTENT_READ"])
def test_read_role_cant_write(unprivileged_user_fixture, role):
common_checks(unprivileged_user_fixture, "iscsi.targetextent.create", role, False)
common_checks(unprivileged_user_fixture, "iscsi.targetextent.update", role, False)
common_checks(unprivileged_user_fixture, "iscsi.targetextent.delete", role, False)
@pytest.mark.parametrize("role", ["SHARING_WRITE", "SHARING_ISCSI_WRITE", "SHARING_ISCSI_TARGETEXTENT_WRITE"])
def test_write_role_can_write(unprivileged_user_fixture, role):
common_checks(unprivileged_user_fixture, "iscsi.targetextent.create", role, True)
common_checks(unprivileged_user_fixture, "iscsi.targetextent.update", role, True)
common_checks(unprivileged_user_fixture, "iscsi.targetextent.delete", role, True)
| 1,238 | Python | .py | 15 | 79.2 | 112 | 0.782895 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,323 | test_certs.py | truenas_middleware/tests/api2/test_certs.py | import datetime
import os.path
import textwrap
import cryptography
import pytest
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 import Name, NameAttribute, CertificateBuilder, BasicConstraints
from middlewared.test.integration.assets.crypto import (
certificate_signing_request, get_cert_params, intermediate_certificate_authority, root_certificate_authority
)
from middlewared.test.integration.utils import call
from truenas_api_client import ValidationErrors
# We would like to test the following cases
# Creating root CA
# Creating intermediate CA
# Importing CA
# Creating certificate from root/intermediate CAs
# Create CSR
# Signing CSR
def test_creating_root_ca():
root_ca = call('certificateauthority.create', {
**get_cert_params(),
'name': 'test_root_ca',
'create_type': 'CA_CREATE_INTERNAL',
})
try:
assert root_ca['CA_type_internal'] is True, root_ca
finally:
call('certificateauthority.delete', root_ca['id'])
def test_root_ca_issuer_reported_correctly():
with root_certificate_authority('root_ca_test') as root_ca:
assert root_ca['issuer'] == 'self-signed', root_ca
def test_creating_intermediate_ca():
with root_certificate_authority('root_ca_test') as root_ca:
intermediate_ca = call('certificateauthority.create', {
**get_cert_params(),
'signedby': root_ca['id'],
'name': 'test_intermediate_ca',
'create_type': 'CA_CREATE_INTERMEDIATE',
})
try:
assert intermediate_ca['CA_type_intermediate'] is True, intermediate_ca
finally:
call('certificateauthority.delete', intermediate_ca['id'])
def test_ca_intermediate_issuer_reported_correctly():
with root_certificate_authority('root_ca_test') as root_ca:
intermediate_ca = call('certificateauthority.create', {
**get_cert_params(),
'signedby': root_ca['id'],
'name': 'test_intermediate_ca',
'create_type': 'CA_CREATE_INTERMEDIATE',
})
root_ca = call('certificateauthority.get_instance', root_ca['id'])
try:
assert intermediate_ca['issuer'] == root_ca, intermediate_ca
finally:
call('certificateauthority.delete', intermediate_ca['id'])
def test_cert_chain_of_intermediate_ca_reported_correctly():
with root_certificate_authority('root_ca_test') as root_ca:
intermediate_ca = call('certificateauthority.create', {
**get_cert_params(),
'signedby': root_ca['id'],
'name': 'test_intermediate_ca',
'create_type': 'CA_CREATE_INTERMEDIATE',
})
try:
assert intermediate_ca['chain_list'] == [
intermediate_ca['certificate'], root_ca['certificate']
], intermediate_ca
finally:
call('certificateauthority.delete', intermediate_ca['id'])
def test_importing_ca():
with root_certificate_authority('root_ca_test') as root_ca:
imported_ca = call('certificateauthority.create', {
'certificate': root_ca['certificate'],
'privatekey': root_ca['privatekey'],
'name': 'test_imported_ca',
'create_type': 'CA_CREATE_IMPORTED',
})
try:
assert imported_ca['CA_type_existing'] is True, imported_ca
finally:
call('certificateauthority.delete', imported_ca['id'])
def test_ca_imported_issuer_reported_correctly():
with root_certificate_authority('root_ca_test') as root_ca:
imported_ca = call('certificateauthority.create', {
'certificate': root_ca['certificate'],
'privatekey': root_ca['privatekey'],
'name': 'test_imported_ca',
'create_type': 'CA_CREATE_IMPORTED',
})
try:
assert imported_ca['issuer'] == 'external', imported_ca
finally:
call('certificateauthority.delete', imported_ca['id'])
def test_ca_imported_add_to_trusted_store_reported_correctly():
with root_certificate_authority('root_ca_test') as root_ca:
imported_ca = call('certificateauthority.create', {
'certificate': root_ca['certificate'],
'privatekey': root_ca['privatekey'],
'name': 'test_tinkerbell',
'add_to_trusted_store': True,
'create_type': 'CA_CREATE_IMPORTED',
})
try:
assert imported_ca['add_to_trusted_store'] is True, imported_ca
finally:
call('certificateauthority.delete', imported_ca['id'])
def test_creating_cert_from_root_ca():
with root_certificate_authority('root_ca_test') as root_ca:
cert = call('certificate.create', {
'name': 'cert_test',
'signedby': root_ca['id'],
'create_type': 'CERTIFICATE_CREATE_INTERNAL',
**get_cert_params(),
}, job=True)
try:
assert cert['cert_type_internal'] is True, cert
finally:
call('certificate.delete', cert['id'], job=True)
def test_cert_chain_of_root_ca_reported_correctly():
with root_certificate_authority('root_ca_test') as root_ca:
cert = call('certificate.create', {
'name': 'cert_test',
'signedby': root_ca['id'],
'create_type': 'CERTIFICATE_CREATE_INTERNAL',
**get_cert_params(),
}, job=True)
try:
assert cert['chain_list'] == [cert['certificate'], root_ca['certificate']], cert
finally:
call('certificate.delete', cert['id'], job=True)
def test_creating_cert_from_intermediate_ca():
with intermediate_certificate_authority('root_ca', 'intermediate_ca') as (root_ca, intermediate_ca):
cert = call('certificate.create', {
'name': 'cert_test',
'signedby': intermediate_ca['id'],
'create_type': 'CERTIFICATE_CREATE_INTERNAL',
**get_cert_params(),
}, job=True)
try:
assert cert['cert_type_internal'] is True, cert
finally:
call('certificate.delete', cert['id'], job=True)
def test_cert_chain_reported_correctly():
with intermediate_certificate_authority('root_ca', 'intermediate_ca') as (root_ca, intermediate_ca):
cert = call('certificate.create', {
'name': 'cert_test',
'signedby': intermediate_ca['id'],
'create_type': 'CERTIFICATE_CREATE_INTERNAL',
**get_cert_params(),
}, job=True)
try:
assert cert['chain_list'] == [
cert['certificate'], intermediate_ca['certificate'], root_ca['certificate']
], cert
finally:
call('certificate.delete', cert['id'], job=True)
def test_cert_issuer_reported_correctly():
with intermediate_certificate_authority('root_ca', 'intermediate_ca') as (root_ca, intermediate_ca):
cert = call('certificate.create', {
'name': 'cert_test',
'signedby': intermediate_ca['id'],
'create_type': 'CERTIFICATE_CREATE_INTERNAL',
**get_cert_params(),
}, job=True)
intermediate_ca = call('certificateauthority.get_instance', intermediate_ca['id'])
try:
assert cert['issuer'] == intermediate_ca, cert
finally:
call('certificate.delete', cert['id'], job=True)
@pytest.mark.parametrize('add_to_trusted_store_enabled', [
True,
False,
])
def test_cert_add_to_trusted_store(add_to_trusted_store_enabled):
with intermediate_certificate_authority('root_ca', 'intermediate_ca') as (root_ca, intermediate_ca):
cert = call('certificate.create', {
'name': 'cert_trusted_store_test',
'signedby': intermediate_ca['id'],
'create_type': 'CERTIFICATE_CREATE_INTERNAL',
'add_to_trusted_store': add_to_trusted_store_enabled,
**get_cert_params(),
}, job=True)
try:
assert cert['add_to_trusted_store'] == add_to_trusted_store_enabled
args = ['filesystem.stat', os.path.join('/var/local/ca-certificates', f'cert_{cert["name"]}.crt')]
if add_to_trusted_store_enabled:
assert call(*args)
else:
with pytest.raises(Exception):
call(*args)
finally:
call('certificate.delete', cert['id'], job=True)
def test_creating_csr():
with certificate_signing_request('csr_test') as csr:
assert csr['cert_type_CSR'] is True, csr
def test_issuer_of_csr():
with certificate_signing_request('csr_test') as csr:
assert csr['issuer'] == 'external - signature pending', csr
def test_signing_csr():
with root_certificate_authority('root_ca') as root_ca:
with certificate_signing_request('csr_test') as csr:
cert = call('certificateauthority.ca_sign_csr', {
'ca_id': root_ca['id'],
'csr_cert_id': csr['id'],
'name': 'signed_cert',
})
root_ca = call('certificateauthority.get_instance', root_ca['id'])
try:
assert isinstance(cert['signedby'], dict), cert
assert cert['signedby']['id'] == root_ca['id'], cert
assert cert['chain_list'] == [cert['certificate'], root_ca['certificate']]
assert cert['issuer'] == root_ca, cert
finally:
call('certificate.delete', cert['id'], job=True)
def test_sign_csr_with_imported_ca():
# Creating Root CA
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
backend=default_backend()
)
# Serialize the private key
private_key_bytes = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption() # No encryption for test purposes
)
# Create a self-signed certificate
subject = Name([
NameAttribute(cryptography.x509.NameOID.COUNTRY_NAME, u'US'),
NameAttribute(cryptography.x509.NameOID.STATE_OR_PROVINCE_NAME, u'Ohio'),
NameAttribute(cryptography.x509.NameOID.LOCALITY_NAME, u'Texas'),
NameAttribute(cryptography.x509.NameOID.ORGANIZATION_NAME, u'MyCA'),
NameAttribute(cryptography.x509.NameOID.COMMON_NAME, u'MyCA'),
])
issuer = subject
cert = CertificateBuilder().subject_name(subject).issuer_name(issuer).not_valid_before(
datetime.datetime.utcnow()).not_valid_after(
datetime.datetime.utcnow() + datetime.timedelta(days=3650)).serial_number(
x509.random_serial_number()).public_key(
private_key.public_key()).add_extension(
BasicConstraints(ca=True, path_length=None), critical=True).sign(
private_key, hashes.SHA256(), default_backend()
)
# Serialize the certificate
cert_bytes = cert.public_bytes(serialization.Encoding.PEM)
imported_root_ca = call('certificateauthority.create', {
'certificate': cert_bytes.decode('utf-8'),
'privatekey': private_key_bytes.decode('utf-8'),
'name': 'test_imported_root_ca',
'create_type': 'CA_CREATE_IMPORTED',
})
with certificate_signing_request('csr_test') as csr:
cert = call('certificateauthority.ca_sign_csr', {
'ca_id': imported_root_ca['id'],
'csr_cert_id': csr['id'],
'name': 'inter_signed_csr'
})
cert_pem_data = cert['certificate'].encode()
cert_data = x509.load_pem_x509_certificate(cert_pem_data, default_backend())
cert_issuer = cert_data.issuer
ca_pem_data = imported_root_ca['certificate'].encode()
ca_data = x509.load_pem_x509_certificate(ca_pem_data, default_backend())
ca_subject = ca_data.subject
imported_root_ca = call('certificateauthority.get_instance', imported_root_ca['id'])
try:
assert imported_root_ca['CA_type_existing'] is True, imported_root_ca
assert isinstance(cert['signedby'], dict), cert
assert cert['signedby']['id'] == imported_root_ca['id'], cert
assert cert['chain_list'] == [cert['certificate'], imported_root_ca['certificate']], cert
assert cert['issuer'] == imported_root_ca, cert
assert cert_issuer == ca_subject
finally:
call('certificate.delete', cert['id'], job=True)
call('certificateauthority.delete', imported_root_ca['id'])
def test_revoking_cert():
with intermediate_certificate_authority('root_ca', 'intermediate_ca') as (root_ca, intermediate_ca):
cert = call('certificate.create', {
'name': 'cert_test',
'signedby': intermediate_ca['id'],
'create_type': 'CERTIFICATE_CREATE_INTERNAL',
**get_cert_params(),
}, job=True)
try:
assert cert['can_be_revoked'] is True, cert
cert = call('certificate.update', cert['id'], {'revoked': True}, job=True)
assert cert['revoked'] is True, cert
root_ca = call('certificateauthority.get_instance', root_ca['id'])
intermediate_ca = call('certificateauthority.get_instance', intermediate_ca['id'])
assert len(root_ca['revoked_certs']) == 1, root_ca
assert len(intermediate_ca['revoked_certs']) == 1, intermediate_ca
assert root_ca['revoked_certs'][0]['certificate'] == cert['certificate'], root_ca
assert intermediate_ca['revoked_certs'][0]['certificate'] == cert['certificate'], intermediate_ca
finally:
call('certificate.delete', cert['id'], job=True)
def test_revoking_ca():
with intermediate_certificate_authority('root_ca', 'intermediate_ca') as (root_ca, intermediate_ca):
cert = call('certificate.create', {
'name': 'cert_test',
'signedby': intermediate_ca['id'],
'create_type': 'CERTIFICATE_CREATE_INTERNAL',
**get_cert_params(),
}, job=True)
try:
assert intermediate_ca['can_be_revoked'] is True, intermediate_ca
intermediate_ca = call('certificateauthority.update', intermediate_ca['id'], {'revoked': True})
assert intermediate_ca['revoked'] is True, intermediate_ca
cert = call('certificate.get_instance', cert['id'])
assert cert['revoked'] is True, cert
root_ca = call('certificateauthority.get_instance', root_ca['id'])
assert len(root_ca['revoked_certs']) == 2, root_ca
assert len(intermediate_ca['revoked_certs']) == 2, intermediate_ca
check_set = {intermediate_ca['certificate'], cert['certificate']}
assert set(c['certificate'] for c in intermediate_ca['revoked_certs']) == check_set, intermediate_ca
assert set(c['certificate'] for c in root_ca['revoked_certs']) == check_set, root_ca
finally:
call('certificate.delete', cert['id'], job=True)
def test_created_certs_exist_on_filesystem():
with intermediate_certificate_authority('root_ca', 'intermediate_ca') as (root_ca, intermediate_ca):
with certificate_signing_request('csr_test') as csr:
cert = call('certificate.create', {
'name': 'cert_test',
'signedby': intermediate_ca['id'],
'create_type': 'CERTIFICATE_CREATE_INTERNAL',
**get_cert_params(),
}, job=True)
try:
assert get_cert_current_files() == get_cert_expected_files()
finally:
call('certificate.delete', cert['id'], job=True)
def test_deleted_certs_dont_exist_on_filesystem():
with intermediate_certificate_authority('root_ca2', 'intermediate_ca2') as (root_ca2, intermediate_ca2):
# no-op
pass
with certificate_signing_request('csr_test2') as csr2:
pass
assert get_cert_current_files() == get_cert_expected_files()
def get_cert_expected_files():
certs = call('certificate.query')
cas = call('certificateauthority.query')
expected_files = {'/etc/certificates/CA'}
for cert in certs + cas:
if cert['chain_list']:
expected_files.add(cert['certificate_path'])
if cert['privatekey']:
expected_files.add(cert['privatekey_path'])
if cert['cert_type_CSR']:
expected_files.add(cert['csr_path'])
if any(cert[k] for k in ('CA_type_existing', 'CA_type_internal', 'CA_type_intermediate')):
expected_files.add(cert['crl_path'])
return expected_files
def get_cert_current_files():
return {
f['path']
for p in ('/etc/certificates', '/etc/certificates/CA') for f in call('filesystem.listdir', p)
}
@pytest.mark.parametrize('life_time,should_work', [
(300, True),
(9999999, False),
])
def test_certificate_lifetime_validation(life_time, should_work):
cert_params = get_cert_params()
cert_params['lifetime'] = life_time
with root_certificate_authority('root-ca') as root_ca:
if should_work:
cert = None
try:
cert = call(
'certificate.create', {
'name': 'test-cert',
'create_type': 'CERTIFICATE_CREATE_INTERNAL',
'signedby': root_ca['id'],
**cert_params,
}, job=True
)
assert cert['parsed'] is True, cert
finally:
if cert:
call('certificate.delete', cert['id'], job=True)
else:
with pytest.raises(ValidationErrors):
call(
'certificate.create', {
'name': 'test-cert',
'signedby': root_ca['id'],
'create_type': 'CERTIFICATE_CREATE_INTERNAL',
**cert_params,
}, job=True
)
@pytest.mark.parametrize('certificate,private_key,should_work', [
(
textwrap.dedent('''\
-----BEGIN CERTIFICATE-----
MIIEDTCCAvWgAwIBAgIEAKWUWTANBgkqhkiG9w0BAQsFADBVMQswCQYDVQQGEwJV
UzEMMAoGA1UECAwDdXNhMRMwEQYDVQQHDApjYWxpZm9ybmlhMQswCQYDVQQKDAJs
bTEWMBQGCSqGSIb3DQEJARYHYUBiLmNvbTAeFw0yMzA0MDYxNjQyMTJaFw0yNDA1
MDcxNjQyMTJaME4xCzAJBgNVBAYTAlVTMQwwCgYDVQQIDAN1c2ExDDAKBgNVBAcM
A3VzYTELMAkGA1UECgwCbG0xFjAUBgkqhkiG9w0BCQEWB2FAYy5jb20wggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtvPEA2x3/jp0riSdgb7TqB9uAobzt
tYbW9E0+WLqf3sLJJ4F4Iq0AI1YYMtOOwcjmvC52eSaqxoGcY4G2J+RgQNR8b8lk
m38vRYQA2SkDCtEQFkLiCrkr5g20xh89gCLEr9c5x45p8Pl7q2LmE6wVIVjWqTSi
Yo4TMD8Nb5LN3vPeM7+fwV7FZDH7PJ4AT1/kTJjhkK0wiOGeTLEW5wiSYO8QMD0r
JHfzAp8UPFsVK8InZTjLS4VJgI0OlG2Von7Nv7Wtxsg5hi7dkLu2tawHE8DD97O5
zhVTZHzBiDF1mrjR3+6RWgn8iF6353UV9hbyPYz51UiCEYHBwFtqQaBlAgMBAAGj
geswgegwDgYDVR0RBAcwBYIDYWJjMB0GA1UdDgQWBBSRzlS66ts6rhuCN+4VK2x7
8E+n1zAMBgNVHRMBAf8EAjAAMIGABgNVHSMEeTB3gBR1fZ31S5XHrijsT/C9fzbB
aqrg5qFZpFcwVTELMAkGA1UEBhMCVVMxDDAKBgNVBAgMA3VzYTETMBEGA1UEBwwK
Y2FsaWZvcm5pYTELMAkGA1UECgwCbG0xFjAUBgkqhkiG9w0BCQEWB2FAYi5jb22C
BACllFgwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwIwDgYDVR0PAQH/BAQDAgOIMA0G
CSqGSIb3DQEBCwUAA4IBAQA7UwYNr6gspgRcCGwzl5RUAL/N3NXv3rcgTPF405s5
OXKDPAxWSulzt/jqAesYvI27koOsGj0sDsSRLRdmj4HG91Xantnv5rxGqdYHEDPo
j8oo1HQv8vqhDcKUJOKH5j5cWO+W75CpAHuMfgxKJ9WdxPSNpKZoOKIMd2hwd4ng
2+ulgfvVKcE4PM4YSrtW4qoAoz/+gyfwSoIAQJ0VOuEwL+QFJ8Ud1aJaJRkLD39P
uLEje++rBbfIX9VPCRS/c3gYAOHu66LYI3toTomY8U3YYiQk8bC3Rp9uAjmgI3br
4DHLwRTEUbOL8CdNcGb1qvO8xBSRzjMIZM8QJHSyYNcM
-----END CERTIFICATE-----
'''),
textwrap.dedent('''\
-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCtvPEA2x3/jp0r
iSdgb7TqB9uAobzttYbW9E0+WLqf3sLJJ4F4Iq0AI1YYMtOOwcjmvC52eSaqxoGc
Y4G2J+RgQNR8b8lkm38vRYQA2SkDCtEQFkLiCrkr5g20xh89gCLEr9c5x45p8Pl7
q2LmE6wVIVjWqTSiYo4TMD8Nb5LN3vPeM7+fwV7FZDH7PJ4AT1/kTJjhkK0wiOGe
TLEW5wiSYO8QMD0rJHfzAp8UPFsVK8InZTjLS4VJgI0OlG2Von7Nv7Wtxsg5hi7d
kLu2tawHE8DD97O5zhVTZHzBiDF1mrjR3+6RWgn8iF6353UV9hbyPYz51UiCEYHB
wFtqQaBlAgMBAAECggEAFNc827rtIspDPUUzFYTg4U/2+zurk6I6Xg+pMmjnXiUV
HZchFz2lngYfHkD+krnZNSBuvGR1CHhOdOmU1jp70TYFpzWrpWdnvs5qcsWZ/1Tt
Vi4tcLsTkloC2+QGPFTiFtD3EuXGxhuTecvJzcqfUluRMhLTDwWegFvBvIVdSVeZ
9XFDZF9O748tdt2PhYcL2L/xDz4sIz89ek4P1v4raB52rcleIduqMat29crVR3ex
VsZK3PLW6HCquUQvdvjLblfzjDS1pqcpIiSsYCrP0eEEKrrg44V8VjcPxXIg4GAE
ioDOpi9vO/3xyxYxXBtlD2o6c9kZUrp+xxx9jztdIQKBgQDo8witC33Z7Rd6dLm9
zgN/wZ2lWqE927fXZBExKjCXZ+A3N58One0TR2qI9S+BRVc2KOCWFGUjnHbx1PfE
xU1UNDY+ir9Lqk+rzhyEk4vst/IwhyovmAhL5fONqlfxB+l29cUh6JIYMtqaWYvj
AbmS5YhZRMa3kI/BtCTRJtPecQKBgQC+7f57XWt7HNe7FvrDTz5M8AmQ7y487NxZ
OcZ1+YKJ57PVY7G7Ye3xqRTd05L6h1P1eCO0gLDiSy5VOz47uFdNcD/9Ia+Ng2oq
P8TC36b86dz3ZDhBm4AB3shaD/JBjUQ0NwLosmrMaDF+lVu8NPA60eeQ70/RgbSA
KNrOUH1DNQKBgQDicOzsGZGat6fs925enNY16CWwSOsYUG7ix3kWy6Y0Z1tDEaRh
9w4vgWqD+6LUDG18TjwSZ3zxIvVUmurGsew7gA2Cuii+Cq4rmc2K6kpIL38TwTA2
15io/rzD5uRZfpFpe/rGvWbWcwigpY8fedvEea8S55IrejDj4JMxZIbrYQKBgQCG
Ke68+XRhWm8thIRJYhHBNptCQRAYt8hO2o5esCnOhgaUWC24IqR1P/7tsZKCgT26
K+XLHPMu0O2J7stYY7zVKZ+NXHJj2ohrj8vPtCE/b4ZaQQ5W69ITfl0DDFmLPp1C
o7Vjlpv9bun4rTN9GSYF7yHtcnyAF8iilhLLDzw2UQKBgQC4FzI6/P2HcUNzf+/m
AThk8+4V35gOSxn3uk48CXNStcCoLMEeXM69SGYq8GaGU/piaog9D8RvF4yMAnnL
wNpy8J/4ldluyidX61N0dMS+NL4l4TPjTvOY22KzjwfnBoqzg+93Mt//M4HfR/ka
3EWl5VmzbuEeytrcH3uHAUpkKg==
-----END PRIVATE KEY-----
'''),
True,
),
(
textwrap.dedent('''\
-----BEGIN CERTIFICATE-----
MIIEDTCCAvWgAwIBAgIEAKWUWTANBgkqhkiG9w0BAQsFADBVMQswCQYDVQQGEwJV
UzEMMAoGA1UECAwDdXNhMRMwEQYDVQQHDApjYWxpZm9ybmlhMQswCQYDVQQKDAJs
bTEWMBQGCSqGSIb3DQEJARYHYUBiLmNvbTAeFw0yMzA0MDYxNjQyMTJaFw0yNDA1
MDcxNjQyMTJaME4xCzAJBgNVBAYTAlVTMQwwCgYDVQQIDAN1c2ExDDAKBgNVBAcM
A3VzYTELMAkGA1UECgwCbG0xFjAUBgkqhkiG9w0BCQEWB2FAYy5jb20wggEiMA0G
CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCtvPEA2x3/jp0riSdgb7TqB9uAobzt
tYbW9E0+WLqf3sLJJ4F4Iq0AI1YYMtOOwcjmvC52eSaqxoGcY4G2J+RgQNR8b8lk
m38vRYQA2SkDCtEQFkLiCrkr5g20xh89gCLEr9c5x45p8Pl7q2LmE6wVIVjWqTSi
Yo4TMD8Nb5LN3vPeM7+fwV7FZDH7PJ4AT1/kTJjhkK0wiOGeTLEW5wiSYO8QMD0r
JHfzAp8UPFsVK8InZTjLS4VJgI0OlG2Von7Nv7Wtxsg5hi7dkLu2tawHE8DD97O5
zhVTZHzBiDF1mrjR3+6RWgn8iF6353UV9hbyPYz51UiCEYHBwFtqQaBlAgMBAAGj
geswgegwDgYDVR0RBAcwBYIDYWJjMB0GA1UdDgQWBBSRzlS66ts6rhuCN+4VK2x7
8E+n1zAMBgNVHRMBAf8EAjAAMIGABgNVHSMEeTB3gBR1fZ31S5XHrijsT/C9fzbB
aqrg5qFZpFcwVTELMAkGA1UEBhMCVVMxDDAKBgNVBAgMA3VzYTETMBEGA1UEBwwK
Y2FsaWZvcm5pYTELMAkGA1UECgwCbG0xFjAUBgkqhkiG9w0BCQEWB2FAYi5jb22C
BACllFgwFgYDVR0lAQH/BAwwCgYIKwYBBQUHAwIwDgYDVR0PAQH/BAQDAgOIMA0G
CSqGSIb3DQEBCwUAA4IBAQA7UwYNr6gspgRcCGwzl5RUAL/N3NXv3rcgTPF405s5
OXKDPAxWSulzt/jqAesYvI27koOsGj0sDsSRLRdmj4HG91Xantnv5rxGqdYHEDPo
j8oo1HQv8vqhDcKUJOKH5j5cWO+W75CpAHuMfgxKJ9WdxPSNpKZoOKIMd2hwd4ng
2+ulgfvVKcE4PM4YSrtW4qoAoz/+gyfwSoIAQJ0VOuEwL+QFJ8Ud1aJaJRkLD39P
uLEje++rBbfIX9VPCRS/c3gYAOHu66LYI3toTomY8U3YYiQk8bC3Rp9uAjmgI3br
4DHLwRTEUbOL8CdNcGb1qvO8xBSRzjMIZM8QJHSyYNcM
-----END CERTIFICATE-----
'''),
textwrap.dedent('''\
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDVMPccUqq6jd8h
h0ybrwRkvK+pvOJze00IK7F6A8RRyCwDL2Yc0GpWR5ecY+jBiZ1n+TfKfaybdKR0
0hhFFuU74JTsUk298hI1GVBNvwbimgraQciWjg0wDjHAN7AFZL8Jb/Tn7/DZlmn+
TgqdPaFIeD4XnLX6zwrc4VemKYDDcdr5JyDVCt3ZtqTEbbtxQ4WvZbtCxlzlkyJu
xwdmGyCvjkQri55+FaejvnPCUzJSOK28jShBuZCIS3lR7HCcAS4cc05TTrWSZr+i
brLISVEz1XASc0pKz8QGMuz5Hk5uNRLl4JGmWZrSV9lqtFYP9hatpLi5mnhWpgYi
Q0IXvNUXAgMBAAECggEAdbgf+0e6dmC4gO8Q4jZ2GpoF9ZgTAulm08gsq89ArFf3
1ZpqrCZ5UUMe+IBCmfu/KxZ2NB3JHd3+oXMRa7UEx1dvZD7eJrBwVVmw+f0tdBrT
O0lv1ZKCvbJYzmbxj0jeI/vqI9heCggAZyf4vHK3iCi9QJSL9/4zZVwY5eus6j4G
RCMXW8ZqiKX3GLtCjPmZilYQHNDbsfAbqy75AsG81fgaKkYkJS29rte9R34BajZs
OFm+y6nIe6zsf0vhn/yPVN4Yhuu/WhkvqouR2NhSF7ulXckuR/ef55GPpbRcpSOj
VUkwJL3wsHPozvmcks/TnZbqj0u7XBGjZ2VK8sF+gQKBgQDsJGMeeaua5pOITVHk
reHaxy4tLs1+98++L9SffBbsQcCu4OdgMBizCXuUw9bHlMx19B/B56cJst239li3
dHfC/mF4/8em5XOx97FyC0rF02qYCPXViTrTSovSEWHuM/ChmhaRlZdp5F4EBMp7
ELdf4OBCHGz47UCLQF75/FPtJwKBgQDnHn9HuFepY+yV1sNcPKj1GfciaseKzTk1
Iw5VVtqyS2p8vdXNUiJmaF0245S3phRBL6PDhdfd3SwMmNYvhTYsqBc6ZRHO4b9J
SjmHct63286NuEn0piYaa3MZ8sV/xI0a5leAdkzyqPTCcn0HlvDL0HTV34umdmfj
kqC4jsWukQKBgC48cavl5tPNkdV+TiqYYUCU/1WZdGMH4oU6mEch5NsdhLy5DJSo
1i04DhpyvfsWB3KQ+ibdVLdxbjg24+gHxetII42th0oGY0DVXskVrO5PFu/t0TSe
SgZU8kuPW71oLhV2NjULNTpmnIHs7jhqbX04arCHIE8dJSYe1HneDhDBAoGBALTk
4txgxYQYaNFykd/8voVwuETg7KOQM0mK0aor2+qXKpbOAqy8r54V63eNsxX20H2g
6v2bIbVOai7F5Ua2bguP2PZkqwaRHKYhiVuhpf6j9UxpRMFO1h3xodpacQiq74Jx
bWVnspxvb3tOHtw04O21j+ziFizJGlE9r7wkS0dxAoGAeq/Ecb+nJp/Ce4h5US1O
4rruiLLYMkcFGmhSMcQ+lVbGOn4eSpqrGWn888Db2oiu7mv+u0TK9ViXwHkfp4FP
Hnm0S8e25py1Lj+bk1tH0ku1I8qcAtihYBtSwPGj+66Qyr8KOlxZP2Scvcqu+zBc
cyhsrrlRc3Gky9L5gtdxdeo=
-----END PRIVATE KEY-----
'''),
False,
),
(
textwrap.dedent('''\
-----BEGIN CERTIFICATE-----
ntnv5rxGqdYHEDPo
j8oo1HQv8vqhDcKUJOKH5j5cWO+W75CpAHuMfgxKJ9WdxPSNpKZoOKIMd2hwd4ng
2+ulgfvVKcE4PM4YSrtW4qoAoz/+gyfwSoIAQJ0VOuEwL+QFJ8Ud1aJaJRkLD39P
uLEje++rBbfIX9VPCRS/c3gYAOHu66LYI3toTomY8U3YYiQk8bC3Rp9uAjmgI3br
4DHLwRTEUbOL8CdNcGb1qvO8xBSRzjMIZM8QJHSyYNcM
-----END CERTIFICATE-----
'''),
textwrap.dedent('''\
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDVMPccUqq6jd8h
h0ybrwRkvK+pvOJze00IK7F6A8RRyCwDL2Yc0GpWR5ecY+jBiZ1n+TfKfaybdKR0
0hhFFuU74JTsUk298hI1GVBNvwbimgraQciWjg0wDjHAN7AFZL8Jb/Tn7/DZlmn+
TgqdPaFIeD4XnLX6zwrc4VemKYDDcdr5JyDVCt3ZtqTEbbtxQ4WvZbtCxlzlkyJu
xwdmGyCvjkQri55+FaejvnPCUzJSOK28jShBuZCIS3lR7HCcAS4cc05TTrWSZr+i
brLISVEz1XASc0pKz8QGMuz5Hk5uNRLl4JGmWZrSV9lqtFYP9hatpLi5mnhWpgYi
Q0IXvNUXAgMBAAECggEAdbgf+0e6dmC4gO8Q4jZ2GpoF9ZgTAulm08gsq89ArFf3
1ZpqrCZ5UUMe+IBCmfu/KxZ2NB3JHd3+oXMRa7UEx1dvZD7eJrBwVVmw+f0tdBrT
O0lv1ZKCvbJYzmbxj0jeI/vqI9heCggAZyf4vHK3iCi9QJSL9/4zZVwY5eus6j4G
RCMXW8ZqiKX3GLtCjPmZilYQHNDbsfAbqy75AsG81fgaKkYkJS29rte9R34BajZs
OFm+y6nIe6zsf0vhn/yPVN4Yhuu/WhkvqouR2NhSF7ulXckuR/ef55GPpbRcpSOj
VUkwJL3wsHPozvmcks/TnZbqj0u7XBGjZ2VK8sF+gQKBgQDsJGMeeaua5pOITVHk
reHaxy4tLs1+98++L9SffBbsQcCu4OdgMBizCXuUw9bHlMx19B/B56cJst239li3
dHfC/mF4/8em5XOx97FyC0rF02qYCPXViTrTSovSEWHuM/ChmhaRlZdp5F4EBMp7
ELdf4OBCHGz47UCLQF75/FPtJwKBgQDnHn9HuFepY+yV1sNcPKj1GfciaseKzTk1
Iw5VVtqyS2p8vdXNUiJmaF0245S3phRBL6PDhdfd3SwMmNYvhTYsqBc6ZRHO4b9J
SjmHct63286NuEn0piYaa3MZ8sV/xI0a5leAdkzyqPTCcn0HlvDL0HTV34umdmfj
kqC4jsWukQKBgC48cavl5tPNkdV+TiqYYUCU/1WZdGMH4oU6mEch5NsdhLy5DJSo
1i04DhpyvfsWB3KQ+ibdVLdxbjg24+gHxetII42th0oGY0DVXskVrO5PFu/t0TSe
SgZU8kuPW71oLhV2NjULNTpmnIHs7jhqbX04arCHIE8dJSYe1HneDhDBAoGBALTk
4txgxYQYaNFykd/8voVwuETg7KOQM0mK0aor2+qXKpbOAqy8r54V63eNsxX20H2g
6v2bIbVOai7F5Ua2bguP2PZkqwaRHKYhiVuhpf6j9UxpRMFO1h3xodpacQiq74Jx
bWVnspxvb3tOHtw04O21j+ziFizJGlE9r7wkS0dxAoGAeq/Ecb+nJp/Ce4h5US1O
4rruiLLYMkcFGmhSMcQ+lVbGOn4eSpqrGWn888Db2oiu7mv+u0TK9ViXwHkfp4FP
Hnm0S8e25py1Lj+bk1tH0ku1I8qcAtihYBtSwPGj+66Qyr8KOlxZP2Scvcqu+zBc
cyhsrrlRc3Gky9L5gtdxdeo=
-----END PRIVATE KEY-----
'''),
False,
)
], ids=['valid_cert', 'invalid_cert', 'invalid_cert'])
def test_importing_certificate_validation(certificate, private_key, should_work):
cert_params = {'certificate': certificate, 'privatekey': private_key}
if should_work:
cert = None
if should_work:
try:
cert = call(
'certificate.create', {
'name': 'test-cert',
'create_type': 'CERTIFICATE_CREATE_IMPORTED',
**cert_params,
}, job=True
)
assert cert['parsed'] is True, cert
finally:
if cert:
call('certificate.delete', cert['id'], job=True)
else:
with pytest.raises(ValidationErrors):
call(
'certificate.create', {
'name': 'test-cert',
'create_type': 'CERTIFICATE_CREATE_IMPORTED',
**cert_params,
}, job=True
)
| 29,787 | Python | .py | 582 | 40.353952 | 112 | 0.665282 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,324 | test_device_get_disk_names.py | truenas_middleware/tests/api2/test_device_get_disk_names.py | from middlewared.test.integration.utils import call
def test_device_get_disk_names():
assert set(list(call('device.get_disks', False, True))) == set(call('device.get_disk_names'))
| 186 | Python | .py | 3 | 59 | 97 | 0.745856 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,325 | test_acltype.py | truenas_middleware/tests/api2/test_acltype.py | import pytest
from auto_config import pool_name
from middlewared.test.integration.utils import call
from middlewared.test.integration.assets.pool import dataset
def query_filters(ds_name):
return [['id', '=', ds_name]], {'get': True, 'extra': {'retrieve_children': False}}
@pytest.fixture(scope='module')
def temp_ds():
with dataset('test1') as ds:
yield ds
def test_default_acltype_on_zpool():
assert 'POSIXACL' in call('filesystem.statfs', f'/mnt/{pool_name}')['flags']
def test_acltype_inheritance(temp_ds):
assert call('zfs.dataset.query', *query_filters(temp_ds))['properties']['acltype']['rawvalue'] == 'posix'
@pytest.mark.parametrize(
'change,expected', [
(
{'acltype': 'NFSV4', 'aclmode': 'PASSTHROUGH'},
(('acltype', 'value', 'nfsv4'), ('aclmode', 'value', 'passthrough'), ('aclinherit', 'value', 'passthrough'))
),
(
{'acltype': 'POSIX', 'aclmode': 'DISCARD'},
(('acltype', 'value', 'posix'), ('aclmode', 'value', 'discard'), ('aclinherit', 'value', 'discard'))
),
],
ids=['NFSV4_PASSTHROUGH', 'POSIX_DISCARD']
)
def test_change_acltype_and_aclmode_to_(temp_ds, change, expected):
call('pool.dataset.update', temp_ds, change)
props = call('zfs.dataset.query', *query_filters(temp_ds))['properties']
for tkey, skey, value in expected:
assert props[tkey][skey] == value, props[tkey][skey]
| 1,445 | Python | .py | 32 | 39.5625 | 120 | 0.6398 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,326 | test_345_acl_nfs4.py | truenas_middleware/tests/api2/test_345_acl_nfs4.py | import secrets
import string
import os
import pytest
from pytest_dependency import depends
from auto_config import pool_name
from functions import SSH_TEST
from middlewared.service_exception import ValidationErrors
from middlewared.test.integration.assets.account import user as create_user
from middlewared.test.integration.assets.pool import dataset as make_dataset
from middlewared.test.integration.utils import call, ssh
shell = '/usr/bin/bash'
group = 'nogroup'
ACLTEST_DATASET_NAME = 'acltest'
ACLTEST_DATASET = f'{pool_name}/{ACLTEST_DATASET_NAME}'
dataset_url = ACLTEST_DATASET.replace('/', '%2F')
ACLTEST_SUBDATASET = f'{pool_name}/acltest/sub1'
getfaclcmd = "nfs4xdr_getfacl"
setfaclcmd = "nfs4xdr_setfacl"
group0 = "root"
ACL_USER = 'acluser'
ACL_PWD = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(10))
base_permset = {
"READ_DATA": False,
"WRITE_DATA": False,
"APPEND_DATA": False,
"READ_NAMED_ATTRS": False,
"WRITE_NAMED_ATTRS": False,
"EXECUTE": False,
"DELETE_CHILD": False,
"READ_ATTRIBUTES": False,
"WRITE_ATTRIBUTES": False,
"DELETE": False,
"READ_ACL": False,
"WRITE_ACL": False,
"WRITE_OWNER": False,
"SYNCHRONIZE": True
}
base_flagset = {
"FILE_INHERIT": False,
"DIRECTORY_INHERIT": False,
"NO_PROPAGATE_INHERIT": False,
"INHERIT_ONLY": False,
"INHERITED": False
}
BASIC_PERMS = ["READ", "TRAVERSE", "MODIFY", "FULL_CONTROL"]
BASIC_FLAGS = ["INHERIT", "NOINHERIT"]
TEST_FLAGS = [
'DIRECTORY_INHERIT',
'FILE_INHERIT',
'INHERIT_ONLY',
'NO_PROPAGATE_INHERIT'
]
INHERIT_FLAGS_BASIC = {
"FILE_INHERIT": True,
"DIRECTORY_INHERIT": True,
"NO_PROPAGATE_INHERIT": False,
"INHERIT_ONLY": False,
"INHERITED": False
}
INHERIT_FLAGS_ADVANCED = {
"FILE_INHERIT": True,
"DIRECTORY_INHERIT": True,
"NO_PROPAGATE_INHERIT": True,
"INHERIT_ONLY": True,
"INHERITED": False
}
default_acl = [
{
"tag": "owner@",
"id": None,
"type": "ALLOW",
"perms": {"BASIC": "FULL_CONTROL"},
"flags": {"BASIC": "INHERIT"}
},
{
"tag": "group@",
"id": None,
"type": "ALLOW",
"perms": {"BASIC": "FULL_CONTROL"},
"flags": {"BASIC": "INHERIT"}
}
]
function_testing_acl_deny = [
{
"tag": "owner@",
"id": None,
"type": "ALLOW",
"perms": {"BASIC": "FULL_CONTROL"},
"flags": {"BASIC": "INHERIT"}
},
{
"tag": "group@",
"id": None,
"type": "ALLOW",
"perms": {"BASIC": "FULL_CONTROL"},
"flags": {"BASIC": "INHERIT"}
},
{
"tag": "everyone@",
"id": None,
"type": "ALLOW",
"perms": {"BASIC": "FULL_CONTROL"},
"flags": {"BASIC": "INHERIT"}
},
]
function_testing_acl_allow = [
{
"tag": "owner@",
"id": None,
"type": "ALLOW",
"perms": {"BASIC": "FULL_CONTROL"},
"flags": {"BASIC": "INHERIT"}
},
{
"tag": "group@",
"id": None,
"type": "ALLOW",
"perms": {"BASIC": "FULL_CONTROL"},
"flags": {"BASIC": "INHERIT"}
}
]
# base64-encoded samba DOSATTRIB xattr
DOSATTRIB_XATTR = "CTB4MTAAAAMAAwAAABEAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABimX3sSqfTAQAAAAAAAAAACg=="
IMPLEMENTED_DENY = [
"WRITE_ATTRIBUTES",
"DELETE",
"DELETE_CHILD",
"FULL_DELETE",
"EXECUTE",
"READ_DATA",
"WRITE_DATA",
"READ_ACL",
"WRITE_ACL",
"WRITE_OWNER",
]
IMPLEMENTED_ALLOW = [
"READ_DATA",
"WRITE_DATA",
"DELETE",
"DELETE_CHILD",
"EXECUTE",
"WRITE_OWNER",
"READ_ACL",
"WRITE_ACL",
]
TEST_INFO = {}
@pytest.fixture(scope='module')
def initialize_for_acl_tests(request):
with make_dataset(ACLTEST_DATASET_NAME, data={'acltype': 'NFSV4', 'aclmode': 'RESTRICTED'}) as ds:
with create_user({
'username': ACL_USER,
'full_name': ACL_USER,
'group_create': True,
'ssh_password_enabled': True,
'password': ACL_PWD
}) as u:
TEST_INFO.update({
'dataset': ds,
'dataset_path': os.path.join('/mnt', ds),
'user': u
})
yield request
@pytest.mark.dependency(name='HAS_NFS4_ACLS')
def test_02_create_dataset(initialize_for_acl_tests):
acl = call('filesystem.getacl', TEST_INFO['dataset_path'])
assert acl['acltype'] == 'NFS4'
def test_04_basic_set_acl_for_dataset(request):
depends(request, ["HAS_NFS4_ACLS"])
call('filesystem.setacl', {
'path': TEST_INFO['dataset_path'],
'uid': 65534,
'gid': 65534,
'dacl': default_acl
}, job=True)
acl_result = call('filesystem.getacl', TEST_INFO['dataset_path'], True)
for key in ['tag', 'type', 'perms', 'flags']:
assert acl_result['acl'][0][key] == default_acl[0][key], str(acl_result)
assert acl_result['acl'][1][key] == default_acl[1][key], str(acl_result)
assert acl_result['uid'] == 65534, str(acl_result)
"""
At this point very basic functionality of API endpoint is verified.
Proceed to more rigorous testing of basic and advanced permissions.
These tests will only manipulate the first entry in the default ACL (owner@).
Each test will iterate through all available options for that particular
variation (BASIC/ADVANCED permissions, BASIC/ADVANCED flags).
"""
@pytest.mark.parametrize('permset', BASIC_PERMS)
def test_08_set_basic_permsets(request, permset):
depends(request, ["HAS_NFS4_ACLS"])
default_acl[0]['perms']['BASIC'] = permset
call('filesystem.setacl', {'path': TEST_INFO['dataset_path'], 'dacl': default_acl}, job=True)
acl_result = call('filesystem.getacl', TEST_INFO['dataset_path'], True)
requested_perms = default_acl[0]['perms']
received_perms = acl_result['acl'][0]['perms']
assert requested_perms == received_perms, str(acl_result)
@pytest.mark.parametrize('flagset', BASIC_FLAGS)
def test_09_set_basic_flagsets(request, flagset):
depends(request, ["HAS_NFS4_ACLS"])
default_acl[0]['flags']['BASIC'] = flagset
call('filesystem.setacl', {'path': TEST_INFO['dataset_path'], 'dacl': default_acl}, job=True)
acl_result = call('filesystem.getacl', TEST_INFO['dataset_path'], True)
requested_flags = default_acl[0]['flags']
received_flags = acl_result['acl'][0]['flags']
assert requested_flags == received_flags, str(acl_result)
@pytest.mark.parametrize('perm', base_permset.keys())
def test_10_set_advanced_permset(request, perm):
depends(request, ["HAS_NFS4_ACLS"])
for key in ['perms', 'flags']:
if default_acl[0][key].get('BASIC'):
default_acl[0][key].pop('BASIC')
default_acl[0]['flags'] = base_flagset.copy()
default_acl[0]['perms'] = base_permset.copy()
default_acl[0]['perms'][perm] = True
call('filesystem.setacl', {'path': TEST_INFO['dataset_path'], 'dacl': default_acl}, job=True)
acl_result = call('filesystem.getacl', TEST_INFO['dataset_path'], True)
requested_perms = default_acl[0]['perms']
received_perms = acl_result['acl'][0]['perms']
assert requested_perms == received_perms, str(acl_result)
@pytest.mark.parametrize('flag', TEST_FLAGS)
def test_11_set_advanced_flagset(request, flag):
depends(request, ["HAS_NFS4_ACLS"])
default_acl[0]['flags'] = base_flagset.copy()
default_acl[0]['flags'][flag] = True
if flag in ['INHERIT_ONLY', 'NO_PROPAGATE_INHERIT']:
default_acl[0]['flags']['DIRECTORY_INHERIT'] = True
call('filesystem.setacl', {'path': TEST_INFO['dataset_path'], 'dacl': default_acl}, job=True)
acl_result = call('filesystem.getacl', TEST_INFO['dataset_path'], True)
requested_flags = default_acl[0]['flags']
received_flags = acl_result['acl'][0]['flags']
assert requested_flags == received_flags, str(acl_result)
"""
This next series of tests verifies that ACLs are being inherited correctly.
We first create a child dataset to verify that ACLs do not change unless
'traverse' is set.
"""
def test_12_prepare_recursive_tests(request):
depends(request, ["HAS_NFS4_ACLS"], scope="session")
call('pool.dataset.create', {'name': ACLTEST_SUBDATASET, 'acltype': 'NFSV4'})
ssh(';'.join([
f'mkdir -p /mnt/{ACLTEST_DATASET}/dir1/dir2',
f'touch /mnt/{ACLTEST_DATASET}/dir1/testfile',
f'touch /mnt/{ACLTEST_DATASET}/dir1/dir2/testfile'
]))
def test_13_recursive_no_traverse(request):
depends(request, ["HAS_NFS4_ACLS"])
default_acl[1]['perms'].pop('BASIC')
default_acl[1]['flags'].pop('BASIC')
default_acl[0]['flags'] = INHERIT_FLAGS_BASIC.copy()
default_acl[1]['flags'] = INHERIT_FLAGS_ADVANCED.copy()
expected_flags_0 = INHERIT_FLAGS_BASIC.copy()
expected_flags_0['INHERITED'] = True
expected_flags_1 = base_flagset.copy()
expected_flags_1['INHERITED'] = True
# get acl of child dataset. This should not change in this test
acl_result = call('filesystem.getacl', f'/mnt/{ACLTEST_SUBDATASET}', True)
init_acl = acl_result['acl'][0]['perms']
call('filesystem.setacl', {
'path': TEST_INFO['dataset_path'],
'dacl': default_acl,
'uid': 65534,
'options': {'recursive': True}
}, job=True)
# Verify that it hasn't changed
acl_result = call('filesystem.getacl', f'/mnt/{ACLTEST_SUBDATASET}', True)
fin_acl = acl_result['acl'][0]['perms']
assert init_acl == fin_acl, str(acl_result)
# check on dir 1. Entry 1 should have INHERIT flag added, and
# INHERIT_ONLY should be set to False at this depth.
acl_result = call('filesystem.getacl', f'/mnt/{ACLTEST_DATASET}/dir1', False)
theacl = acl_result['acl']
assert theacl[0]['flags'] == expected_flags_0, acl_result
assert theacl[1]['flags'] == expected_flags_1, acl_result
# Verify that user was changed on subdirectory
assert acl_result['uid'] == 65534, acl_result
# check on dir 2 - the no propogate inherit flag should have taken
# effect and ACL length should be 1
acl_result = call('filesystem.getacl', f'/mnt/{ACLTEST_DATASET}/dir1/dir2', False)
theacl = acl_result['acl']
assert theacl[0]['flags'] == expected_flags_0, acl_result
assert len(theacl) == 1, acl_result
# Verify that user was changed two deep
assert acl_result['uid'] == 65534, acl_result
def test_14_recursive_with_traverse(request):
depends(request, ["HAS_NFS4_ACLS"])
expected_flags_0 = INHERIT_FLAGS_BASIC.copy()
expected_flags_0['INHERITED'] = True
expected_flags_1 = base_flagset.copy()
expected_flags_1['INHERITED'] = True
call('filesystem.setacl', {
'path': TEST_INFO['dataset_path'],
'dacl': default_acl,
'uid': 65534,
'options': {'recursive': True, 'traverse': True}
}, job=True)
acl_result = call('filesystem.getacl', f'/mnt/{ACLTEST_SUBDATASET}', True)
theacl = acl_result['acl']
assert theacl[0]['flags'] == expected_flags_0, acl_result
assert theacl[1]['flags'] == expected_flags_1, acl_result
# Verify that user was changed
assert acl_result['uid'] == 65534, acl_result
def test_15_strip_acl_from_dataset(request):
depends(request, ["HAS_NFS4_ACLS"])
call('filesystem.setperm', {
'path': TEST_INFO['dataset_path'],
'mode': '777',
'uid': 65534,
'options': {'stripacl': True, 'recursive': True}
}, job=True)
assert call('filesystem.stat', f'/mnt/{ACLTEST_SUBDATASET}')['acl'] is True
st = call('filesystem.stat', f'/mnt/{ACLTEST_DATASET}')
assert st['acl'] is False, str(st)
assert oct(st['mode']) == '0o40777', str(st)
st = call('filesystem.stat', f'/mnt/{ACLTEST_DATASET}/dir1')
assert st['acl'] is False, str(st)
assert oct(st['mode']) == '0o40777', str(st)
st = call('filesystem.stat', f'/mnt/{ACLTEST_DATASET}/dir1/testfile')
assert st['acl'] is False, str(st)
assert oct(st['mode']) == '0o100777', str(st)
def test_20_delete_child_dataset(request):
depends(request, ["HAS_NFS4_ACLS"])
call('pool.dataset.delete', ACLTEST_SUBDATASET)
@pytest.mark.dependency(name="HAS_TESTFILE")
def test_22_prep_testfile(request):
depends(request, ["HAS_NFS4_ACLS"], scope="session")
ssh(f'echo -n "CAT" >> /mnt/{ACLTEST_DATASET}/acltest.txt')
"""
The following tests verify that DENY ACEs are functioning correctly.
Deny ace will be prepended to base ACL that grants FULL_CONTROL.
#define VREAD_NAMED_ATTRS 000000200000 /* not used */
#define VWRITE_NAMED_ATTRS 000000400000 /* not used */
#define VDELETE_CHILD 000001000000
#define VREAD_ATTRIBUTES 000002000000 /* permission to stat(2) */
#define VWRITE_ATTRIBUTES 000004000000 /* change {m,c,a}time */
#define VDELETE 000010000000
#define VREAD_ACL 000020000000 /* read ACL and file mode */
#define VWRITE_ACL 000040000000 /* change ACL and/or file mode */
#define VWRITE_OWNER 000100000000 /* change file owner */
#define VSYNCHRONIZE 000200000000 /* not used */
Some tests must be skipped due to lack of implementation in VFS.
"""
@pytest.mark.parametrize('perm', IMPLEMENTED_DENY)
def test_23_test_acl_function_deny(perm, request):
"""
Iterate through available permissions and prepend
deny ACE denying that particular permission to the
acltest user, then attempt to perform an action that
should result in failure.
"""
depends(request, ["HAS_NFS4_ACLS", "HAS_TESTFILE"], scope="session")
if perm == "FULL_DELETE":
to_deny = {"DELETE_CHILD": True, "DELETE": True}
else:
to_deny = {perm: True}
payload_acl = [{
"tag": "USER",
"id": TEST_INFO['user']['uid'],
"type": "DENY",
"perms": to_deny,
"flags": {"BASIC": "INHERIT"}
}]
payload_acl.extend(function_testing_acl_deny)
call('filesystem.setacl', {
'path': TEST_INFO['dataset_path'],
'dacl': payload_acl,
'gid': 0, 'uid': 0,
'options': {'recursive': True},
}, job=True)
if perm == "EXECUTE":
cmd = f'cd /mnt/{ACLTEST_DATASET}'
elif perm == "READ_ATTRIBUTES":
cmd = f'stat /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm in ["DELETE", "DELETE_CHILD", "FULL_DELETE"]:
cmd = f'rm -f /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "READ_DATA":
cmd = f'cat /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "WRITE_DATA":
cmd = f'echo -n "CAT" >> /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "WRITE_ATTRIBUTES":
cmd = f'touch -a -m -t 201512180130.09 /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "READ_ACL":
cmd = f'{getfaclcmd} /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "WRITE_ACL":
cmd = f'{setfaclcmd} -b /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "WRITE_OWNER":
cmd = f'chown {ACL_USER} /mnt/{ACLTEST_DATASET}/acltest.txt'
else:
# This should never happen.
cmd = "touch /var/empty/ERROR"
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
"""
Per RFC5661 Section 6.2.1.3.2, deletion is permitted if either
DELETE_CHILD is permitted on parent, or DELETE is permitted on
file. This means that it should succeed when tested in isolation,
but fail when combined.
Unfortunately, this is implemented differenting in FreeBSD vs Linux.
Former follows above recommendation, latter does not in that denial
of DELETE on file takes precedence over allow of DELETE_CHILD.
"""
errstr = f'cmd: {cmd}, res: {results["output"]}, to_deny {to_deny}'
expected_delete = ["DELETE_CHILD"]
if perm in expected_delete:
assert results['result'] is True, errstr
# unfortunately, we now need to recreate our testfile.
ssh(f'echo -n "CAT" >> /mnt/{ACLTEST_DATASET}/acltest.txt')
elif perm == "READ_ATTRIBUTES":
assert results['result'] is True, errstr
else:
assert results['result'] is False, errstr
@pytest.mark.parametrize('perm', IMPLEMENTED_ALLOW)
def test_24_test_acl_function_allow(perm, request):
"""
Iterate through available permissions and prepend
allow ACE permitting that particular permission to the
acltest user, then attempt to perform an action that
should result in success.
"""
depends(request, ["HAS_NFS4_ACLS", "HAS_TESTFILE"], scope="session")
"""
Some extra permissions bits must be set for these tests
EXECUTE so that we can traverse to the path in question
and READ_ATTRIBUTES because most of the utilites we use
for testing have to stat(2) the files.
"""
to_allow = {perm: True}
if perm != "EXECUTE":
to_allow["EXECUTE"] = True
if perm != "READ_ATTRIBUTES":
to_allow["READ_ATTRIBUTES"] = True
if perm == "WRITE_ACL":
to_allow["READ_ACL"] = True
payload_acl = [{
"tag": "USER",
"id": TEST_INFO['user']['uid'],
"type": "ALLOW",
"perms": to_allow,
"flags": {"BASIC": "INHERIT"}
}]
payload_acl.extend(function_testing_acl_allow)
call('filesystem.setacl', {
'path': TEST_INFO['dataset_path'],
'dacl': payload_acl,
'gid': 65534, 'uid': 0,
'options': {'recursive': True},
}, job=True)
if perm == "EXECUTE":
cmd = f'cd /mnt/{ACLTEST_DATASET}'
elif perm == "READ_ATTRIBUTES":
cmd = f'stat /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm in ["DELETE", "DELETE_CHILD", "FULL_DELETE"]:
cmd = f'rm /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "READ_DATA":
cmd = f'cat /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "WRITE_DATA":
cmd = f'echo -n "CAT" >> /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "WRITE_ATTRIBUTES":
cmd = f'touch -a -m -t 201512180130.09 /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "READ_ACL":
cmd = f'{getfaclcmd} /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "WRITE_ACL":
cmd = f'{setfaclcmd} -x 0 /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "WRITE_OWNER":
cmd = f'chown {ACL_USER} /mnt/{ACLTEST_DATASET}/acltest.txt'
else:
# This should never happen.
cmd = "touch /var/empty/ERROR"
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {to_allow}'
assert results['result'] is True, errstr
if perm in ["DELETE", "DELETE_CHILD"]:
# unfortunately, we now need to recreate our testfile.
ssh(f'echo -n "CAT" >> /mnt/{ACLTEST_DATASET}/acltest.txt')
@pytest.mark.parametrize('perm', IMPLEMENTED_ALLOW)
def test_25_test_acl_function_omit(perm, request):
"""
Iterate through available permissions and add permissions
required for an explicit ALLOW of that ACE from the previous
test to succeed. This sets the stage to have success hinge
on presence of the particular permissions bit. Then we omit
it. This should result in a failure.
"""
depends(request, ["HAS_NFS4_ACLS", "HAS_TESTFILE"], scope="session")
"""
Some extra permissions bits must be set for these tests
EXECUTE so that we can traverse to the path in question
and READ_ATTRIBUTES because most of the utilites we use
for testing have to stat(2) the files.
"""
to_allow = {}
if perm != "EXECUTE":
to_allow["EXECUTE"] = True
if perm != "READ_ATTRIBUTES":
to_allow["READ_ATTRIBUTES"] = True
if perm == "WRITE_ACL":
to_allow["READ_ACL"] = True
payload_acl = [{
"tag": "USER",
"id": TEST_INFO['user']['uid'],
"type": "ALLOW",
"perms": to_allow,
"flags": {"BASIC": "INHERIT"}
}]
payload_acl.extend(function_testing_acl_allow)
call('filesystem.setacl', {
'path': TEST_INFO['dataset_path'],
'dacl': payload_acl,
'gid': 65534, 'uid': 0,
'options': {'recursive': True},
}, job=True)
if perm == "EXECUTE":
cmd = f'cd /mnt/{ACLTEST_DATASET}'
elif perm == "READ_ATTRIBUTES":
cmd = f'stat /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm in ["DELETE", "DELETE_CHILD", "FULL_DELETE"]:
cmd = f'rm /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "READ_DATA":
cmd = f'cat /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "WRITE_DATA":
cmd = f'echo -n "CAT" >> /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "WRITE_ATTRIBUTES":
cmd = f'touch -a -m -t 201512180130.09 /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "READ_ACL":
cmd = f'{getfaclcmd} /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "WRITE_ACL":
cmd = f'{setfaclcmd} -x 0 /mnt/{ACLTEST_DATASET}/acltest.txt'
elif perm == "WRITE_OWNER":
cmd = f'chown {ACL_USER} /mnt/{ACLTEST_DATASET}/acltest.txt'
else:
# This should never happen.
cmd = "touch /var/empty/ERROR"
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {to_allow}'
assert results['result'] is False, errstr
@pytest.mark.parametrize('perm', IMPLEMENTED_ALLOW)
def test_25_test_acl_function_allow_restrict(perm, request):
"""
Iterate through implemented allow permissions and verify that
they grant no more permissions than intended. Some bits cannot
be tested in isolation effectively using built in utilities.
"""
depends(request, ["HAS_NFS4_ACLS", "HAS_TESTFILE"], scope="session")
"""
Some extra permissions bits must be set for these tests
EXECUTE so that we can traverse to the path in question
and READ_ATTRIBUTES because most of the utilites we use
for testing have to stat(2) the files.
"""
to_allow = {}
tests_to_skip = []
tests_to_skip.append(perm)
if perm != "EXECUTE":
to_allow["EXECUTE"] = True
tests_to_skip.append("EXECUTE")
if perm != "READ_ATTRIBUTES":
to_allow["READ_ATTRIBUTES"] = True
tests_to_skip.append("READ_ATTRIBUTES")
if perm == "DELETE_CHILD":
tests_to_skip.append("DELETE")
payload_acl = [{
"tag": "USER",
"id": TEST_INFO['user']['uid'],
"type": "ALLOW",
"perms": to_allow,
"flags": {"BASIC": "INHERIT"}
}]
payload_acl.extend(function_testing_acl_allow)
call('filesystem.setacl', {
'path': TEST_INFO['dataset_path'],
'dacl': payload_acl,
'gid': 65534, 'uid': 0,
'options': {'recursive': True},
}, job=True)
if "EXECUTE" not in tests_to_skip:
cmd = f'cd /mnt/{ACLTEST_DATASET}'
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {to_allow}'
assert results['result'] is False, errstr
if "DELETE" not in tests_to_skip:
cmd = f'rm /mnt/{ACLTEST_DATASET}/acltest.txt'
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {to_allow}'
assert results['result'] is False, errstr
if results['result'] is True:
# File must be re-created. Kernel ACL inheritance routine
# will ensure that new file has right ACL.
ssh(f'echo -n "CAT" >> /mnt/{ACLTEST_DATASET}/acltest.txt')
if "READ_DATA" not in tests_to_skip:
cmd = f'cat /mnt/{ACLTEST_DATASET}/acltest.txt'
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {to_allow}'
assert results['result'] is False, errstr
if "WRITE_DATA" not in tests_to_skip:
cmd = f'echo -n "CAT" >> /mnt/{ACLTEST_DATASET}/acltest.txt'
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {to_allow}'
assert results['result'] is False, errstr
if "WRITE_ATTRIBUTES" not in tests_to_skip:
cmd = f'touch -a -m -t 201512180130.09 /mnt/{ACLTEST_DATASET}/acltest.txt'
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {to_allow}'
assert results['result'] is False, errstr
if "READ_ACL" not in tests_to_skip:
cmd = f'{getfaclcmd} /mnt/{ACLTEST_DATASET}/acltest.txt'
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {to_allow}'
assert results['result'] is False, errstr
if "WRITE_ACL" not in tests_to_skip:
cmd = f'{setfaclcmd} -x 0 /mnt/{ACLTEST_DATASET}/acltest.txt'
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {to_allow}'
assert results['result'] is False, errstr
if "WRITE_OWNER" not in tests_to_skip:
cmd = f'chown {ACL_USER} /mnt/{ACLTEST_DATASET}/acltest.txt'
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {to_allow}'
assert results['result'] is False, errstr
def test_26_file_execute_deny(request):
"""
Base permset with everyone@ FULL_CONTROL, but ace added on
top explictly denying EXECUTE. Attempt to execute file should fail.
"""
depends(request, ["HAS_NFS4_ACLS", "HAS_TESTFILE"], scope="session")
payload_acl = [
{
"tag": "USER",
"id": TEST_INFO['user']['uid'],
"type": "DENY",
"perms": {"EXECUTE": True},
"flags": {"FILE_INHERIT": True}
},
{
"tag": "USER",
"id": TEST_INFO['user']['uid'],
"type": "ALLOW",
"perms": {"EXECUTE": True},
"flags": {"BASIC": "NOINHERIT"}
},
]
payload_acl.extend(function_testing_acl_deny)
call('filesystem.setacl', {
'path': TEST_INFO['dataset_path'],
'dacl': payload_acl,
'gid': 0, 'uid': 0,
'options': {'recursive': True},
}, job=True)
ssh(f'echo "echo CANARY" > /mnt/{ACLTEST_DATASET}/acltest.txt')
cmd = f'/mnt/{ACLTEST_DATASET}/acltest.txt'
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {payload_acl}'
assert results['result'] is False, errstr
def test_27_file_execute_allow(request):
"""
Verify that setting execute allows file execution. READ_DATA and
READ_ATTRIBUTES are also granted beecause we need to be able to
stat and read our test script.
"""
depends(request, ["HAS_NFS4_ACLS", "HAS_TESTFILE"], scope="session")
payload_acl = [
{
"tag": "USER",
"id": TEST_INFO['user']['uid'],
"type": "ALLOW",
"perms": {
"EXECUTE": True,
"READ_DATA": True,
"READ_ATTRIBUTES": True
},
"flags": {"FILE_INHERIT": True}
},
{
"tag": "USER",
"id": TEST_INFO['user']['uid'],
"type": "ALLOW",
"perms": {"EXECUTE": True},
"flags": {"BASIC": "NOINHERIT"}
},
]
payload_acl.extend(function_testing_acl_allow)
call('filesystem.setacl', {
'path': TEST_INFO['dataset_path'],
'dacl': payload_acl,
'gid': 0, 'uid': 0,
'options': {'recursive': True},
}, job=True)
ssh(f'echo "echo CANARY" > /mnt/{ACLTEST_DATASET}/acltest.txt')
cmd = f'/mnt/{ACLTEST_DATASET}/acltest.txt'
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {payload_acl}'
assert results['result'] is True, errstr
def test_28_file_execute_omit(request):
"""
Grant user all permissions except EXECUTE. Attempt to execute
file should fail.
"""
depends(request, ["HAS_NFS4_ACLS", "HAS_TESTFILE"], scope="session")
payload_acl = [
{
"tag": "USER",
"id": TEST_INFO['user']['uid'],
"type": "ALLOW",
"perms": base_permset.copy(),
"flags": {"FILE_INHERIT": True}
},
{
"tag": "USER",
"id": TEST_INFO['user']['uid'],
"type": "ALLOW",
"perms": {"EXECUTE": True},
"flags": {"BASIC": "NOINHERIT"}
},
]
payload_acl.extend(function_testing_acl_allow)
# at this point the user's ACE has all perms set
# remove execute.
payload_acl[0]['perms']['EXECUTE'] = False
call('filesystem.setacl', {
'path': TEST_INFO['dataset_path'],
'dacl': payload_acl,
'gid': 0, 'uid': 0,
'options': {'recursive': True},
}, job=True)
ssh(f'echo "echo CANARY" > /mnt/{ACLTEST_DATASET}/acltest.txt')
cmd = f'/mnt/{ACLTEST_DATASET}/acltest.txt'
results = SSH_TEST(cmd, ACL_USER, ACL_PWD)
errstr = f'cmd: {cmd}, res: {results["output"]}, to_allow {payload_acl}'
assert results['result'] is False, errstr
def test_29_owner_restrictions(request):
depends(request, ["HAS_NFS4_ACLS"], scope="session")
payload_acl = [{
"tag": "owner@",
"id": -1,
"type": "ALLOW",
"perms": {"BASIC": "READ"},
"flags": {"BASIC": "INHERIT"}
}]
call('filesystem.setacl', {
'path': TEST_INFO['dataset_path'],
'dacl': payload_acl,
'gid': 0, 'uid': TEST_INFO['user']['uid'],
'options': {'recursive': True},
}, job=True)
results = ssh(
f'mkdir /mnt/{ACLTEST_DATASET}/dir1/dir_should_not_exist',
complete_response=True, check=False,
user=ACL_USER, password=ACL_PWD
)
assert results['result'] is False, str(results)
results = ssh(
f'touch /mnt/{ACLTEST_DATASET}/dir1/file_should_not_exist',
complete_response=True, check=False,
user=ACL_USER, password=ACL_PWD
)
assert results['result'] is False, str(results)
def test_30_acl_inherit_nested_dataset():
with make_dataset("acl_test_inherit1", data={'share_type': 'SMB'}) as ds1:
call('filesystem.add_to_acl', {
'path': os.path.join('/mnt', ds1),
'entries': [{'id_type': 'GROUP', 'id': 666, 'access': 'READ'}]
}, job=True)
acl1 = call('filesystem.getacl', os.path.join('/mnt', ds1))
assert any(x['id'] == 666 for x in acl1['acl'])
with pytest.raises(ValidationErrors):
# ACL on parent dataset prevents adding APPS group to ACL. Fail.
with make_dataset("acl_test_inherit1/acl_test_inherit2", data={'share_type': 'APPS'}):
pass
with make_dataset("acl_test_inherit1/acl_test_inherit2", data={'share_type': 'NFS'}) as ds2:
acl2 = call('filesystem.getacl', os.path.join('/mnt', ds2))
assert acl1['acltype'] == acl2['acltype']
assert any(x['id'] == 666 for x in acl2['acl'])
| 31,015 | Python | .py | 769 | 33.858257 | 102 | 0.617382 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,327 | test_audit_websocket.py | truenas_middleware/tests/api2/test_audit_websocket.py | # -*- coding=utf-8 -*-
from unittest.mock import ANY
import pytest
from middlewared.service_exception import CallError, ValidationErrors
from middlewared.test.integration.assets.account import unprivileged_user_client, user
from middlewared.test.integration.assets.api_key import api_key
from middlewared.test.integration.assets.two_factor_auth import enabled_twofactor_auth, get_user_secret, get_2fa_totp_token
from middlewared.test.integration.utils import call, client, ssh
from middlewared.test.integration.utils.audit import expect_audit_log
@pytest.fixture(scope='function')
def sharing_admin_user(unprivileged_user_fixture):
privilege = call('privilege.query', [['local_groups.0.group', '=', unprivileged_user_fixture.group_name]])
assert len(privilege) > 0, 'Privilege not found'
call('privilege.update', privilege[0]['id'], {'roles': ['SHARING_ADMIN']})
try:
yield unprivileged_user_fixture
finally:
call('privilege.update', privilege[0]['id'], {'roles': []})
def test_unauthenticated_call():
with client(auth=None) as c:
with expect_audit_log([
{
"service_data": {
"vers": {
"major": 0,
"minor": 1,
},
"origin": ANY,
"protocol": "WEBSOCKET",
"credentials": None,
},
"event": "METHOD_CALL",
"event_data": {
"authenticated": False,
"authorized": False,
"method": "user.create",
"params": [{"username": "sergey", "full_name": "Sergey"}],
"description": "Create user sergey",
},
"success": False,
}
]):
with pytest.raises(CallError):
c.call("user.create", {"username": "sergey", "full_name": "Sergey"})
def test_unauthorized_call():
with unprivileged_user_client() as c:
with expect_audit_log([
{
"service_data": {
"vers": {
"major": 0,
"minor": 1,
},
"origin": ANY,
"protocol": "WEBSOCKET",
"credentials": {
"credentials": "LOGIN_PASSWORD",
"credentials_data": {"username": ANY, "login_at": ANY},
},
},
"event": "METHOD_CALL",
"event_data": {
"authenticated": True,
"authorized": False,
"method": "user.create",
"params": [{"username": "sergey", "full_name": "Sergey"}],
"description": "Create user sergey",
},
"success": False,
}
]):
with pytest.raises(CallError):
c.call("user.create", {"username": "sergey", "full_name": "Sergey"})
def test_bogus_call():
with client() as c:
with expect_audit_log([
{
"service_data": {
"vers": {
"major": 0,
"minor": 1,
},
"origin": ANY,
"protocol": "WEBSOCKET",
"credentials": {
"credentials": "LOGIN_PASSWORD",
"credentials_data": {"username": "root", "login_at": ANY},
},
},
"event": "METHOD_CALL",
"event_data": {
"authenticated": True,
"authorized": True,
"method": "user.create",
"params": [{}],
"description": "Create user",
},
"success": False,
}
]):
with pytest.raises(ValidationErrors):
c.call("user.create", {})
def test_invalid_call():
with client() as c:
with expect_audit_log([
{
"service_data": {
"vers": {
"major": 0,
"minor": 1,
},
"origin": ANY,
"protocol": "WEBSOCKET",
"credentials": {
"credentials": "LOGIN_PASSWORD",
"credentials_data": {"username": "root", "login_at": ANY},
},
},
"event": "METHOD_CALL",
"event_data": {
"authenticated": True,
"authorized": True,
"method": "user.create",
"params": [{"username": "sergey", "password": "********"}],
"description": "Create user sergey",
},
"success": False,
}
]):
with pytest.raises(ValidationErrors):
c.call("user.create", {"username": "sergey", "password": "password"})
def test_typo_in_secret_credential_name():
with client() as c:
with expect_audit_log([
{
"service_data": {
"vers": {
"major": 0,
"minor": 1,
},
"origin": ANY,
"protocol": "WEBSOCKET",
"credentials": {
"credentials": "LOGIN_PASSWORD",
"credentials_data": {"username": "root", "login_at": ANY},
},
},
"event": "METHOD_CALL",
"event_data": {
"authenticated": True,
"authorized": True,
"method": "user.create",
"params": [{"username": "sergey"}],
"description": "Create user sergey",
},
"success": False,
}
]):
with pytest.raises(ValidationErrors):
c.call("user.create", {"username": "sergey", "passwrod": "password"})
def test_valid_call():
with expect_audit_log([
{
"service_data": {
"vers": {
"major": 0,
"minor": 1,
},
"origin": ANY,
"protocol": "WEBSOCKET",
"credentials": {
"credentials": "LOGIN_PASSWORD",
"credentials_data": {"username": "root", "login_at": ANY},
},
},
"event": "METHOD_CALL",
"event_data": {
"authenticated": True,
"authorized": True,
"method": "user.create",
"params": [
{
"username": "sergey",
"full_name": "Sergey",
"group_create": True,
"home": "/nonexistent",
"password": "********",
"home_create": True,
}
],
"description": "Create user sergey",
},
"success": True,
},
{},
]):
with user({
"username": "sergey",
"full_name": "Sergey",
"group_create": True,
"home": "/nonexistent",
"password": "password",
}):
pass
def test_password_login():
with expect_audit_log([
{
"service_data": {
"vers": {
"major": 0,
"minor": 1,
},
"origin": ANY,
"protocol": "WEBSOCKET",
"credentials": {
"credentials": "LOGIN_PASSWORD",
"credentials_data": {"username": "root", "login_at": ANY},
},
},
"event": "AUTHENTICATION",
"event_data": {
"credentials": {
"credentials": "LOGIN_PASSWORD",
"credentials_data": {"username": "root", "login_at": ANY},
},
"error": None,
},
"success": True,
}
], include_logins=True):
with client():
pass
def test_password_login_failed():
with expect_audit_log([
{
"event": "AUTHENTICATION",
"event_data": {
"credentials": {
"credentials": "LOGIN_PASSWORD",
"credentials_data": {"username": "invalid"},
},
"error": "Bad username or password",
},
"success": False,
}
], include_logins=True):
with client(auth=("invalid", ""), auth_required=False):
pass
def test_token_login():
token = call("auth.generate_token", 300, {}, True)
with client(auth=None) as c:
with expect_audit_log([
{
"event": "AUTHENTICATION",
"event_data": {
"credentials": {
"credentials": "TOKEN",
"credentials_data": {
"parent": {
"credentials": "LOGIN_PASSWORD",
"credentials_data": {"username": "root", "login_at": ANY},
},
"username": "root",
},
},
"error": None,
},
"success": True,
}
], include_logins=True):
assert c.call("auth.login_with_token", token)
def test_token_login_failed():
with client(auth=None) as c:
with expect_audit_log([
{
"event": "AUTHENTICATION",
"event_data": {
"credentials": {
"credentials": "TOKEN",
"credentials_data": {
"token": "invalid_token",
},
},
"error": "Invalid token",
},
"success": False,
}
], include_logins=True):
c.call("auth.login_with_token", "invalid_token")
def test_token_attributes_login_failed():
token = call("auth.generate_token", 300, {"filename": "debug.txz", "job": 1020}, True)
with client(auth=None) as c:
with expect_audit_log([
{
"event": "AUTHENTICATION",
"event_data": {
"credentials": {
"credentials": "TOKEN",
"credentials_data": {
"token": token,
},
},
"error": "Bad token",
},
"success": False,
}
], include_logins=True):
c.call("auth.login_with_token", token)
def test_api_key_login():
with api_key() as key:
with client(auth=None) as c:
with expect_audit_log([
{
"event": "AUTHENTICATION",
"event_data": {
"credentials": {
"credentials": "API_KEY",
"credentials_data": {
"username": "root",
"login_at": ANY,
"api_key": {"id": ANY, "name": ANY},
},
},
"error": None,
},
"success": True,
}
], include_logins=True):
assert c.call("auth.login_with_api_key", key)
def test_api_key_login_failed():
with client(auth=None) as c:
with expect_audit_log([
{
"event": "AUTHENTICATION",
"event_data": {
"credentials": {
"credentials": "API_KEY",
"credentials_data": {
"api_key": "invalid_api_key",
"username": None
},
},
"error": "Invalid API key",
},
"success": False,
}
], include_logins=True):
c.call("auth.login_with_api_key", "invalid_api_key")
def test_2fa_login(sharing_admin_user):
user_obj_id = call('user.query', [['username', '=', sharing_admin_user.username]], {'get': True})['id']
with enabled_twofactor_auth():
call('user.renew_2fa_secret', sharing_admin_user.username, {'interval': 60})
secret = get_user_secret(user_obj_id)
with client(auth=None) as c:
resp = c.call('auth.login_ex', {
'mechanism': 'PASSWORD_PLAIN',
'username': sharing_admin_user.username,
'password': sharing_admin_user.password
})
assert resp['response_type'] == 'OTP_REQUIRED'
assert resp['username'] == sharing_admin_user.username
# simulate user fat-fingering the OTP token and then getting it correct on second attempt
otp = get_2fa_totp_token(secret)
with expect_audit_log([
{
"event": "AUTHENTICATION",
"event_data": {
"credentials": {
"credentials": "LOGIN_TWOFACTOR",
"credentials_data": {
"username": sharing_admin_user.username,
},
},
"error": "One-time token validation failed.",
},
"success": False,
}
], include_logins=True):
resp = c.call('auth.login_ex', {
'mechanism': 'OTP_TOKEN',
'otp_token': 'canary'
})
assert resp['response_type'] == 'OTP_REQUIRED'
assert resp['username'] == sharing_admin_user.username
with expect_audit_log([
{
"event": "AUTHENTICATION",
"event_data": {
"credentials": {
"credentials": "LOGIN_TWOFACTOR",
"credentials_data": {
"username": sharing_admin_user.username,
"login_at": ANY,
},
},
"error": None,
},
"success": True,
}
], include_logins=True):
resp = c.call('auth.login_ex', {
'mechanism': 'OTP_TOKEN',
'otp_token': otp
})
assert resp['response_type'] == 'SUCCESS'
@pytest.mark.parametrize('logfile', ('/var/log/messages', '/var/log/syslog'))
def test_check_syslog_leak(logfile):
entries = ssh(f'grep @cee {logfile}', check=False)
assert '@cee' not in entries
| 15,606 | Python | .py | 409 | 21.599022 | 123 | 0.405306 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,328 | test_audit_iscsi.py | truenas_middleware/tests/api2/test_audit_iscsi.py | import pytest
from middlewared.test.integration.assets.iscsi import iscsi_extent, iscsi_target
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.utils import call
from middlewared.test.integration.utils.audit import expect_audit_method_calls
REDACTED_SECRET = '********'
MB = 1024 * 1024
MB_100 = 100 * MB
DEFAULT_ISCSI_PORT = 3260
@pytest.fixture(scope='module')
def initialize_zvol_for_iscsi_audit_tests(request):
with dataset('audit-test-iscsi') as ds:
zvol = f'{ds}/zvol'
payload = {
'name': zvol,
'type': 'VOLUME',
'volsize': MB_100,
'volblocksize': '16K'
}
zvol_config = call('pool.dataset.create', payload)
try:
yield zvol
finally:
call('pool.dataset.delete', zvol_config['id'])
def test_iscsi_auth_audit():
auth_config = None
tag = 1
user1 = 'someuser1'
user2 = 'someuser2'
password1 = 'somepassword123'
password2 = 'newpassword1234'
try:
# CREATE
with expect_audit_method_calls([{
'method': 'iscsi.auth.create',
'params': [
{
'tag': tag,
'user': user1,
'secret': REDACTED_SECRET,
}
],
'description': f'Create iSCSI Authorized Access {user1} ({tag})',
}]):
payload = {
'tag': tag,
'user': user1,
'secret': password1,
}
auth_config = call('iscsi.auth.create', payload)
# UPDATE
with expect_audit_method_calls([{
'method': 'iscsi.auth.update',
'params': [
auth_config['id'],
{
'user': user2,
'secret': REDACTED_SECRET,
}],
'description': f'Update iSCSI Authorized Access {user1} ({tag})',
}]):
payload = {
'user': user2,
'secret': password2,
}
auth_config = call('iscsi.auth.update', auth_config['id'], payload)
finally:
if auth_config is not None:
# DELETE
id_ = auth_config['id']
with expect_audit_method_calls([{
'method': 'iscsi.auth.delete',
'params': [id_],
'description': f'Delete iSCSI Authorized Access {user2} ({tag})',
}]):
call('iscsi.auth.delete', id_)
def test_iscsi_extent_audit(initialize_zvol_for_iscsi_audit_tests):
extent_name1 = 'extent1'
extent_name2 = 'extent2'
disk = f'zvol/{initialize_zvol_for_iscsi_audit_tests}'
try:
# CREATE
with expect_audit_method_calls([{
'method': 'iscsi.extent.create',
'params': [
{
'type': 'DISK',
'disk': disk,
'name': extent_name1,
}
],
'description': f'Create iSCSI extent {extent_name1}',
}]):
payload = {
'type': 'DISK',
'disk': disk,
'name': extent_name1,
}
extent_config = call('iscsi.extent.create', payload)
# UPDATE
with expect_audit_method_calls([{
'method': 'iscsi.extent.update',
'params': [
extent_config['id'],
{
'name': extent_name2,
}],
'description': f'Update iSCSI extent {extent_name1}',
}]):
payload = {
'name': extent_name2,
}
extent_config = call('iscsi.extent.update', extent_config['id'], payload)
finally:
if extent_config is not None:
# DELETE
id_ = extent_config['id']
with expect_audit_method_calls([{
'method': 'iscsi.extent.delete',
'params': [id_],
'description': f'Delete iSCSI extent {extent_name2}',
}]):
call('iscsi.extent.delete', id_)
def test_iscsi_global_audit():
global_config = None
try:
# CREATE
with expect_audit_method_calls([{
'method': 'iscsi.global.update',
'params': [
{
'alua': True,
'listen_port': 13260,
}
],
'description': 'Update iSCSI',
}]):
payload = {
'alua': True,
'listen_port': 13260,
}
global_config = call('iscsi.global.update', payload)
finally:
if global_config is not None:
payload = {
'alua': False,
'listen_port': DEFAULT_ISCSI_PORT,
}
global_config = call('iscsi.global.update', payload)
def test_iscsi_host_audit():
host_config = None
ip = '1.2.3.4'
iqn = 'iqn.1993-08.org.debian:01:1234567890'
description = 'Development VM (debian)'
try:
# CREATE
with expect_audit_method_calls([{
'method': 'iscsi.host.create',
'params': [
{
'ip': ip,
'iqns': [iqn],
}
],
'description': f'Create iSCSI host {ip}',
}]):
payload = {
'ip': ip,
'iqns': [iqn],
}
host_config = call('iscsi.host.create', payload)
# UPDATE
with expect_audit_method_calls([{
'method': 'iscsi.host.update',
'params': [
host_config['id'],
{
'description': description,
}],
'description': f'Update iSCSI host {ip}',
}]):
payload = {
'description': description,
}
host_config = call('iscsi.host.update', host_config['id'], payload)
finally:
if host_config is not None:
# DELETE
id_ = host_config['id']
with expect_audit_method_calls([{
'method': 'iscsi.host.delete',
'params': [id_],
'description': f'Delete iSCSI host {ip}',
}]):
call('iscsi.host.delete', id_)
def test_iscsi_initiator_audit():
initiator_config = None
comment = 'Default initiator'
comment2 = 'INITIATOR'
try:
# CREATE
with expect_audit_method_calls([{
'method': 'iscsi.initiator.create',
'params': [
{
'comment': comment,
'initiators': [],
}
],
'description': f'Create iSCSI initiator {comment}',
}]):
payload = {
'comment': comment,
'initiators': [],
}
initiator_config = call('iscsi.initiator.create', payload)
# UPDATE
with expect_audit_method_calls([{
'method': 'iscsi.initiator.update',
'params': [
initiator_config['id'],
{
'comment': comment2,
'initiators': ['1.2.3.4', '5.6.7.8'],
}],
'description': f'Update iSCSI initiator {comment}',
}]):
payload = {
'comment': comment2,
'initiators': ['1.2.3.4', '5.6.7.8'],
}
initiator_config = call('iscsi.initiator.update', initiator_config['id'], payload)
finally:
if initiator_config is not None:
# DELETE
id_ = initiator_config['id']
with expect_audit_method_calls([{
'method': 'iscsi.initiator.delete',
'params': [id_],
'description': f'Delete iSCSI initiator {comment2}',
}]):
call('iscsi.initiator.delete', id_)
def test_iscsi_portal_audit():
portal_config = None
comment = 'Default portal'
comment2 = 'PORTAL'
try:
# CREATE
with expect_audit_method_calls([{
'method': 'iscsi.portal.create',
'params': [
{
'listen': [{'ip': '0.0.0.0'}],
'comment': comment,
'discovery_authmethod': 'NONE',
}
],
'description': f'Create iSCSI portal {comment}',
}]):
payload = {
'listen': [{'ip': '0.0.0.0'}],
'comment': comment,
'discovery_authmethod': 'NONE',
}
portal_config = call('iscsi.portal.create', payload)
# UPDATE
with expect_audit_method_calls([{
'method': 'iscsi.portal.update',
'params': [
portal_config['id'],
{
'comment': comment2,
}],
'description': f'Update iSCSI portal {comment}',
}]):
payload = {
'comment': comment2,
}
portal_config = call('iscsi.portal.update', portal_config['id'], payload)
finally:
if portal_config is not None:
# DELETE
id_ = portal_config['id']
with expect_audit_method_calls([{
'method': 'iscsi.portal.delete',
'params': [id_],
'description': f'Delete iSCSI portal {comment2}',
}]):
call('iscsi.portal.delete', id_)
def test_iscsi_target_audit():
target_config = None
target_name = 'target1'
target_alias1 = 'target1 alias'
target_alias2 = 'Updated target1 alias'
try:
# CREATE
with expect_audit_method_calls([{
'method': 'iscsi.target.create',
'params': [
{
'name': target_name,
'alias': target_alias1,
}
],
'description': f'Create iSCSI target {target_name}',
}]):
payload = {
'name': target_name,
'alias': target_alias1,
}
target_config = call('iscsi.target.create', payload)
# UPDATE
with expect_audit_method_calls([{
'method': 'iscsi.target.update',
'params': [
target_config['id'],
{
'alias': target_alias2,
}],
'description': f'Update iSCSI target {target_name}',
}]):
payload = {
'alias': target_alias2,
}
target_config = call('iscsi.target.update', target_config['id'], payload)
finally:
if target_config is not None:
# DELETE
id_ = target_config['id']
with expect_audit_method_calls([{
'method': 'iscsi.target.delete',
'params': [id_, True],
'description': f'Delete iSCSI target {target_name}',
}]):
call('iscsi.target.delete', id_, True)
def test_iscsi_targetextent_audit(initialize_zvol_for_iscsi_audit_tests):
payload = {
'type': 'DISK',
'disk': f'zvol/{initialize_zvol_for_iscsi_audit_tests}',
'name': 'extent1',
}
with iscsi_extent(payload) as extent_config:
with iscsi_target({'name': 'target1', 'alias': 'Audit test'}) as target_config:
targetextent_config = None
try:
# CREATE
with expect_audit_method_calls([{
'method': 'iscsi.targetextent.create',
'params': [
{
'target': target_config['id'],
'extent': extent_config['id'],
'lunid': 0,
}
],
'description': 'Create iSCSI target/LUN/extent mapping target1/0/extent1',
}]):
payload = {
'target': target_config['id'],
'extent': extent_config['id'],
'lunid': 0,
}
targetextent_config = call('iscsi.targetextent.create', payload)
# UPDATE
with expect_audit_method_calls([{
'method': 'iscsi.targetextent.update',
'params': [
targetextent_config['id'],
{
'lunid': 1,
}],
'description': 'Update iSCSI target/LUN/extent mapping target1/0/extent1',
}]):
payload = {
'lunid': 1,
}
targetextent_config = call('iscsi.targetextent.update', targetextent_config['id'], payload)
finally:
if targetextent_config is not None:
# DELETE
id_ = targetextent_config['id']
with expect_audit_method_calls([{
'method': 'iscsi.targetextent.delete',
'params': [id_, True],
'description': 'Delete iSCSI target/LUN/extent mapping target1/1/extent1',
}]):
call('iscsi.targetextent.delete', id_, True)
| 13,611 | Python | .py | 387 | 21.78553 | 111 | 0.458608 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,329 | test_smb_share_crud_roles.py | truenas_middleware/tests/api2/test_smb_share_crud_roles.py | import pytest
from middlewared.service_exception import ValidationErrors
from middlewared.test.integration.assets.account import unprivileged_user_client
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.assets.roles import common_checks
from middlewared.test.integration.assets.smb import smb_share
from middlewared.test.integration.utils import call
@pytest.fixture(scope='module')
def create_dataset():
with dataset('smb_roles_test') as ds:
yield ds
@pytest.mark.parametrize("role", ["SHARING_READ", "SHARING_SMB_READ"])
def test_read_role_can_read(unprivileged_user_fixture, role):
common_checks(unprivileged_user_fixture, "sharing.smb.query", role, True, valid_role_exception=False)
@pytest.mark.parametrize("role", ["SHARING_READ", "SHARING_SMB_READ"])
def test_read_role_cant_write(unprivileged_user_fixture, role):
common_checks(unprivileged_user_fixture, "sharing.smb.create", role, False)
common_checks(unprivileged_user_fixture, "sharing.smb.update", role, False)
common_checks(unprivileged_user_fixture, "sharing.smb.delete", role, False)
common_checks(unprivileged_user_fixture, "sharing.smb.getacl", role, True)
common_checks(unprivileged_user_fixture, "sharing.smb.setacl", role, False)
common_checks(unprivileged_user_fixture, "smb.status", role, False)
@pytest.mark.parametrize("role", ["SHARING_WRITE", "SHARING_SMB_WRITE"])
def test_write_role_can_write(unprivileged_user_fixture, role):
common_checks(unprivileged_user_fixture, "sharing.smb.create", role, True)
common_checks(unprivileged_user_fixture, "sharing.smb.update", role, True)
common_checks(unprivileged_user_fixture, "sharing.smb.delete", role, True)
common_checks(unprivileged_user_fixture, "sharing.smb.getacl", role, True)
common_checks(unprivileged_user_fixture, "sharing.smb.setacl", role, True)
common_checks(unprivileged_user_fixture, "smb.status", role, True, valid_role_exception=False)
common_checks(
unprivileged_user_fixture, "service.start", role, True, method_args=["cifs"], valid_role_exception=False
)
common_checks(
unprivileged_user_fixture, "service.restart", role, True, method_args=["cifs"], valid_role_exception=False
)
common_checks(
unprivileged_user_fixture, "service.reload", role, True, method_args=["cifs"], valid_role_exception=False
)
common_checks(
unprivileged_user_fixture, "service.stop", role, True, method_args=["cifs"], valid_role_exception=False
)
@pytest.mark.parametrize("role", ["SHARING_WRITE", "SHARING_SMB_WRITE"])
def test_auxsmbconf_rejected_create(create_dataset, role):
share = None
with unprivileged_user_client(roles=[role]) as c:
with pytest.raises(ValidationErrors) as ve:
try:
share = c.call('sharing.smb.create', {
'name': 'FAIL',
'path': f'/mnt/{create_dataset}',
'auxsmbconf': 'test:param = CANARY'
})
finally:
if share:
call('sharing.smb.delete', share['id'])
@pytest.mark.parametrize("role", ["SHARING_WRITE", "SHARING_SMB_WRITE"])
def test_auxsmbconf_rejected_update(create_dataset, role):
with smb_share(f'/mnt/{create_dataset}', 'FAIL') as share:
with unprivileged_user_client(roles=[role]) as c:
with pytest.raises(ValidationErrors):
c.call('sharing.smb.update', share['id'], {'auxsmbconf': 'test:param = Bob'})
| 3,552 | Python | .py | 62 | 50.612903 | 114 | 0.708981 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,330 | test_keychain_ssh.py | truenas_middleware/tests/api2/test_keychain_ssh.py | import pytest
from middlewared.service_exception import CallError
from middlewared.test.integration.assets.account import user
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.utils import call
@pytest.fixture(scope="module")
def credential():
credential = call("keychaincredential.create", {
"name": "key",
"type": "SSH_KEY_PAIR",
"attributes": call("keychaincredential.generate_ssh_key_pair"),
})
try:
yield credential
finally:
call("keychaincredential.delete", credential["id"])
def test_remote_ssh_semiautomatic_setup_invalid_homedir(credential):
with user({
"username": "admin",
"full_name": "admin",
"group_create": True,
"home_create": False,
"password": "test1234",
}):
token = call("auth.generate_token")
with pytest.raises(CallError) as ve:
call("keychaincredential.remote_ssh_semiautomatic_setup", {
"name": "localhost",
"url": "http://localhost",
"token": token,
"username": "admin",
"private_key": credential["id"],
})
assert "make sure that home directory for admin user on the remote system exists" in ve.value.errmsg
def test_remote_ssh_semiautomatic_setup_sets_user_attributes(credential):
with dataset("unpriv_homedir") as homedir:
with user({
"username": "unpriv",
"full_name": "unpriv",
"group_create": True,
"home": f"/mnt/{homedir}",
"password_disabled": True,
"smb": False,
"shell": "/usr/sbin/nologin",
}):
token = call("auth.generate_token")
connection = call("keychaincredential.remote_ssh_semiautomatic_setup", {
"name": "localhost",
"url": "http://localhost",
"token": token,
"username": "unpriv",
"private_key": credential["id"],
})
try:
call("replication.list_datasets", "SSH", connection["id"])
finally:
call("keychaincredential.delete", connection["id"])
def test_ssl_certificate_error(credential):
token = call("auth.generate_token")
with pytest.raises(CallError) as ve:
call("keychaincredential.remote_ssh_semiautomatic_setup", {
"name": "localhost",
# Should fail on default self-signed certificate
"url": "https://localhost",
"token": token,
"private_key": credential["id"],
})
assert ve.value.errno == CallError.ESSLCERTVERIFICATIONERROR
def test_ignore_ssl_certificate_error(credential):
token = call("auth.generate_token")
connection = call("keychaincredential.remote_ssh_semiautomatic_setup", {
"name": "localhost",
"url": "https://localhost",
"verify_ssl": False,
"token": token,
"private_key": credential["id"],
})
call("keychaincredential.delete", connection["id"])
| 3,120 | Python | .py | 78 | 30.474359 | 108 | 0.598878 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,331 | test_ntpserver_alert.py | truenas_middleware/tests/api2/test_ntpserver_alert.py | import contextlib
import copy
import time
from middlewared.test.integration.utils import call, mock, ssh
CONFIG_FILE = "/etc/chrony/chrony.conf"
BAD_NTP = "172.16.0.0"
@contextlib.contextmanager
def temp_remove_ntp_config():
orig = call("system.ntpserver.query")
try:
for i in orig:
_id = i.pop("id")
assert call("system.ntpserver.delete", _id)
yield copy.deepcopy(orig[0]) # arbitrarily yield first entry
finally:
for i in orig:
# finally update with original (functional) config
assert call("system.ntpserver.create", i)
def test_verify_ntp_alert_is_raised():
with temp_remove_ntp_config() as temp:
temp["address"] = BAD_NTP
temp["force"] = True
temp_id = call("system.ntpserver.create", temp)["id"]
call("system.ntpserver.query", [["address", "=", BAD_NTP]], {"get": True})
# verify the OS config
results = ssh(f'fgrep "{BAD_NTP}" {CONFIG_FILE}', complete_response=True)
assert results["result"] is True, results
# verify alert is raised
with mock("system.time_info", return_value={"uptime_seconds": 600}):
assert call("alert.run_source", "NTPHealthCheck")[0]["args"]["reason"].startswith("No Active NTP peers")
# remove our bogus entry
assert call("system.ntpserver.delete", temp_id)
def test_verify_ntp_alert_is_cleared():
max_retries = 10
for i in range(max_retries):
alerts = call("alert.run_source", "NTPHealthCheck")
if not alerts:
return
else:
time.sleep(1)
assert False, f"NTPHealthCheck alert didnt clear after {max_retries} seconds: {alerts}"
| 1,717 | Python | .py | 41 | 34.536585 | 116 | 0.640625 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,332 | test_vm_roles.py | truenas_middleware/tests/api2/test_vm_roles.py | import pytest
from middlewared.test.integration.assets.roles import common_checks
@pytest.mark.parametrize('method, expected_error', [
('vm.virtualization_details', False),
('vm.maximum_supported_vcpus', False),
('vm.get_display_devices', True),
('vm.get_display_web_uri', True),
('vm.get_available_memory', False),
('vm.bootloader_options', False),
])
def test_vm_readonly_role(unprivileged_user_fixture, method, expected_error):
common_checks(unprivileged_user_fixture, method, 'READONLY_ADMIN', True, valid_role_exception=expected_error)
@pytest.mark.parametrize('role, method, valid_role', [
('VM_READ', 'vm.supports_virtualization', True),
('VM_WRITE', 'vm.supports_virtualization', True),
('VM_READ', 'vm.virtualization_details', True),
('VM_WRITE', 'vm.virtualization_details', True),
('VM_READ', 'vm.maximum_supported_vcpus', True),
('VM_WRITE', 'vm.maximum_supported_vcpus', True),
('VM_READ', 'vm.flags', True),
('VM_WRITE', 'vm.flags', True),
('VM_READ', 'vm.cpu_model_choices', True),
('VM_WRITE', 'vm.cpu_model_choices', True),
('VM_READ', 'vm.port_wizard', True),
('VM_READ', 'vm.bootloader_options', True),
])
def test_vm_read_write_roles(unprivileged_user_fixture, role, method, valid_role):
common_checks(unprivileged_user_fixture, method, role, valid_role, valid_role_exception=False)
@pytest.mark.parametrize('role, method, valid_role', [
('VM_WRITE', 'vm.clone', True),
('VM_READ', 'vm.get_memory_usage', True),
('VM_WRITE', 'vm.get_memory_usage', True),
('VM_READ', 'vm.start', False),
('VM_WRITE', 'vm.start', True),
('VM_READ', 'vm.stop', False),
('VM_WRITE', 'vm.stop', True),
('VM_READ', 'vm.restart', False),
('VM_WRITE', 'vm.restart', True),
('VM_READ', 'vm.suspend', False),
('VM_WRITE', 'vm.suspend', True),
('VM_READ', 'vm.resume', False),
('VM_WRITE', 'vm.resume', True),
('VM_READ', 'vm.get_vm_memory_info', True),
('VM_READ', 'vm.get_display_devices', True),
('VM_READ', 'vm.status', True),
('VM_READ', 'vm.log_file_path', True),
])
def test_vm_read_write_roles_requiring_virtualization(unprivileged_user_fixture, role, method, valid_role):
common_checks(unprivileged_user_fixture, method, role, valid_role)
@pytest.mark.parametrize('role, method, valid_role', [
('VM_DEVICE_READ', 'vm.device.iommu_enabled', True),
('VM_DEVICE_READ', 'vm.device.passthrough_device_choices', True),
('VM_DEVICE_READ', 'vm.device.nic_attach_choices', True),
('VM_DEVICE_READ', 'vm.device.usb_passthrough_choices', True),
('VM_READ', 'vm.guest_architecture_and_machine_choices', True),
])
def test_vm_device_read_write_roles(unprivileged_user_fixture, role, method, valid_role):
common_checks(unprivileged_user_fixture, method, role, valid_role, valid_role_exception=False)
@pytest.mark.parametrize('role, method, valid_role', [
('VM_DEVICE_READ', 'vm.device.passthrough_device', True),
('VM_DEVICE_WRITE', 'vm.device.passthrough_device', True),
])
def test_vm_device_read_write_roles_requiring_virtualization(unprivileged_user_fixture, role, method, valid_role):
common_checks(unprivileged_user_fixture, method, role, valid_role)
| 3,244 | Python | .py | 64 | 46.578125 | 114 | 0.678763 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,333 | test_block_hooks.py | truenas_middleware/tests/api2/test_block_hooks.py | import uuid
import pytest
from middlewared.test.integration.utils import client, mock
@pytest.mark.parametrize("block", [True, False])
def test_block_hooks(block):
hook_name = str(uuid.uuid4())
with mock("test.test1", """
async def mock(self, hook_name, blocked_hooks):
from pathlib import Path
sentinel = Path("/tmp/block_hooks_sentinel")
async def hook(middleware):
sentinel.write_text("")
self.middleware.register_hook(hook_name, hook, blockable=True, sync=True)
sentinel.unlink(missing_ok=True)
with self.middleware.block_hooks(*blocked_hooks):
await self.middleware.call_hook(hook_name)
return sentinel.exists()
"""):
with client() as c:
assert c.call("test.test1", hook_name, [hook_name] if block else []) == (not block)
| 926 | Python | .py | 20 | 35.35 | 95 | 0.625718 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,334 | test_job_credentials.py | truenas_middleware/tests/api2/test_job_credentials.py | from middlewared.test.integration.assets.account import unprivileged_user_client
from middlewared.test.integration.utils import call, mock
from unittest.mock import ANY
def test_job_credentials():
with mock("test.test1", """
from middlewared.service import job
@job()
def mock(self, job, *args):
return 42
"""):
with unprivileged_user_client(allowlist=[{"method": "CALL", "resource": "test.test1"}]) as c:
job_id = c.call("test.test1")
job = call("core.get_jobs", [["id", "=", job_id]], {"get": True})
assert job["credentials"] == {"type": "LOGIN_PASSWORD", "data": {"username": c.username, "login_at": ANY}}
| 706 | Python | .py | 14 | 42.5 | 118 | 0.621543 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,335 | test_cloud_sync_script.py | truenas_middleware/tests/api2/test_cloud_sync_script.py | import pytest
from truenas_api_client import ClientException
from middlewared.test.integration.assets.cloud_sync import local_ftp_task, run_task
from middlewared.test.integration.utils import call, ssh
def test_pre_script_failure():
with local_ftp_task({
"pre_script": "echo Custom error\nexit 123",
}) as task:
with pytest.raises(ClientException) as ve:
run_task(task)
assert ve.value.error == "[EFAULT] Pre-script failed with exit code 123"
job = call("core.get_jobs", [["method", "=", "cloudsync.sync"]], {"order_by": ["-id"], "get": True})
assert job["logs_excerpt"] == "[Pre-script] Custom error\n"
def test_pre_script_ok():
ssh("rm /tmp/cloud_sync_test", check=False)
with local_ftp_task({
"pre_script": "touch /tmp/cloud_sync_test",
}) as task:
run_task(task)
ssh("cat /tmp/cloud_sync_test")
def test_post_script_not_running_after_failure():
ssh("touch /tmp/cloud_sync_test")
with local_ftp_task({
"post_script": "rm /tmp/cloud_sync_test",
}) as task:
call("service.stop", "ftp")
with pytest.raises(ClientException) as ve:
run_task(task)
assert "connection refused" in ve.value.error
ssh("cat /tmp/cloud_sync_test")
def test_post_script_ok():
ssh("rm /tmp/cloud_sync_test", check=False)
with local_ftp_task({
"post_script": "touch /tmp/cloud_sync_test",
}) as task:
run_task(task)
ssh("cat /tmp/cloud_sync_test")
def test_script_shebang():
with local_ftp_task({
"post_script": "#!/usr/bin/env python3\nprint('Test' * 2)",
}) as task:
run_task(task)
job = call("core.get_jobs", [["method", "=", "cloudsync.sync"]], {"order_by": ["-id"], "get": True})
assert job["logs_excerpt"].endswith("[Post-script] TestTest\n")
| 1,876 | Python | .py | 44 | 35.840909 | 108 | 0.627689 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,336 | test_190_filesystem.py | truenas_middleware/tests/api2/test_190_filesystem.py | #!/usr/bin/env python3
# Author: Eric Turgeon
# License: BSD
import errno
import pytest
import stat
import sys
import os
apifolder = os.getcwd()
sys.path.append(apifolder)
from copy import deepcopy
from functions import POST, PUT, SSH_TEST, wait_on_job
from auto_config import pool_name, user, password
from middlewared.service_exception import CallError
from middlewared.test.integration.assets.filesystem import directory
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.utils import call, ssh
from utils import create_dataset
group = 'root'
path = '/etc'
path_list = ['default', 'kernel', 'zfs', 'ssh']
random_path = ['/boot/grub', '/root', '/bin', '/usr/bin']
@pytest.mark.parametrize('path', random_path)
def test_03_get_filesystem_stat_(path):
results = POST('/filesystem/stat/', path)
assert results.status_code == 200, results.text
assert isinstance(results.json(), dict) is True, results.text
assert isinstance(results.json()['size'], int) is True, results.text
assert isinstance(results.json()['mode'], int) is True, results.text
assert results.json()['uid'] == 0, results.text
assert results.json()['gid'] == 0, results.text
assert isinstance(results.json()['atime'], float) is True, results.text
assert isinstance(results.json()['mtime'], float) is True, results.text
assert isinstance(results.json()['ctime'], float) is True, results.text
assert isinstance(results.json()['dev'], int) is True, results.text
assert isinstance(results.json()['inode'], int) is True, results.text
assert results.json()['nlink'] in tuple(range(10)), results.text
assert results.json()['user'] == 'root', results.text
assert results.json()['group'] == group, results.text
assert results.json()['acl'] is False, results.text
def test_04_test_filesystem_statfs_fstype(request):
# test zfs fstype first
parent_path = f'/mnt/{pool_name}'
data = call('filesystem.statfs', parent_path)
assert data['fstype'] == 'zfs', data['fstype']
# mount nested tmpfs entry and make sure statfs
# returns `tmpfs` as the fstype
# mkdir
nested_path = f'{parent_path}/tmpfs'
cmd1 = f'mkdir -p {nested_path}'
results = SSH_TEST(cmd1, user, password)
assert results['result'] is True, results['output']
# mount tmpfs
cmd2 = f'mount -t tmpfs -o size=10M tmpfstest {nested_path}'
results = SSH_TEST(cmd2, user, password)
assert results['result'] is True, results['output']
# test fstype
data = call('filesystem.statfs', nested_path)
assert data['fstype'] == 'tmpfs', data['fstype']
# cleanup
cmd3 = f'umount {nested_path}'
results = SSH_TEST(cmd3, user, password)
assert results['result'] is True, results['output']
cmd4 = f'rmdir {nested_path}'
results = SSH_TEST(cmd4, user, password)
assert results['result'] is True, results['output']
def test_05_set_immutable_flag_on_path(request):
t_path = os.path.join('/mnt', pool_name, 'random_directory_immutable')
t_child_path = os.path.join(t_path, 'child')
with directory(t_path) as d:
for flag_set in (True, False):
call('filesystem.set_immutable', flag_set, d)
# We test 2 things
# 1) Writing content to the parent path fails/succeeds based on "set"
# 2) "is_immutable_set" returns sane response
if flag_set:
with pytest.raises(PermissionError):
call('filesystem.mkdir', f'{t_child_path}_{flag_set}')
else:
call('filesystem.mkdir', f'{t_child_path}_{flag_set}')
is_immutable = call('filesystem.is_immutable', t_path)
assert is_immutable == flag_set, 'Immutable flag is still not set' if flag_set else 'Immutable flag is still set'
def test_06_test_filesystem_listdir_exclude_non_mounts():
# create a random directory at top-level of '/mnt'
mnt = '/mnt/'
randir = 'random_dir'
path = mnt + randir
with directory(path) as _:
# now call filesystem.listdir specifying '/mnt' as path
# and ensure `randir` is not in the output
results = POST('/filesystem/listdir/', {'path': mnt})
assert results.status_code == 200, results.text
assert not any(i['name'] == randir for i in results.json()), f'{randir} should not be listed'
def test_07_test_filesystem_stat_filetype(request):
"""
This test checks that file types are properly
identified through the filesystem plugin in middleware.
There is an additional check to make sure that paths
in the ZFS CTL directory (.zfs) are properly flagged.
"""
ds_name = 'stat_test'
snap_name = f'{ds_name}_snap1'
path = f'/mnt/{pool_name}/{ds_name}'
targets = ['file', 'directory', 'symlink', 'other']
cmds = [
f'mkdir {path}/directory',
f'touch {path}/file',
f'ln -s {path}/file {path}/symlink',
f'mkfifo {path}/other'
]
with create_dataset(f'{pool_name}/{ds_name}'):
results = SSH_TEST(' && '.join(cmds), user, password)
assert results['result'] is True, str(results)
for x in targets:
target = f'{path}/{x}'
statout = call('filesystem.stat', target)
assert statout['type'] == x.upper(), str(statout)
assert not statout['is_ctldir']
call('zfs.snapshot.create', {
'dataset': f'{pool_name}/{ds_name}',
'name': snap_name,
'recursive': False,
})
for x in targets:
target = f'{path}/.zfs/snapshot/{snap_name}/{x}'
statout = call('filesystem.stat', target)
assert statout['type'] == x.upper(), str(statout)
assert statout['is_ctldir']
assert call('filesystem.stat', f'{path}/.zfs/snapshot/{snap_name}')['is_ctldir']
assert all(dirent['is_ctldir'] for dirent in call(
'filesystem.listdir', f'{path}/.zfs/snapshot', [], {'select': ['name', 'is_ctldir']}
))
assert call('filesystem.stat', f'{path}/.zfs/snapshot')['is_ctldir']
assert all(dirent['is_ctldir'] for dirent in call(
'filesystem.listdir', f'{path}/.zfs', [], {'select': ['name', 'is_ctldir']}
))
assert call('filesystem.stat', f'{path}/.zfs')['is_ctldir']
def test_08_test_fiilesystem_statfs_flags(request):
"""
This test verifies that changing ZFS properties via
middleware causes mountinfo changes visible via statfs.
"""
ds_name = 'statfs_test'
target = f'{pool_name}/{ds_name}'
target_url = target.replace('/', '%2F')
path = f'/mnt/{target}'
# tuple: ZFS property name, property value, mountinfo value
properties = [
("readonly", "ON", "RO"),
("readonly", "OFF", "RW"),
("atime", "OFF", "NOATIME"),
("exec", "OFF", "NOEXEC"),
("acltype", "NFSV4", "NFS4ACL"),
("acltype", "POSIX", "POSIXACL"),
]
with create_dataset(target):
for p in properties:
# set option we're checking and make sure it's really set
payload = {
p[0]: p[1]
}
if p[0] == 'acltype':
payload.update({
'aclmode': 'RESTRICTED' if p[1] == 'NFSV4' else 'DISCARD'
})
results = PUT(f'/pool/dataset/id/{target_url}', payload)
assert results.status_code == 200, results.text
prop_out = results.json()[p[0]]
assert prop_out['value'] == p[1]
# check statfs results
results = POST('/filesystem/statfs/', path)
assert results.status_code == 200, results.text
mount_flags = results.json()['flags']
assert p[2] in mount_flags, f'{path}: ({p[2]}) not in {mount_flags}'
def test_09_test_dosmodes():
modes = ['readonly', 'hidden', 'system', 'archive', 'offline', 'sparse']
ds_name = 'dosmode_test'
target = f'{pool_name}/{ds_name}'
path = f'/mnt/{target}'
testpaths = [
f'{path}/testfile',
f'{path}/testdir',
]
with create_dataset(target):
cmd = [
f'touch {testpaths[0]}',
f'mkdir {testpaths[1]}'
]
results = SSH_TEST(' && '.join(cmd), user, password)
assert results['result'] is True, str(results)
for p in testpaths:
expected_flags = call('filesystem.get_zfs_attributes', p)
for m in modes:
to_set = {m: not expected_flags[m]}
res = call('filesystem.set_zfs_attributes', {'path': p, 'zfs_file_attributes': to_set})
expected_flags.update(to_set)
assert expected_flags == res
res = call('filesystem.get_zfs_attributes', p)
assert expected_flags == res
def test_10_acl_path_execute_validation():
ds_name = 'acl_execute_test'
target = f'{pool_name}/{ds_name}'
path = f'/mnt/{target}'
NFSV4_DACL = [
{'tag': 'owner@', 'id': -1, 'type': 'ALLOW', 'perms': {'BASIC': 'FULL_CONTROL'}, 'flags': {'BASIC': 'INHERIT'}},
{'tag': 'group@', 'id': -1, 'type': 'ALLOW', 'perms': {'BASIC': 'FULL_CONTROL'}, 'flags': {'BASIC': 'INHERIT'}},
{'tag': 'USER', 'id': 65534, 'type': 'ALLOW', 'perms': {'BASIC': 'FULL_CONTROL'}, 'flags': {'BASIC': 'INHERIT'}},
{'tag': 'GROUP', 'id': 65534, 'type': 'ALLOW', 'perms': {'BASIC': 'FULL_CONTROL'}, 'flags': {'BASIC': 'INHERIT'}},
]
# Do NFSv4 checks
with create_dataset(target, {'acltype': 'NFSV4', 'aclmode': 'PASSTHROUGH'}, None, 770):
sub_ds_name = f'{ds_name}/sub'
sub_target = f'{pool_name}/{sub_ds_name}'
sub_path = f'/mnt/{sub_target}'
"""
For NFSv4 ACLs four different tags generate user tokens differently:
1) owner@ tag will test `uid` from payload
2) group@ tag will test `gid` from payload
3) GROUP will test the `id` in payload with id_type
4) USER will test the `id` in mayload with USER id_type
"""
# Start with testing denials
with create_dataset(sub_target, {'acltype': 'NFSV4', 'aclmode': 'PASSTHROUGH'}):
acl = deepcopy(NFSV4_DACL)
names = ['daemon', 'apps', 'nobody', 'nogroup']
for idx, entry in enumerate(NFSV4_DACL):
perm_job = POST('/filesystem/setacl/',
{'path': sub_path, "dacl": acl, 'uid': 1, 'gid': 568})
assert perm_job.status_code == 200, perm_job.text
job_status = wait_on_job(perm_job.json(), 180)
# all of these tests should fail
assert job_status['state'] == 'FAILED', str(job_status['results'])
assert names[idx] in job_status['results']['error'], job_status['results']['error']
acl.pop(0)
# when this test starts, we have 770 perms on parent
for entry in NFSV4_DACL:
# first set permissions on parent dataset
if entry['tag'] == 'owner@':
perm_job = POST('/filesystem/chown/', {
'path': path,
'uid': 1,
'gid': 0
})
elif entry['tag'] == 'group@':
perm_job = POST('/filesystem/chown/', {
'path': path,
'uid': 0,
'gid': 568
})
elif entry['tag'] == 'USER':
perm_job = POST('/filesystem/setacl/', {
'path': path,
'uid': 0,
'gid': 0,
'dacl': [entry]
})
elif entry['tag'] == 'GROUP':
perm_job = POST('/filesystem/setacl/', {
'path': path,
'uid': 0,
'gid': 0,
'dacl': [entry]
})
assert perm_job.status_code == 200, perm_job.text
job_status = wait_on_job(perm_job.json(), 180)
assert job_status['state'] == 'SUCCESS', str(job_status['results'])
# Now set the acl on child dataset. This should succeed
perm_job = POST('/filesystem/setacl/', {
'path': sub_path,
'uid': 1,
'gid': 568,
'dacl': [entry]
})
job_status = wait_on_job(perm_job.json(), 180)
assert job_status['state'] == 'SUCCESS', str(job_status['results'])
@pytest.fixture(scope="module")
def file_and_directory():
with dataset("test_file_and_directory") as ds:
ssh(f"mkdir /mnt/{ds}/test-directory")
ssh(f"touch /mnt/{ds}/test-file")
yield ds
@pytest.mark.parametrize("query,result", [
([], {"test-directory", "test-file"}),
([["type", "=", "DIRECTORY"]], {"test-directory"}),
([["type", "!=", "DIRECTORY"]], {"test-file"}),
([["type", "=", "FILE"]], {"test-file"}),
([["type", "!=", "FILE"]], {"test-directory"}),
])
def test_type_filter(file_and_directory, query, result):
listdir = call("filesystem.listdir", f"/mnt/{file_and_directory}", query)
assert {item["name"] for item in listdir} == result, listdir
def test_mkdir_mode():
with dataset("test_mkdir_mode") as ds:
testdir = os.path.join("/mnt", ds, "testdir")
call("filesystem.mkdir", {'path': testdir, 'options': {'mode': '777'}})
st = call("filesystem.stat", testdir)
assert stat.S_IMODE(st["mode"]) == 0o777
def test_mkdir_chmod_failure():
with dataset("test_mkdir_chmod", {"share_type": "SMB"}) as ds:
testdir = os.path.join("/mnt", ds, "testdir")
with pytest.raises(PermissionError):
call("filesystem.mkdir", {'path': testdir, 'options': {'mode': '777'}})
with pytest.raises(CallError) as ce:
call("filesystem.stat", testdir)
assert ce.value.errno == errno.ENOENT
mkdir_st = call("filesystem.mkdir", {'path': testdir, 'options': {'mode': '777', 'raise_chmod_error': False}})
st = call("filesystem.stat", testdir)
# Verify that mode output returned from mkdir matches what was actually set
assert st['mode'] == mkdir_st['mode']
# mkdir succeeded, but chmod failed so we get mode based on inherited ACL (SMB preset)
assert stat.S_IMODE(st["mode"]) == 0o770
| 14,618 | Python | .py | 311 | 37.33119 | 125 | 0.573243 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,337 | test_438_snapshots.py | truenas_middleware/tests/api2/test_438_snapshots.py | from middlewared.test.integration.assets.pool import dataset, snapshot
from auto_config import pool_name
from middlewared.test.integration.utils import call
def _verify_snapshot_keys_present(snap, expected, unexpected):
"""
Verify that the snapshot returned by the query has the expected keys in its dict
and none of the unexpected ones.
:param snap: a dict containing snapshot data
:param expected: a list of strings, expected key names in the dict
:param unexpected: a list of strings, key names that should not be in the dict
"""
assert set(expected).issubset(set(snap.keys())), f"Failed to get all expected keys: {snap.keys()}"
for key in unexpected:
assert key not in snap.keys(), f"Unexpectedly, was returned '{key}'"
def _verify_snapshot_against_config(snap, dataset_id, snap_config):
"""
Verify that the snapshot returned by the query has data that matches the data
returned then the dataset and snapshot were created.
:param snap: a dict containing snapshot data
:param dataset_id: dataset name
:param snap_config: a dict containing the snapshot data (when it was created)
"""
assert snap['pool'] == dataset_id.split('/')[0], f"Incorrect pool: {snap}"
assert snap['name'] == snap_config['name'], f"Incorrect name: {snap}"
assert snap['type'] == "SNAPSHOT", f"Incorrect type: {snap}"
assert snap['snapshot_name'] == snap_config['snapshot_name'], f"Incorrect snapshot_name: {snap}"
assert snap['dataset'] == dataset_id, f"Incorrect dataset: {snap}"
assert snap['id'] == snap_config['id'], f"Incorrect id: {snap}"
assert isinstance(snap['createtxg'], str), f"Incorrect type for createtxg: {snap}"
assert snap['createtxg'] == snap_config['createtxg'], f"Incorrect createtxg: {snap}"
def _verify_snapshot_properties(snap, properties_list):
"""
Verify that the snapshot returned by the query has the expected items in its
'properties' value.
In the case of 'name' and 'createtxg' properties we perform additional checks
as this data should be present twice in snap.
:param snap: a dict containing snapshot data
:param properties_list: a list of strings, key names of properties that should
be present in snap['properties']
"""
for prop in properties_list:
assert prop in snap['properties'], f"Missing property: {prop}"
# Special checking if name requested
if 'name' in properties_list:
assert snap['properties']['name']['value'] == snap['name'], f"Name property does not match {snap['properties']['name']}"
if 'createtxg' in properties_list:
assert snap['properties']['createtxg']['value'] == snap['createtxg'], f"createtxg property does not match {snap['properties']['name']}"
#
# Snapshot query: filter by dataset name
#
def _test_xxx_snapshot_query_filter_dataset(dataset_name, properties_list,
expected_keys = ['pool', 'name', 'type', 'snapshot_name', 'dataset', 'id', 'createtxg'],
unexpected_keys = ['properties']):
"""
Perform snapshot queries, filtered by dataset name.
:param dataset_name: a string, the name of the dataset to be created and used in queries.
:param properties_list: a list of strings, the names to be queried in snapshot properties option
:expected_keys: a list of strings, the key names expected to be present in the snapshot dict
:unexpected_keys: a list of strings, the key names expected NOT to be present in the snapshot dict
"""
with dataset(dataset_name) as dataset_id:
with snapshot(dataset_id, "snap01", get=True) as snap01_config:
payload = {
'query-filters': [["dataset", "=", dataset_id]],
'query-options': {
'extra': {
'properties': properties_list
}
}
}
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
# Check that we have one snap returned and that it has the expected
# data
assert len(snaps) == 1
snap = snaps[0]
_verify_snapshot_keys_present(snap, expected_keys, unexpected_keys)
_verify_snapshot_against_config(snap, dataset_id, snap01_config)
if 'properties' not in unexpected_keys:
_verify_snapshot_properties(snap, properties_list)
# Now create another snapshot and re-issue the query to check the
# new results.
with snapshot(dataset_id, "snap02", get=True) as snap02_config:
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
# Check that we have two snaps returned and that they have the expected
# data.
assert len(snaps) == 2
# Need to sort the snaps by createtxg
ssnaps = sorted(snaps, key=lambda d: int(d['createtxg']))
snap01 = ssnaps[0]
snap02 = ssnaps[1]
_verify_snapshot_keys_present(snap01, expected_keys, unexpected_keys)
_verify_snapshot_against_config(snap01, dataset_id, snap01_config)
_verify_snapshot_keys_present(snap02, expected_keys, unexpected_keys)
_verify_snapshot_against_config(snap02, dataset_id, snap02_config)
if 'properties' not in unexpected_keys:
_verify_snapshot_properties(snap01, properties_list)
_verify_snapshot_properties(snap02, properties_list)
existing_snaps = {snap01['createtxg'], snap02['createtxg']}
# Now create *another* dataset and snapshot and ensure we
# only see the snapshots we're supposed to.
with dataset(f"{dataset_name}2") as dataset2:
with snapshot(dataset2, "snap03", get=True) as snap03_config:
# First issue the original query again & ensure we still have
# the expected snapshots
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
assert len(snaps) == 2
for snap in snaps:
assert snap['createtxg'] in existing_snaps, f"Got unexpected snap: {snap}"
# Next issue the query with a different filter
payload.update({
'query-filters': [["dataset", "=", dataset2]]
})
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
assert len(snaps) == 1
snap = snaps[0]
assert snap['createtxg'] not in existing_snaps, f"Got unexpected snap: {snap}"
new_snaps = {snap['createtxg']}
_verify_snapshot_keys_present(snap, expected_keys, unexpected_keys)
_verify_snapshot_against_config(snap, dataset2, snap03_config)
if 'properties' not in unexpected_keys:
_verify_snapshot_properties(snap, properties_list)
# Next issue the query with a bogus filter
payload.update({
'query-filters': [["dataset", "=", f"{dataset_name}-BOGUS"]]
})
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
assert len(snaps) == 0
# Next issue the query WITHOUT a filter. It's possible
# that this test could be run while other snapshots are
# present, so take that into account during checks, e.g.
# assert count >= 3 rather than == 3
payload.update({
'query-filters': []
})
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
assert len(snaps) >= 3
all_snaps = set([s['createtxg'] for s in snaps])
assert existing_snaps.issubset(all_snaps), "Existing snaps not returned in filterless query"
assert new_snaps.issubset(all_snaps), "New snaps not returned in filterless query"
# Let the snap03 get cleaned up, and then ensure even with a filterless query
# that it is no longer returned.
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
assert len(snaps) >= 2
all_snaps = set([s['createtxg'] for s in snaps])
assert existing_snaps.issubset(all_snaps), "Existing snaps not returned in filterless query"
assert not new_snaps.issubset(all_snaps), "New snaps returned in filterless query"
def _test_simple_snapshot_query_filter_dataset(dataset_name, properties_list):
"""
Perform simple snapshot queries, filtered by dataset name.
:param dataset_name: a string, the name of the dataset to be created and used in queries.
:param properties_list: a list of strings, the names to be queried in snapshot properties option
"""
_test_xxx_snapshot_query_filter_dataset(dataset_name, properties_list,
expected_keys = ['pool', 'name', 'type', 'snapshot_name', 'dataset', 'id', 'createtxg'],
unexpected_keys = ['properties'])
def _test_full_snapshot_query_filter_dataset(dataset_name, properties_list):
"""
Perform non-simple (non fast-path) snapshot queries, filtered by dataset name.
:param dataset_name: a string, the name of the dataset to be created and used in queries.
:param properties_list: a list of strings, the names to be queried in snapshot properties option
"""
_test_xxx_snapshot_query_filter_dataset(dataset_name, properties_list,
['pool', 'name', 'type', 'snapshot_name', 'dataset', 'id', 'createtxg', 'properties'],
[])
def test_01_snapshot_query_filter_dataset_props_name(request):
"""
Test snapshot query, filtered by dataset with properties option: 'name'
The results should be simple (fast-path) without 'properties'.
"""
_test_simple_snapshot_query_filter_dataset("ds-snapshot-simple-query-name", ['name'])
def test_02_snapshot_query_filter_dataset_props_createtxg(request):
"""
Test snapshot query, filtered by dataset with properties option: 'createtxg'
The results should be simple (fast-path) without 'properties'.
"""
_test_simple_snapshot_query_filter_dataset("ds-snapshot-simple-query-createtxg", ['createtxg'])
def test_03_snapshot_query_filter_dataset_props_name_createtxg(request):
"""
Test snapshot query, filtered by dataset with properties option: 'name', 'createtxg'
The results should be simple (fast-path) without 'properties'.
"""
_test_simple_snapshot_query_filter_dataset("ds-snapshot-simple-query-name-createtxg", ['name', 'createtxg'])
_test_simple_snapshot_query_filter_dataset("ds-snapshot-simple-query-createtxg-name", ['createtxg', 'name'])
def test_04_snapshot_query_filter_dataset_props_used(request):
"""
Test snapshot query, filtered by dataset including properties option: 'used'
The results should be regular (NON fast-path) query that returns 'properties'.
"""
_test_full_snapshot_query_filter_dataset("ds-snapshot-simple-query-createtxg", ['used'])
_test_full_snapshot_query_filter_dataset("ds-snapshot-simple-query-createtxg", ['used', 'name'])
_test_full_snapshot_query_filter_dataset("ds-snapshot-simple-query-createtxg", ['used', 'name', 'createtxg'])
_test_full_snapshot_query_filter_dataset("ds-snapshot-simple-query-createtxg", ['used', 'createtxg'])
#
# Snapshot query: filter by snapshot name
#
def _test_xxx_snapshot_query_filter_snapshot(dataset_name, properties_list, expected_keys, unexpected_keys):
"""
Perform snapshot queries, filtered by snapshot name.
:param dataset_name: a string, the name of the dataset to be created and used in queries.
:param properties_list: a list of strings, the names to be queried in snapshot properties option
:expected_keys: a list of strings, the key names expected to be present in the snapshot dict
:unexpected_keys: a list of strings, the key names expected NOT to be present in the snapshot dict
"""
with dataset(dataset_name) as dataset_id:
with snapshot(dataset_id, "snap01", get=True) as snap01_config:
with snapshot(dataset_id, "snap02", get=True) as snap02_config:
# Query snap01
payload = {
'query-filters': [['name', '=', snap01_config['name']]],
'query-options': {
'extra': {
'properties': properties_list
}
}
}
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
# Check that we have one snap returned and that it has the expected
# data
assert len(snaps) == 1
snap = snaps[0]
_verify_snapshot_keys_present(snap, expected_keys, unexpected_keys)
_verify_snapshot_against_config(snap, dataset_id, snap01_config)
if 'properties' not in unexpected_keys:
_verify_snapshot_properties(snap, properties_list)
# Query snap02
payload = {
'query-filters': [['name', '=', snap02_config['name']]],
'query-options': {
'extra': {
'properties': properties_list
}
}
}
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
# Check that we have one snap returned and that it has the expected
# data
assert len(snaps) == 1
snap = snaps[0]
_verify_snapshot_keys_present(snap, expected_keys, unexpected_keys)
_verify_snapshot_against_config(snap, dataset_id, snap02_config)
if 'properties' not in unexpected_keys:
_verify_snapshot_properties(snap, properties_list)
# Allow snap02 to be destroyed, then query again to make sure we don't get it
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
assert len(snaps) == 0
def _test_simple_snapshot_query_filter_snapshot(dataset_name, properties_list):
"""
Perform simple snapshot queries, filtered by snapshot name.
:param dataset_name: a string, the name of the dataset to be created and used in queries.
:param properties_list: a list of strings, the names to be queried in snapshot properties option
"""
_test_xxx_snapshot_query_filter_snapshot(dataset_name, properties_list,
expected_keys = ['pool', 'name', 'type', 'snapshot_name', 'dataset', 'id', 'createtxg'],
unexpected_keys = ['properties'])
def _test_full_snapshot_query_filter_snapshot(dataset_name, properties_list):
"""
Perform non-simple (non fast-path) snapshot queries, filtered by snapshot name.
:param dataset_name: a string, the name of the dataset to be created and used in queries.
:param properties_list: a list of strings, the names to be queried in snapshot properties option
"""
_test_xxx_snapshot_query_filter_snapshot(dataset_name, properties_list,
['pool', 'name', 'type', 'snapshot_name', 'dataset', 'id', 'createtxg', 'properties'],
[])
def test_05_snapshot_query_filter_snapshot_props_name(request):
"""
Test snapshot query, filtered by snapshot with properties option: 'name'
The results should be simple (fast-path) without 'properties'.
"""
_test_simple_snapshot_query_filter_snapshot("ds-snapshot-simple-query-name", ['name'])
def test_06_snapshot_query_filter_snapshot_props_createtxg(request):
"""
Test snapshot query, filtered by snapshot with properties option: 'createtxg'
The results should be simple (fast-path) without 'properties'.
"""
_test_simple_snapshot_query_filter_snapshot("ds-snapshot-simple-query-createtxg", ['createtxg'])
def test_07_snapshot_query_filter_snapshot_props_name_createtxg(request):
"""
Test snapshot query, filtered by snapshot with properties option: 'name', 'createtxg'
The results should be simple (fast-path) without 'properties'.
"""
_test_simple_snapshot_query_filter_snapshot("ds-snapshot-simple-query-name-createtxg", ['name', 'createtxg'])
_test_simple_snapshot_query_filter_snapshot("ds-snapshot-simple-query-createtxg-name", ['createtxg', 'name'])
def test_08_snapshot_query_filter_snapshot_props_used(request):
"""
Test snapshot query, filtered by snapshot including properties option: 'used'
The results should be regular (NON fast-path) query that returns 'properties'.
"""
_test_full_snapshot_query_filter_snapshot("ds-snapshot-simple-query-createtxg", ['used'])
_test_full_snapshot_query_filter_snapshot("ds-snapshot-simple-query-createtxg", ['used', 'name'])
_test_full_snapshot_query_filter_snapshot("ds-snapshot-simple-query-createtxg", ['used', 'name', 'createtxg'])
_test_full_snapshot_query_filter_snapshot("ds-snapshot-simple-query-createtxg", ['used', 'createtxg'])
#
# Snapshot query: filter by pool name
#
def _test_xxx_snapshot_query_filter_pool(dataset_name, properties_list, expected_keys, unexpected_keys):
"""
Perform snapshot queries, filtered by pool name.
:param dataset_name: a string, the name of the dataset to be created and used in queries.
:param properties_list: a list of strings, the names to be queried in snapshot properties option
:expected_keys: a list of strings, the key names expected to be present in the snapshot dict
:unexpected_keys: a list of strings, the key names expected NOT to be present in the snapshot dict
"""
with dataset(dataset_name) as dataset_id:
# Before we create any snapshots for this test, query snapshots
payload = {
'query-filters': [['pool', '=', pool_name]],
'query-options': {
'extra': {
'properties': properties_list
}
}
}
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
original_snap_count = len(snaps)
with snapshot(dataset_id, "snap01", get=True) as snap01_config:
with snapshot(dataset_id, "snap02", get=True) as snap02_config:
# Query again
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
# Check that we have two additional snap returned and that
# they have the expected data
assert len(snaps) == original_snap_count+2
ssnaps = sorted(snaps, key=lambda d: int(d['createtxg']))
snap01 = ssnaps[-2]
snap02 = ssnaps[-1]
_verify_snapshot_keys_present(snap01, expected_keys, unexpected_keys)
_verify_snapshot_against_config(snap01, dataset_id, snap01_config)
_verify_snapshot_keys_present(snap02, expected_keys, unexpected_keys)
_verify_snapshot_against_config(snap02, dataset_id, snap02_config)
if 'properties' not in unexpected_keys:
_verify_snapshot_properties(snap01, properties_list)
_verify_snapshot_properties(snap02, properties_list)
# Allow snap02 to be destroyed & query again.
snaps = call("zfs.snapshot.query", payload["query-filters"], payload["query-options"])
assert len(snaps) == original_snap_count+1
ssnaps = sorted(snaps, key=lambda d: int(d['createtxg']))
snap01 = ssnaps[-1]
_verify_snapshot_keys_present(snap01, expected_keys, unexpected_keys)
_verify_snapshot_against_config(snap01, dataset_id, snap01_config)
if 'properties' not in unexpected_keys:
_verify_snapshot_properties(snap01, properties_list)
def _test_simple_snapshot_query_filter_pool(dataset_name, properties_list):
"""
Perform simple snapshot queries, filtered by pool name.
:param dataset_name: a string, the name of the dataset to be created and used in queries.
:param properties_list: a list of strings, the names to be queried in snapshot properties option
"""
_test_xxx_snapshot_query_filter_pool(dataset_name, properties_list,
expected_keys = ['pool', 'name', 'type', 'snapshot_name', 'dataset', 'id', 'createtxg'],
unexpected_keys = ['properties'])
def _test_full_snapshot_query_filter_pool(dataset_name, properties_list):
"""
Perform non-simple (non fast-path) snapshot queries, filtered by pool name.
:param dataset_name: a string, the name of the dataset to be created and used in queries.
:param properties_list: a list of strings, the names to be queried in snapshot properties option
"""
_test_xxx_snapshot_query_filter_pool(dataset_name, properties_list,
['pool', 'name', 'type', 'snapshot_name', 'dataset', 'id', 'createtxg', 'properties'],
[])
def test_09_snapshot_query_filter_pool_props_name(request):
"""
Test snapshot query, filtered by pool with properties option: 'name'
The results should be simple (fast-path) without 'properties'.
"""
_test_simple_snapshot_query_filter_pool("ds-snapshot-simple-query-name", ['name'])
def test_10_snapshot_query_filter_pool_props_createtxg(request):
"""
Test snapshot query, filtered by pool with properties option: 'createtxg'
The results should be simple (fast-path) without 'properties'.
"""
_test_simple_snapshot_query_filter_pool("ds-snapshot-simple-query-createtxg", ['createtxg'])
def test_11_snapshot_query_filter_pool_props_name_createtxg(request):
"""
Test snapshot query, filtered by pool with properties option: 'name', 'createtxg'
The results should be simple (fast-path) without 'properties'.
"""
_test_simple_snapshot_query_filter_pool("ds-snapshot-simple-query-name-createtxg", ['name', 'createtxg'])
_test_simple_snapshot_query_filter_pool("ds-snapshot-simple-query-createtxg-name", ['createtxg', 'name'])
def test_12_snapshot_query_filter_pool_props_used(request):
"""
Test snapshot query, filtered by pool including properties option: 'used'
The results should be regular (NON fast-path) query that returns 'properties'.
"""
_test_full_snapshot_query_filter_pool("ds-snapshot-simple-query-createtxg", ['used'])
_test_full_snapshot_query_filter_pool("ds-snapshot-simple-query-createtxg", ['used', 'name'])
_test_full_snapshot_query_filter_pool("ds-snapshot-simple-query-createtxg", ['used', 'name', 'createtxg'])
_test_full_snapshot_query_filter_pool("ds-snapshot-simple-query-createtxg", ['used', 'createtxg'])
| 23,528 | Python | .py | 386 | 50.054404 | 143 | 0.642476 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,338 | test_disk_wipe.py | truenas_middleware/tests/api2/test_disk_wipe.py | import time
import pytest
from auto_config import ha
from middlewared.test.integration.utils import call, ssh
VMFS_MAGIC_STRING_B64 = "DdABwA=="
VMFS_MAGIC_STRING_WFS = "VMFS_volume_member"
def test_disk_wipe_partition_clean():
"""Confirm we clean up around the middle partitions"""
signal_msg = "ix private data"
disk = call("disk.get_unused")[0]["name"]
# Create a data partition
call('disk.format', disk)
parts = call('disk.list_partitions', disk)
seek_blk = parts[0]['start_sector']
blk_size = parts[0]['start'] // parts[0]['start_sector']
# Fake a VMFS volume at start of disk
ssh(
f'echo -n {VMFS_MAGIC_STRING_B64} > vmfs;'
f"base64 -d vmfs | dd of=/dev/{disk} bs=1M seek=1 count=1 status=none"
)
assert VMFS_MAGIC_STRING_WFS in ssh(f"wipefs /dev/{disk}")
# Write some private data into the start of the data partition
ssh(
f"echo '{signal_msg}' > junk;"
f"dd if=junk bs={blk_size} count=1 oseek={seek_blk} of=/dev/{disk};"
"rm -f junk"
)
# Confirm presence of signal_message
readback_presence = ssh(f"dd if=/dev/{disk} bs={blk_size} iseek={seek_blk} count=1").splitlines()[0]
assert signal_msg in readback_presence
# Clean the drive
call('disk.wipe', disk, 'QUICK', job=True)
# Confirm it's now clean
assert VMFS_MAGIC_STRING_WFS not in ssh(f"wipefs /dev/{disk}")
readback_clean = ssh(f"dd if=/dev/{disk} bs={blk_size} iseek={seek_blk} count=1").splitlines()[0]
assert signal_msg not in readback_clean
# Confirm we have no partitions from middleware
partitions = call('disk.list_partitions', disk)
assert len(partitions) == 0
# Confirm the kernel partition tables indicate no partitions
proc_partitions = str(ssh('cat /proc/partitions'))
# If the wipe is truly successful /proc/partitions should have a singular
# entry for 'disk' in the table
assert len([line for line in proc_partitions.splitlines() if disk in line]) == 1
@pytest.mark.parametrize('dev_name', ['BOOT', 'UNUSED', 'bogus', ''])
def test_disk_get_partitions_quick(dev_name):
"""
dev_name:
'BOOT' - find a proper device that has partitions
'UNUSED' - find a proper device that does not have partitons
All others are failure tests. All failures are properly handled
and should return an empty dictionary
"""
has_partitions = False
if 'BOOT' == dev_name:
dev_name = call('boot.get_disks')[0]
has_partitions = True
elif 'UNUSED' == dev_name:
# NOTE: 'unused' disks typically have no partitions
dev_name = call('disk.get_unused')[0]['name']
parts = call('disk.get_partitions_quick', dev_name)
assert has_partitions == (len(parts) > 0)
def test_disk_wipe_abort():
"""Test that we can sucessfully abort a disk.wipe job"""
expected_pids = set()
if ha:
# In HA systems fenced may be using the disk. Obtain the PID
# so that we can ignore it.
fenced_info = call('failover.fenced.run_info')
if fenced_info['running']:
expected_pids.add(str(fenced_info['pid']))
# Obtain a disk to wipe
disk = call("disk.get_unused")[0]["name"]
job_id = call("disk.wipe", disk, "FULL")
# Wait for wipe process to actually start
for i in range(20):
job = call("core.get_jobs", [["id", "=", job_id]], {"get": True})
if job["progress"]["percent"] > 0:
break
time.sleep(0.1)
else:
assert False, job
call("core.job_abort", job_id)
for i in range(20):
result = set(ssh(f"fuser /dev/{disk}", check=False).strip().split())
# Check that only the expected PIDs are using the disk
# (which means that the abort was completed successfully)
if result == expected_pids:
# Ensure that the job was aborted before completion
job = call("core.get_jobs", [["id", "=", job_id]], {"get": True})
assert job["state"] == "ABORTED"
assert job["progress"]["percent"] < 95
break
time.sleep(0.1)
else:
assert False, result
| 4,168 | Python | .py | 96 | 36.947917 | 104 | 0.638745 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,339 | test_ipa_join.py | truenas_middleware/tests/api2/test_ipa_join.py | import pytest
from middlewared.test.integration.assets.directory_service import ipa, FREEIPA_ADMIN_BINDPW
from middlewared.test.integration.assets.product import product_type
from middlewared.test.integration.utils import call, client
from middlewared.test.integration.utils.client import truenas_server
@pytest.fixture(scope="module")
def do_freeipa_connection():
with ipa() as config:
yield config
@pytest.fixture(scope="function")
def override_product():
if truenas_server.server_type == 'ENTERPRISE_HA':
yield
else:
with product_type():
yield
@pytest.fixture(scope="function")
def enable_ds_auth(override_product):
sys_config = call('system.general.update', {'ds_auth': True})
try:
yield sys_config
finally:
call('system.general.update', {'ds_auth': False})
def test_setup_and_enabling_freeipa(do_freeipa_connection):
config = do_freeipa_connection
ds = call('directoryservices.status')
assert ds['type'] == 'IPA'
assert ds['status'] == 'HEALTHY'
alerts = [alert['klass'] for alert in call('alert.list')]
# There's a one-shot alert that gets fired if we are an IPA domain
# connected via legacy mechanism.
assert 'IPALegacyConfiguration' not in alerts
assert config['kerberos_realm'], str(config)
assert config['kerberos_principal'], str(config)
# our kerberos principal should be the host one (not SMB or NFS)
assert config['kerberos_principal'].startswith('host/')
def test_accounts_cache(do_freeipa_connection):
ipa_users_cnt = call('user.query', [['local', '=', False]], {'count': True})
assert ipa_users_cnt != 0
ipa_groups_cnt = call('group.query', [['local', '=', False]], {'count': True})
assert ipa_groups_cnt != 0
@pytest.mark.parametrize('keytab_name', [
'IPA_MACHINE_ACCOUNT',
'IPA_NFS_KEYTAB',
'IPA_SMB_KEYTAB'
])
def test_keytabs_exist(do_freeipa_connection, keytab_name):
call('kerberos.keytab.query', [['name', '=', keytab_name]], {'get': True})
def test_check_kerberos_ticket(do_freeipa_connection):
tkt = call('kerberos.check_ticket')
assert tkt['name_type'] == 'KERBEROS_PRINCIPAL'
assert tkt['name'].startswith(do_freeipa_connection['kerberos_principal'])
def test_certificate(do_freeipa_connection):
call('certificateauthority.query', [['name', '=', 'IPA_DOMAIN_CACERT']], {'get': True})
def test_system_keytab_has_nfs_principal(do_freeipa_connection):
assert call('kerberos.keytab.has_nfs_principal')
def test_smb_keytab_exists(do_freeipa_connection):
call('filesystem.stat', '/etc/ipa/smb.keytab')
def test_admin_privilege(do_freeipa_connection, enable_ds_auth):
ipa_config = call('ldap.ipa_config')
priv_names = [priv['name'] for priv in call('privilege.query')]
assert ipa_config['domain'].upper() in priv_names
priv = call('privilege.query', [['name', '=', ipa_config['domain'].upper()]], {'get': True})
admins_grp = call('group.get_group_obj', {'groupname': 'admins', 'sid_info': True})
assert len(priv['ds_groups']) == 1
assert priv['ds_groups'][0]['gid'] == admins_grp['gr_gid']
assert priv['ds_groups'][0]['sid'] == admins_grp['sid']
assert priv['roles'] == ['FULL_ADMIN']
with client(auth=('ipaadmin', FREEIPA_ADMIN_BINDPW)) as c:
me = c.call('auth.me')
assert 'DIRECTORY_SERVICE' in me['account_attributes']
assert 'LDAP' in me['account_attributes']
assert me['privilege']['roles'] == set(priv['roles'])
def test_dns_resolution(do_freeipa_connection):
ipa_config = do_freeipa_connection['ipa_config']
addresses = call('dnsclient.forward_lookup', {'names': [ipa_config['host']]})
assert len(addresses) != 0
| 3,745 | Python | .py | 77 | 43.701299 | 96 | 0.689722 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,340 | test_disk_format.py | truenas_middleware/tests/api2/test_disk_format.py | import json
import time
from middlewared.test.integration.utils import call, ssh
"""
We use 'parted' to partition disks.
Verification is based on 'parted' documentation (https://people.redhat.com/msnitzer/docs/io-limits.txt):
The heuristic parted uses is:
1) Always use the reported 'alignment_offset' as the offset for the
start of the first primary partition.
2a) If 'optimal_io_size' is defined (not 0) align all partitions on an
'optimal_io_size' boundary.
2b) If 'optimal_io_size' is undefined (0) and 'alignment_offset' is 0
and 'minimum_io_size' is a power of 2: use a 1MB default alignment.
- as you can see this is the catch all for "legacy" devices which
don't appear to provide "I/O hints"; so in the default case all
partitions will align on a 1MB boundary.
- NOTE: we can't distinguish between a "legacy" device and modern
device that provides "I/O hints" with alignment_offset=0 and
optimal_io_size=0. Such a device might be a single SAS 4K device.
So worst case we lose < 1MB of space at the start of the disk.
"""
# Some 'constants'
MBR_SECTOR_GAP = 34
ONE_MB = 1048576
DATA_TYPE_UUID = "6a898cc3-1dd2-11b2-99a6-080020736631"
def get_parted_info(disk_path):
# By the time this is called, the disk has been formatted
# but the kernel might not have been made fully aware of the changes
# so let's retry a bit before failing
for i in range(10):
pbytes = json.loads(ssh(f'parted {disk_path} unit b p --json'))['disk']
if pbytes.get('partitions') is None:
time.sleep(1)
else:
break
else:
assert False, f'parted tool failed to find partitions (in bytes) on {disk_path!r} ({pbytes!r})'
for i in range(10):
psectors = json.loads(ssh(f'parted {disk_path} unit s p --json'))['disk']
if psectors.get('partitions') is None:
time.sleep(1)
else:
break
else:
assert False, f'parted tool failed to find partitions (in sectors) on {disk_path!r} ({psectors!r})'
return pbytes, psectors
def test_disk_format_and_wipe():
"""Generate a single data partition"""
# get an unused disk and format it
unused = call('disk.get_unused')
assert unused, 'Need at least 1 unused disk'
call('disk.format', unused[0]['name'])
partitions = call('disk.list_partitions', unused[0]['name'])
assert partitions, partitions
# The first and only partition should be data
assert len(partitions) == 1, partitions
partition = partitions[0]
assert partition['partition_type'] == DATA_TYPE_UUID
# we used libparted to format a drive so let's
# validate our API matches parted output (NOTE:
# we check both bytes and sectors)
parted_bytes, parted_sectors = get_parted_info(f'/dev/{unused[0]["name"]}')
# sanity check (make sure parted shows same number of partitions)
assert len(parted_bytes['partitions']) == len(partitions), parted_bytes['partitions']
assert len(parted_sectors['partitions']) == len(partitions), parted_sectors['partitions']
# validate our API shows proper start/end sizes in bytes
pbyte = parted_bytes['partitions'][0]
assert int(pbyte['size'].split('B')[0]) == partition['size']
assert int(pbyte['start'].split('B')[0]) == partition['start']
assert int(pbyte['end'].split('B')[0]) == partition['end']
# validate our API shows proper start/end sizes in sectors
psect = parted_sectors['partitions'][0]
assert int(psect['start'].split('s')[0]) == partition['start_sector']
assert int(psect['end'].split('s')[0]) == partition['end_sector']
# verify wipe disk should removes partition labels
call('disk.wipe', partition['disk'], 'QUICK', job=True)
# the partitions are removed
new_parts = call('disk.list_partitions', partition['disk'])
assert len(new_parts) == 0, new_parts
# sanity check, make sure parted doesn't see partitions either
pbytes = json.loads(ssh(f'parted /dev/{unused[0]["name"]} unit b p --json'))['disk']
assert pbytes.get('partitions') is None, repr(pbytes)
| 4,169 | Python | .py | 82 | 44.902439 | 107 | 0.676572 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,341 | test_staticroutes.py | truenas_middleware/tests/api2/test_staticroutes.py | import pytest
from middlewared.service_exception import ValidationErrors
from middlewared.test.integration.utils import call, ssh
ROUTE = {
"destination": "127.1.1.1",
"gateway": "127.0.0.1",
"description": "Test Route",
}
BAD_ROUTE = {"destination": "fe80:aaaa:bbbb:cccc::1/64", "gateway": ROUTE["gateway"]}
def test_staticroute():
"""
1. try to create invalid route
2. create valid route
3. validate route was added to OS
4. try to update valid route with invalid data
5. delete route
6. validate route was removed from OS
"""
# try to create bad route
with pytest.raises(ValidationErrors):
call("staticroute.create", BAD_ROUTE)
# now create valid one
id_ = call("staticroute.create", ROUTE)["id"]
# validate query
qry = call("staticroute.query", [["id", "=", id_]], {"get": True})
assert ROUTE["destination"] in qry["destination"]
assert ROUTE["gateway"] == qry["gateway"]
assert ROUTE["description"] == qry["description"]
# validate route was added to OS
results = ssh(f"ip route show {ROUTE['destination']}", complete_response=True)
assert f"{ROUTE['destination']} via {ROUTE['gateway']}" in results["stdout"]
# update it with bad data
with pytest.raises(ValidationErrors):
call("staticroute.update", id_, {"destination": BAD_ROUTE["destination"]})
# now delete
assert call("staticroute.delete", id_)
assert not call("staticroute.query", [["id", "=", id_]])
# validate route was removed from OS
results = ssh(
f"ip route show {ROUTE['destination']}", complete_response=True, check=False
)
assert ROUTE["destination"] not in results["stdout"]
| 1,709 | Python | .py | 42 | 35.833333 | 85 | 0.671696 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,342 | test_iscsi_auth_crud_roles.py | truenas_middleware/tests/api2/test_iscsi_auth_crud_roles.py | import pytest
from middlewared.test.integration.assets.roles import common_checks
@pytest.mark.parametrize("role", ["SHARING_READ", "SHARING_ISCSI_READ", "SHARING_ISCSI_AUTH_READ"])
def test_read_role_can_read(unprivileged_user_fixture, role):
common_checks(unprivileged_user_fixture, "iscsi.auth.query", role, True, valid_role_exception=False)
@pytest.mark.parametrize("role", ["SHARING_READ", "SHARING_ISCSI_READ", "SHARING_ISCSI_AUTH_READ"])
def test_read_role_cant_write(unprivileged_user_fixture, role):
common_checks(unprivileged_user_fixture, "iscsi.auth.create", role, False)
common_checks(unprivileged_user_fixture, "iscsi.auth.update", role, False)
common_checks(unprivileged_user_fixture, "iscsi.auth.delete", role, False)
@pytest.mark.parametrize("role", ["SHARING_WRITE", "SHARING_ISCSI_WRITE", "SHARING_ISCSI_AUTH_WRITE"])
def test_write_role_can_write(unprivileged_user_fixture, role):
common_checks(unprivileged_user_fixture, "iscsi.auth.create", role, True)
common_checks(unprivileged_user_fixture, "iscsi.auth.update", role, True)
common_checks(unprivileged_user_fixture, "iscsi.auth.delete", role, True)
| 1,158 | Python | .py | 15 | 73.866667 | 104 | 0.767606 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,343 | test_344_acl_templates.py | truenas_middleware/tests/api2/test_344_acl_templates.py | #!/usr/bin/env python3
import pytest
import sys
import os
from pytest_dependency import depends
apifolder = os.getcwd()
sys.path.append(apifolder)
from functions import POST, GET, PUT, DELETE
from auto_config import pool_name
@pytest.mark.dependency(name="ACLTEMPLATE_DATASETS_CREATED")
@pytest.mark.parametrize('acltype', ['NFSV4', 'POSIX'])
def test_01_create_test_datasets(request, acltype):
"""
Setup of datasets for testing templates.
This test shouldn't fail unless pool.dataset endpoint is
thoroughly broken.
"""
result = POST(
'/pool/dataset/', {
'name': f'{pool_name}/acltemplate_{acltype.lower()}',
'acltype': acltype,
'aclmode': 'DISCARD' if acltype == 'POSIX' else 'PASSTHROUGH'
}
)
assert result.status_code == 200, result.text
@pytest.mark.parametrize('acltype', ['NFSV4', 'POSIX'])
def test_02_check_builtin_types_by_path(request, acltype):
"""
This test verifies that we can query builtins by paths, and
that the acltype of the builtins matches that of the
underlying path.
"""
depends(request, ["ACLTEMPLATE_DATASETS_CREATED"], scope="session")
expected_acltype = 'POSIX1E' if acltype == 'POSIX' else 'NFS4'
payload = {
'path': f'/mnt/{pool_name}/acltemplate_{acltype.lower()}',
}
results = POST('/filesystem/acltemplate/by_path', payload)
assert results.status_code == 200, results.text
for entry in results.json():
assert entry['builtin'], results.text
assert entry['acltype'] == expected_acltype, results.text
payload['format-options'] = {
'resolve_names': True,
'ensure_builtins': True
}
results = POST('/filesystem/acltemplate/by_path', payload)
assert results.status_code == 200, results.text
for entry in results.json():
for ace in entry['acl']:
if ace['tag'] not in ('USER_OBJ', 'GROUP_OBJ', 'USER', 'GROUP'):
continue
assert ace.get('who') is not None, results.text
@pytest.mark.dependency(name="NEW_ACLTEMPLATES_CREATED")
@pytest.mark.parametrize('acltype', ['NFS4', 'POSIX'])
def test_03_create_new_template(request, acltype):
"""
This method queries an existing builtin and creates a
new acltemplate based on the data. Test of new ACL template
insertion.
"""
depends(request, ["ACLTEMPLATE_DATASETS_CREATED"], scope="session")
results = GET(
'/filesystem/acltemplate', payload={
'query-filters': [['name', '=', f'{acltype}_RESTRICTED']],
'query-options': {'get': True},
}
)
assert results.status_code == 200, results.text
acl = results.json()['acl']
for entry in acl:
if entry['id'] is None:
entry['id'] = -1
payload = {
'name': f'{acltype}_TEST',
'acl': acl,
'acltype': results.json()['acltype']
}
results = POST('/filesystem/acltemplate', payload)
assert results.status_code == 200, results.text
@pytest.mark.dependency(name="NEW_ACLTEMPLATES_UPDATED")
@pytest.mark.parametrize('acltype', ['NFS4', 'POSIX'])
def test_09_update_new_template(request, acltype):
"""
Rename the template we created to validated that `update`
method works.
"""
depends(request, ["NEW_ACLTEMPLATES_CREATED"], scope="session")
results = GET(
'/filesystem/acltemplate', payload={
'query-filters': [['name', '=', f'{acltype}_TEST']],
'query-options': {'get': True},
}
)
assert results.status_code == 200, results.text
payload = results.json()
id = payload.pop('id')
payload.pop('builtin')
payload['name'] = f'{payload["name"]}2'
results = PUT(f'/filesystem/acltemplate/id/{id}/', payload)
assert results.status_code == 200, results.text
@pytest.mark.parametrize('acltype', ['NFS4', 'POSIX'])
def test_10_delete_new_template(request, acltype):
depends(request, ["NEW_ACLTEMPLATES_UPDATED"], scope="session")
results = GET(
'/filesystem/acltemplate', payload={
'query-filters': [['name', '=', f'{acltype}_TEST2']],
'query-options': {'get': True},
}
)
assert results.status_code == 200, results.text
results = DELETE(f'/filesystem/acltemplate/id/{results.json()["id"]}')
assert results.status_code == 200, results.text
def test_40_knownfail_builtin_delete(request):
results = GET(
'/filesystem/acltemplate', payload={
'query-filters': [['builtin', '=', True]],
'query-options': {'get': True},
}
)
assert results.status_code == 200, results.text
id = results.json()['id']
results = DELETE(f'/filesystem/acltemplate/id/{id}')
assert results.status_code == 422, results.text
def test_41_knownfail_builtin_update(request):
results = GET(
'/filesystem/acltemplate', payload={
'query-filters': [['builtin', '=', True]],
'query-options': {'get': True},
}
)
assert results.status_code == 200, results.text
payload = results.json()
id = payload.pop('id')
payload.pop('builtin')
payload['name'] = 'CANARY'
results = PUT(f'/filesystem/acltemplate/id/{id}/', payload)
assert results.status_code == 422, results.text
@pytest.mark.parametrize('acltype', ['NFSV4', 'POSIX'])
def test_50_delete_test1_dataset(request, acltype):
depends(request, ["ACLTEMPLATE_DATASETS_CREATED"], scope="session")
dataset_name = f'{pool_name}/acltemplate_{acltype.lower()}'
results = DELETE(f'/pool/dataset/id/{dataset_name.replace("/", "%2F")}/')
assert results.status_code == 200, results.text
| 5,695 | Python | .py | 144 | 33.472222 | 77 | 0.642572 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,344 | test_audit_nfs.py | truenas_middleware/tests/api2/test_audit_nfs.py | import pytest
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.utils import call
from middlewared.test.integration.utils.audit import expect_audit_method_calls
@pytest.fixture(scope='module')
def nfs_audit_dataset(request):
with dataset('audit-test-nfs') as ds:
try:
yield ds
finally:
pass
def test_nfs_config_audit():
'''
Test the auditing of NFS configuration changes
'''
bogus_user = 'bogus_user'
bogus_password = 'boguspassword123'
initial_nfs_config = call('nfs.config')
try:
# UPDATE
payload = {
'mountd_log': not initial_nfs_config['mountd_log'],
'mountd_port': 618,
'protocols': ["NFSV4"]
}
with expect_audit_method_calls([{
'method': 'nfs.update',
'params': [payload],
'description': 'Update NFS configuration',
}]):
call('nfs.update', payload)
finally:
# Restore initial state
restore_payload = {
'mountd_log': initial_nfs_config['mountd_log'],
'mountd_port': initial_nfs_config['mountd_port'],
'protocols': initial_nfs_config['protocols']
}
call('nfs.update', restore_payload)
def test_nfs_share_audit(nfs_audit_dataset):
'''
Test the auditing of NFS share operations
'''
nfs_export_path = f"/mnt/{nfs_audit_dataset}"
try:
# CREATE
payload = {
"comment": "My Test Share",
"path": nfs_export_path,
"security": ["SYS"]
}
with expect_audit_method_calls([{
'method': 'sharing.nfs.create',
'params': [payload],
'description': f'NFS share create {nfs_export_path}',
}]):
share_config = call('sharing.nfs.create', payload)
# UPDATE
payload = {
"security": []
}
with expect_audit_method_calls([{
'method': 'sharing.nfs.update',
'params': [
share_config['id'],
payload,
],
'description': f'NFS share update {nfs_export_path}',
}]):
share_config = call('sharing.nfs.update', share_config['id'], payload)
finally:
if share_config is not None:
# DELETE
id_ = share_config['id']
with expect_audit_method_calls([{
'method': 'sharing.nfs.delete',
'params': [id_],
'description': f'NFS share delete {nfs_export_path}',
}]):
call('sharing.nfs.delete', id_)
| 2,682 | Python | .py | 80 | 23.9625 | 82 | 0.548325 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,345 | test_twofactor_auth.py | truenas_middleware/tests/api2/test_twofactor_auth.py | #!/usr/bin/env python3
import contextlib
import errno
import os
import sys
import pytest
apifolder = os.getcwd()
sys.path.append(apifolder)
from middlewared.service_exception import CallError
from middlewared.test.integration.assets.account import user as user_create
from middlewared.test.integration.assets.two_factor_auth import enabled_twofactor_auth, get_user_secret, get_2fa_totp_token
from middlewared.test.integration.assets.account import unprivileged_user
from middlewared.test.integration.utils import call, client
TEST_USERNAME = 'test2fauser'
TEST_USERNAME_2 = 'test2fauser2'
TEST_PASSWORD = 'testpassword'
TEST_PASSWORD_2 = 'testpassword2'
TEST_GID = 544
TEST_TWOFACTOR_INTERVAL = {'interval': 60}
USERS_2FA_CONF = {
TEST_USERNAME: {'interval': 30, 'otp_digits': 6},
TEST_USERNAME_2: {'interval': 40, 'otp_digits': 7}
}
@contextlib.contextmanager
def user(data: dict):
data['group'] = call('group.query', [['gid', '=', TEST_GID]], {'get': True})['id']
with user_create(data) as user_obj:
yield user_obj
@pytest.fixture(scope='function')
def clear_ratelimit():
call('rate.limit.cache_clear')
def do_login(username, password, otp=None, expected=True):
with client(auth=None) as c:
resp = c.call('auth.login_ex', {
'mechanism': 'PASSWORD_PLAIN',
'username': username,
'password': password,
})
if not otp and expected:
assert resp['response_type'] == 'SUCCESS'
elif not otp and not expected:
assert resp['response_type'] in ('AUTH_ERR', 'OTP_REQUIRED')
else:
assert resp['response_type'] == 'OTP_REQUIRED'
if not otp:
return
resp = c.call('auth.login_ex_continue', {
'mechanism': 'OTP_TOKEN',
'otp_token': otp
})
if expected:
assert resp['response_type'] == 'SUCCESS'
else:
assert resp['response_type'] == 'OTP_REQUIRED'
def test_login_without_2fa():
with user({
'username': TEST_USERNAME,
'password': TEST_PASSWORD,
'full_name': TEST_USERNAME,
}):
do_login(TEST_USERNAME, TEST_PASSWORD)
@pytest.mark.parametrize("user_name,password,renew_options", [
('test_user1', 'test_password1', {'interval': 30, 'otp_digits': 6}),
('test_user2', 'test_password2', {'interval': 60, 'otp_digits': 7}),
('test_user3', 'test_password3', {'interval': 50, 'otp_digits': 8}),
])
def test_secret_generation_for_user(user_name, password, renew_options):
with user({
'username': user_name,
'password': password,
'full_name': user_name,
}) as user_obj:
assert get_user_secret(user_obj['id'], False) != []
assert get_user_secret(user_obj['id'])['secret'] is None
call('user.renew_2fa_secret', user_obj['username'], renew_options)
user_secret_obj = get_user_secret(user_obj['id'])
assert user_secret_obj['secret'] is not None
for k in ('interval', 'otp_digits'):
assert user_secret_obj[k] == renew_options[k]
def test_secret_generation_for_multiple_users():
with user({
'username': TEST_USERNAME,
'password': TEST_PASSWORD,
'full_name': TEST_USERNAME,
}) as first_user:
call('user.renew_2fa_secret', first_user['username'], USERS_2FA_CONF[first_user['username']])
with user({
'username': TEST_USERNAME_2,
'password': TEST_PASSWORD_2,
'full_name': TEST_USERNAME_2,
}) as second_user:
call('user.renew_2fa_secret', second_user['username'], USERS_2FA_CONF[second_user['username']])
for user_obj in (first_user, second_user):
user_secret_obj = get_user_secret(user_obj['id'])
assert user_secret_obj['secret'] is not None
for k in ('interval', 'otp_digits'):
assert user_secret_obj[k] == USERS_2FA_CONF[user_obj['username']][k]
def test_login_without_otp_for_user_without_2fa():
with user({
'username': TEST_USERNAME_2,
'password': TEST_PASSWORD_2,
'full_name': TEST_USERNAME_2,
}):
with enabled_twofactor_auth():
do_login(TEST_USERNAME_2, TEST_PASSWORD_2)
def test_login_with_otp_for_user_with_2fa():
with user({
'username': TEST_USERNAME_2,
'password': TEST_PASSWORD_2,
'full_name': TEST_USERNAME_2,
}) as user_obj:
with enabled_twofactor_auth():
call('user.renew_2fa_secret', user_obj['username'], TEST_TWOFACTOR_INTERVAL)
do_login(TEST_USERNAME_2, TEST_PASSWORD_2, get_2fa_totp_token(get_user_secret(user_obj['id'])))
def test_user_2fa_secret_renewal(clear_ratelimit):
with user({
'username': TEST_USERNAME_2,
'password': TEST_PASSWORD_2,
'full_name': TEST_USERNAME_2,
}) as user_obj:
with enabled_twofactor_auth():
call('user.renew_2fa_secret', user_obj['username'], TEST_TWOFACTOR_INTERVAL)
do_login(TEST_USERNAME_2, TEST_PASSWORD_2, get_2fa_totp_token(get_user_secret(user_obj['id'])))
secret = get_user_secret(user_obj['id'])
call('user.renew_2fa_secret', user_obj['username'], TEST_TWOFACTOR_INTERVAL)
call('user.get_instance', user_obj['id'])
assert get_user_secret(user_obj['id'])['secret'] != secret
do_login(TEST_USERNAME_2, TEST_PASSWORD_2, get_2fa_totp_token(get_user_secret(user_obj['id'])))
def test_restricted_user_2fa_secret_renewal(clear_ratelimit):
with unprivileged_user(
username=TEST_USERNAME,
group_name='TEST_2FA_GROUP',
privilege_name='TEST_2FA_PRIVILEGE',
allowlist=[],
web_shell=False,
roles=['READONLY_ADMIN']
) as acct:
with enabled_twofactor_auth():
with client(auth=(acct.username, acct.password)) as c:
with pytest.raises(CallError) as ve:
# Trying to renew another user's 2fa token should fail
c.call('user.renew_2fa_secret', "root", TEST_TWOFACTOR_INTERVAL)
assert ve.value.errno == errno.EPERM
c.call('user.renew_2fa_secret', acct.username, TEST_TWOFACTOR_INTERVAL)
user_obj = call('user.query', [['username', '=', acct.username]], {'get': True})
do_login(acct.username, acct.password, get_2fa_totp_token(get_user_secret(user_obj['id'])))
secret = get_user_secret(user_obj['id'])
c.call('user.renew_2fa_secret', acct.username, TEST_TWOFACTOR_INTERVAL)
assert get_user_secret(user_obj['id'])['secret'] != secret
do_login(acct.username, acct.password, get_2fa_totp_token(get_user_secret(user_obj['id'])))
def test_multiple_users_login_with_otp(clear_ratelimit):
with user({
'username': TEST_USERNAME,
'password': TEST_PASSWORD,
'full_name': TEST_USERNAME,
}) as first_user:
with enabled_twofactor_auth():
do_login(TEST_USERNAME, TEST_PASSWORD)
with user({
'username': TEST_USERNAME_2,
'password': TEST_PASSWORD_2,
'full_name': TEST_USERNAME_2,
}) as second_user:
call('user.renew_2fa_secret', second_user['username'], TEST_TWOFACTOR_INTERVAL)
otp_token = get_2fa_totp_token(get_user_secret(second_user['id']))
do_login(TEST_USERNAME_2, TEST_PASSWORD_2, otp_token)
# verify we can't replay same token
do_login(TEST_USERNAME_2, TEST_PASSWORD_2, otp_token)
# Verify 2FA still required
do_login(TEST_USERNAME_2, TEST_PASSWORD_2, expected=False)
call('user.renew_2fa_secret', first_user['username'], TEST_TWOFACTOR_INTERVAL)
do_login(TEST_USERNAME, TEST_PASSWORD, get_2fa_totp_token(get_user_secret(first_user['id'])))
def test_login_with_otp_failure(clear_ratelimit):
""" simulate continually fat-fingering OTP token until eventual failure """
with user({
'username': TEST_USERNAME,
'password': TEST_PASSWORD,
'full_name': TEST_USERNAME,
}) as u:
with enabled_twofactor_auth():
call('user.renew_2fa_secret', u['username'], TEST_TWOFACTOR_INTERVAL)
with client(auth=None) as c:
resp = c.call('auth.login_ex', {
'mechanism': 'PASSWORD_PLAIN',
'username': TEST_USERNAME,
'password': TEST_PASSWORD,
})
assert resp['response_type'] == 'OTP_REQUIRED'
retry_cnt = 0
while retry_cnt < 3:
resp = c.call('auth.login_ex_continue', {
'mechanism': 'OTP_TOKEN',
'otp_token': 'canary'
})
assert resp['response_type'] == 'OTP_REQUIRED', retry_cnt
retry_cnt += 1
# We've now exhausted any grace from server. Hammer is dropped.
resp = c.call('auth.login_ex_continue', {
'mechanism': 'OTP_TOKEN',
'otp_token': 'canary'
})
assert resp['response_type'] == 'AUTH_ERR'
def test_login_with_otp_switch_account(clear_ratelimit):
""" Validate we can abandon a login attempt with 2FA """
with user({
'username': TEST_USERNAME,
'password': TEST_PASSWORD,
'full_name': TEST_USERNAME,
}) as u:
with user({
'username': TEST_USERNAME_2,
'password': TEST_PASSWORD_2,
'full_name': TEST_USERNAME_2,
}):
with enabled_twofactor_auth():
call('user.renew_2fa_secret', u['username'], TEST_TWOFACTOR_INTERVAL)
with client(auth=None) as c:
resp = c.call('auth.login_ex', {
'mechanism': 'PASSWORD_PLAIN',
'username': TEST_USERNAME,
'password': TEST_PASSWORD,
})
assert resp['response_type'] == 'OTP_REQUIRED'
resp = c.call('auth.login_ex', {
'mechanism': 'PASSWORD_PLAIN',
'username': TEST_USERNAME_2,
'password': TEST_PASSWORD_2,
})
assert resp['response_type'] == 'SUCCESS'
| 10,569 | Python | .py | 229 | 35.436681 | 123 | 0.586046 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,346 | test_boot_attach_replace_detach.py | truenas_middleware/tests/api2/test_boot_attach_replace_detach.py | import pytest
from middlewared.test.integration.utils import call
from auto_config import ha
if not ha:
# the HA VMs only have 1 extra disk at time
# of writing this. QE is aware and is working
# on adding more disks to them so in the meantime
# we have to skip this test since it will fail
# 100% of the time on HA VMs.
@pytest.mark.timeout(600)
def test_boot_attach_replace_detach():
existing_disks = call("boot.get_disks")
assert len(existing_disks) == 1
unused = call("disk.get_unused")
to_attach = unused[0]["name"]
replace_with = unused[1]["name"]
# Attach a disk and wait for resilver to finish
call("boot.attach", to_attach, job=True)
while True:
state = call("boot.get_state")
if not (
state["scan"] and
state["scan"]["function"] == "RESILVER" and
state["scan"]["state"] == "SCANNING"
):
break
assert state["topology"]["data"][0]["type"] == "MIRROR"
assert state["topology"]["data"][0]["children"][0]["status"] == "ONLINE"
to_replace = state["topology"]["data"][0]["children"][1]["name"]
assert to_replace.startswith(to_attach)
assert state["topology"]["data"][0]["children"][1]["status"] == "ONLINE"
# Replace newly attached disk
call("boot.replace", to_replace, replace_with, job=True)
# Resilver is a part of replace routine
state = call("boot.get_state")
assert state["topology"]["data"][0]["type"] == "MIRROR"
assert state["topology"]["data"][0]["children"][0]["status"] == "ONLINE"
to_detach = state["topology"]["data"][0]["children"][1]["name"]
assert to_detach.startswith(replace_with)
assert state["topology"]["data"][0]["children"][1]["status"] == "ONLINE"
# Detach replaced disk, returning the pool to its initial state
call("boot.detach", to_detach)
assert len(call("boot.get_disks")) == 1
| 2,053 | Python | .py | 43 | 38.790698 | 80 | 0.596192 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,347 | test_032_ad_kerberos.py | truenas_middleware/tests/api2/test_032_ad_kerberos.py | import os
import sys
import pytest
from middlewared.test.integration.assets.pool import dataset
apifolder = os.getcwd()
sys.path.append(apifolder)
from functions import SSH_TEST
from auto_config import hostname, password, user
from contextlib import contextmanager
from base64 import b64decode
from protocols import nfs_share
from middlewared.service_exception import ValidationErrors
from middlewared.test.integration.utils import call
from middlewared.test.integration.assets.directory_service import active_directory
try:
from config import AD_DOMAIN, ADPASSWORD, ADUSERNAME, AD_COMPUTER_OU
except ImportError:
pytestmark = pytest.mark.skip(reason='Missing AD configuration')
SAMPLE_KEYTAB = "BQIAAABTAAIAC0hPTUVET00uRlVOABFyZXN0cmljdGVka3JiaG9zdAASdGVzdDQ5LmhvbWVkb20uZnVuAAAAAV8kEroBAAEACDHN3Kv9WKLLAAAAAQAAAAAAAABHAAIAC0hPTUVET00uRlVOABFyZXN0cmljdGVka3JiaG9zdAAGVEVTVDQ5AAAAAV8kEroBAAEACDHN3Kv9WKLLAAAAAQAAAAAAAABTAAIAC0hPTUVET00uRlVOABFyZXN0cmljdGVka3JiaG9zdAASdGVzdDQ5LmhvbWVkb20uZnVuAAAAAV8kEroBAAMACDHN3Kv9WKLLAAAAAQAAAAAAAABHAAIAC0hPTUVET00uRlVOABFyZXN0cmljdGVka3JiaG9zdAAGVEVTVDQ5AAAAAV8kEroBAAMACDHN3Kv9WKLLAAAAAQAAAAAAAABbAAIAC0hPTUVET00uRlVOABFyZXN0cmljdGVka3JiaG9zdAASdGVzdDQ5LmhvbWVkb20uZnVuAAAAAV8kEroBABEAEBDQOH+tKYCuoedQ53WWKFgAAAABAAAAAAAAAE8AAgALSE9NRURPTS5GVU4AEXJlc3RyaWN0ZWRrcmJob3N0AAZURVNUNDkAAAABXyQSugEAEQAQENA4f60pgK6h51DndZYoWAAAAAEAAAAAAAAAawACAAtIT01FRE9NLkZVTgARcmVzdHJpY3RlZGtyYmhvc3QAEnRlc3Q0OS5ob21lZG9tLmZ1bgAAAAFfJBK6AQASACCKZTjTnrjT30jdqAG2QRb/cFyTe9kzfLwhBAm5QnuMiQAAAAEAAAAAAAAAXwACAAtIT01FRE9NLkZVTgARcmVzdHJpY3RlZGtyYmhvc3QABlRFU1Q0OQAAAAFfJBK6AQASACCKZTjTnrjT30jdqAG2QRb/cFyTe9kzfLwhBAm5QnuMiQAAAAEAAAAAAAAAWwACAAtIT01FRE9NLkZVTgARcmVzdHJpY3RlZGtyYmhvc3QAEnRlc3Q0OS5ob21lZG9tLmZ1bgAAAAFfJBK6AQAXABAcyjciCUnM9DmiyiPO4VIaAAAAAQAAAAAAAABPAAIAC0hPTUVET00uRlVOABFyZXN0cmljdGVka3JiaG9zdAAGVEVTVDQ5AAAAAV8kEroBABcAEBzKNyIJScz0OaLKI87hUhoAAAABAAAAAAAAAEYAAgALSE9NRURPTS5GVU4ABGhvc3QAEnRlc3Q0OS5ob21lZG9tLmZ1bgAAAAFfJBK6AQABAAgxzdyr/ViiywAAAAEAAAAAAAAAOgACAAtIT01FRE9NLkZVTgAEaG9zdAAGVEVTVDQ5AAAAAV8kEroBAAEACDHN3Kv9WKLLAAAAAQAAAAAAAABGAAIAC0hPTUVET00uRlVOAARob3N0ABJ0ZXN0NDkuaG9tZWRvbS5mdW4AAAABXyQSugEAAwAIMc3cq/1YossAAAABAAAAAAAAADoAAgALSE9NRURPTS5GVU4ABGhvc3QABlRFU1Q0OQAAAAFfJBK6AQADAAgxzdyr/ViiywAAAAEAAAAAAAAATgACAAtIT01FRE9NLkZVTgAEaG9zdAASdGVzdDQ5LmhvbWVkb20uZnVuAAAAAV8kEroBABEAEBDQOH+tKYCuoedQ53WWKFgAAAABAAAAAAAAAEIAAgALSE9NRURPTS5GVU4ABGhvc3QABlRFU1Q0OQAAAAFfJBK6AQARABAQ0Dh/rSmArqHnUOd1lihYAAAAAQAAAAAAAABeAAIAC0hPTUVET00uRlVOAARob3N0ABJ0ZXN0NDkuaG9tZWRvbS5mdW4AAAABXyQSugEAEgAgimU40564099I3agBtkEW/3Bck3vZM3y8IQQJuUJ7jIkAAAABAAAAAAAAAFIAAgALSE9NRURPTS5GVU4ABGhvc3QABlRFU1Q0OQAAAAFfJBK6AQASACCKZTjTnrjT30jdqAG2QRb/cFyTe9kzfLwhBAm5QnuMiQAAAAEAAAAAAAAATgACAAtIT01FRE9NLkZVTgAEaG9zdAASdGVzdDQ5LmhvbWVkb20uZnVuAAAAAV8kEroBABcAEBzKNyIJScz0OaLKI87hUhoAAAABAAAAAAAAAEIAAgALSE9NRURPTS5GVU4ABGhvc3QABlRFU1Q0OQAAAAFfJBK6AQAXABAcyjciCUnM9DmiyiPO4VIaAAAAAQAAAAAAAAA1AAEAC0hPTUVET00uRlVOAAdURVNUNDkkAAAAAV8kEroBAAEACDHN3Kv9WKLLAAAAAQAAAAAAAAA1AAEAC0hPTUVET00uRlVOAAdURVNUNDkkAAAAAV8kEroBAAMACDHN3Kv9WKLLAAAAAQAAAAAAAAA9AAEAC0hPTUVET00uRlVOAAdURVNUNDkkAAAAAV8kEroBABEAEBDQOH+tKYCuoedQ53WWKFgAAAABAAAAAAAAAE0AAQALSE9NRURPTS5GVU4AB1RFU1Q0OSQAAAABXyQSugEAEgAgimU40564099I3agBtkEW/3Bck3vZM3y8IQQJuUJ7jIkAAAABAAAAAAAAAD0AAQALSE9NRURPTS5GVU4AB1RFU1Q0OSQAAAABXyQSugEAFwAQHMo3IglJzPQ5osojzuFSGgAAAAEAAAAA" # noqa
SAMPLEDOM_NAME = "CANARY.FUN"
SAMPLEDOM_REALM = {
"realm": SAMPLEDOM_NAME,
"kdc": ["169.254.100.1", "169.254.100.2", "169.254.100.3"],
"admin_server": ["169.254.100.10", "169.254.100.11", "169.254.100.12"],
"kpasswd_server": ["169.254.100.20", "169.254.100.21", "169.254.100.22"],
}
APPDEFAULTS_PAM_OVERRIDE = """
pam = {
forwardable = false
ticket_lifetime = 36000
}
"""
def get_export_sec(exports_config):
sec_entry = None
for entry in exports_config.splitlines():
if not entry.startswith("\t"):
continue
line = entry.strip().split("(")[1]
sec_entry = line.split(",")[0]
break
return sec_entry
def regenerate_exports():
# NFS service isn't running for these tests
# and so exports aren't updated. Force the update.
call('etc.generate', 'nfsd')
def check_export_sec(expected):
regenerate_exports()
results = SSH_TEST('cat /etc/exports', user, password)
assert results['result'] is True, results['stderr']
exports_config = results['stdout'].strip()
sec = get_export_sec(exports_config)
assert sec == expected, exports_config
def parse_krb5_conf(fn, split=None, state=None):
results = SSH_TEST('cat /etc/krb5.conf', user, password)
assert results['result'] is True, results['output']
if split:
krb5conf_lines = results['stdout'].split(split)
else:
krb5conf_lines = results['stdout'].splitlines()
for idx, entry in enumerate(krb5conf_lines):
fn(krb5conf_lines, idx, entry, state)
return results['output']
@contextmanager
def add_kerberos_keytab(ktname):
kt = call('kerberos.keytab.create', {
"name": ktname,
"file": SAMPLE_KEYTAB
})
try:
yield kt
finally:
call('kerberos.keytab.delete', kt['id'])
@contextmanager
def add_kerberos_realm(realm_name):
realm = call('kerberos.realm.create', {
'realm': realm_name,
})
try:
yield realm
finally:
call('kerberos.realm.delete', realm['id'])
@pytest.fixture(scope="function")
def do_ad_connection(request):
with active_directory(
AD_DOMAIN,
ADUSERNAME,
ADPASSWORD,
netbiosname=hostname,
createcomputer=AD_COMPUTER_OU,
) as ad:
yield (request, ad)
def test_kerberos_keytab_and_realm(do_ad_connection):
def krb5conf_parser(krb5conf_lines, idx, entry, state):
if entry.lstrip() == f"kdc = {SAMPLEDOM_REALM['kdc'][0]}":
assert krb5conf_lines[idx + 1].lstrip() == f"kdc = {SAMPLEDOM_REALM['kdc'][1]}"
assert krb5conf_lines[idx + 2].lstrip() == f"kdc = {SAMPLEDOM_REALM['kdc'][2]}"
state['has_kdc'] = True
if entry.lstrip() == f"admin_server = {SAMPLEDOM_REALM['admin_server'][0]}":
assert krb5conf_lines[idx + 1].lstrip() == f"admin_server = {SAMPLEDOM_REALM['admin_server'][1]}"
assert krb5conf_lines[idx + 2].lstrip() == f"admin_server = {SAMPLEDOM_REALM['admin_server'][2]}"
state['has_admin_server'] = True
if entry.lstrip() == f"kpasswd_server = {SAMPLEDOM_REALM['kpasswd_server'][0]}":
assert krb5conf_lines[idx + 1].lstrip() == f"kpasswd_server = {SAMPLEDOM_REALM['kpasswd_server'][1]}"
assert krb5conf_lines[idx + 2].lstrip() == f"kpasswd_server = {SAMPLEDOM_REALM['kpasswd_server'][2]}"
state['has_kpasswd_server'] = True
call('directoryservices.status')['status'] == 'HEALTHY'
"""
The keytab in this case is a b64encoded keytab file.
AD_MACHINE_ACCOUNT is automatically generated during domain
join and uploaded into our configuration database. This
test checks for its presence and that it's validly b64 encoded.
The process of decoding and adding to system keytab is tested
in later kerberos tests. "kerberos.start" will decode, write
to system keytab, and kinit. So in this case, proper function
can be determined by printing contents of system keytab and
verifying that we were able to get a kerberos ticket.
"""
kt = call('kerberos.keytab.query', [['name', '=', 'AD_MACHINE_ACCOUNT']], {'get': True})
b64decode(kt['file'])
"""
kerberos_principal_choices lists unique keytab principals in
the system keytab. AD_MACHINE_ACCOUNT should add more than
one principal.
"""
orig_kt = call('kerberos.keytab.kerberos_principal_choices')
assert orig_kt != []
"""
kerberos.check_ticket performs a platform-independent verification
of kerberos ticket.
"""
call('kerberos.check_ticket')
"""
Test uploading b64encoded sample kerberos keytab included
at top of this file. In the next series of tests we will
upload, validate that it was uploaded, and verify that the
keytab is read back correctly.
"""
with add_kerberos_keytab('KT2'):
kt2 = call('kerberos.keytab.query', [['name', '=', 'KT2']], {'get': True})
b64decode(kt2['file'])
assert kt2['file'] == SAMPLE_KEYTAB
"""
AD Join should automatically add a kerberos realm
for the AD domain.
"""
call('kerberos.realm.query', [['realm', '=', AD_DOMAIN.upper()]], {'get': True})
with add_kerberos_realm(SAMPLEDOM_NAME) as new_realm:
payload = SAMPLEDOM_REALM.copy()
payload.pop("realm")
call('kerberos.realm.update', new_realm['id'], payload)
r = call('kerberos.realm.query', [['realm', '=', SAMPLEDOM_NAME]], {'get': True})
r.pop('id')
assert r == SAMPLEDOM_REALM
# Verify realms properly added to krb5.conf
iter_state = {
'has_kdc': False,
'has_admin_server': False,
'has_kpasswd_server': False
}
output = parse_krb5_conf(krb5conf_parser, state=iter_state)
assert iter_state['has_kdc'] is True, output
assert iter_state['has_admin_server'] is True, output
assert iter_state['has_kpasswd_server'] is True, output
assert len(call('kerberos.realm.query', [['realm', '=', SAMPLEDOM_NAME]])) == 0
def test_kerberos_krbconf(do_ad_connection):
def parser_1(unused, idx, sec, state):
if not sec.startswith("appdefaults"):
return
for entry in sec.splitlines():
if entry.lstrip().startswith('}'):
break
if entry.strip() == "forwardable = false":
state['has_forwardable'] = True
if entry.strip() == "ticket_lifetime = 36000":
state['has_ticket_lifetime'] = True
def parse_section(unused, idx, sec, state):
if not sec.startswith(state['section']):
return
for entry in sec.splitlines():
if entry.strip() == state['to_check']:
state['found'] = True
break
"""
Test of more complex auxiliary parameter parsing that allows
users to override our defaults.
"""
call('kerberos.update', {'appdefaults_aux': APPDEFAULTS_PAM_OVERRIDE})
iter_state = {
'has_forwardable': False,
'has_ticket_lifetime': False
}
output = parse_krb5_conf(parser_1, split='[', state=iter_state)
assert iter_state['has_forwardable'] is True, output
assert iter_state['has_ticket_lifetime'] is True, output
call('kerberos.update', {'appdefaults_aux': 'encrypt = true'})
iter_state = {
'section': 'appdefaults',
'found': False,
'to_check': 'encrypt = true'
}
output = parse_krb5_conf(parse_section, split='[', state=iter_state)
assert iter_state['found'] is True, output
call('kerberos.update', {'libdefaults_aux': 'rdns = true'})
iter_state = {
'section': 'libdefaults',
'found': False,
'to_check': 'rdns = true'
}
output = parse_krb5_conf(parse_section, split='[', state=iter_state)
assert iter_state['found'] is True, output
def test_invalid_aux():
call('kerberos.update', {'appdefaults_aux': '', 'libdefaults_aux': ''})
# check that parser raises validation errors
with pytest.raises(ValidationErrors):
call('kerberos.update', {'appdefaults_aux': 'canary = true'})
with pytest.raises(ValidationErrors):
call('kerberos.update', {'libdefaults_aux': 'canary = true'})
def test_kerberos_nfs4(do_ad_connection):
assert call('kerberos.keytab.has_nfs_principal') is True
with dataset('AD_NFS') as ds:
with nfs_share(f'/mnt/{ds}', options={'comment': 'KRB Test Share'}):
call('nfs.update', {"protocols": ["NFSV3", "NFSV4"]})
"""
First NFS exports check. In this situation we are joined to
AD and therefore have a keytab with NFS entry
Expected security is:
"V4: / -sec=sys:krb5:krb5i:krb5p"
"""
check_export_sec('sec=sys:krb5:krb5i:krb5p')
call('nfs.update', {"v4_krb": True})
"""
Second NFS exports check. We now have an NFS SPN entry
Expected security is:
"V4: / -sec=krb5:krb5i:krb5p"
"""
check_export_sec('sec=krb5:krb5i:krb5p')
"""
v4_krb_enabled should still be True after this
disabling v4_krb because we still have an nfs
service principal in our keytab.
"""
data = call('nfs.update', {'v4_krb': False})
assert data['v4_krb_enabled'] is True, str(data)
"""
Third NFS exports check. We now have an NFS SPN entry
but v4_krb is disabled.
Expected security is:
"V4: / -sec=sys:krb5:krb5i:krb5p"
"""
check_export_sec('sec=sys:krb5:krb5i:krb5p')
def test_verify_nfs_krb_disabled():
"""
This test checks that we no longer are flagged as having
v4_krb_enabled now that we are not joined to AD.
"""
assert call('nfs.config')['v4_krb_enabled'] is False
def test_kerberos_ticket_management(do_ad_connection):
klist_out = call('kerberos.klist')
assert klist_out['default_principal'].startswith(hostname.upper()), str(klist_out)
assert klist_out['ticket_cache']['type'] == 'KEYRING'
assert klist_out['ticket_cache']['name'].startswith('persistent:0')
assert len(klist_out['tickets']) != 0
to_check = None
for tkt in klist_out['tickets']:
if tkt['server'].startswith('krbtgt'):
to_check = tkt
assert to_check is not None, str(klist_out)
assert 'RENEWABLE' in to_check['flags']
call('core.get_jobs', [
['method', '=', 'kerberos.wait_for_renewal'],
['state', '=', 'RUNNING']
], {'get': True})
def test_check_ad_machine_account_deleted_after_ad_leave():
assert len(call('kerberos.keytab.query')) == 0
| 14,156 | Python | .py | 274 | 44.485401 | 2,662 | 0.705239 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,348 | test_541_vm.py | truenas_middleware/tests/api2/test_541_vm.py | import dataclasses
import time
import pytest
from pytest_dependency import depends
from auto_config import pool_name
from middlewared.test.integration.utils import call
from middlewared.test.integration.assets.pool import dataset
@dataclasses.dataclass
class VmAssets:
# probably best to keep this module
# to only creating 1 VM, since the
# functionality can be tested on 1
# and creating > 1 nested VMs incurs
# an ever-increasing perf penalty in
# test infrastructure
VM_NAMES = ['vm01']
VM_INFO = dict()
VM_DEVICES = dict()
@pytest.mark.dependency(name='VIRT_SUPPORTED')
def test_001_is_virtualization_supported():
if not call('vm.virtualization_details')['supported']:
pytest.skip('Virtualization not supported')
elif call('failover.licensed'):
pytest.skip('Virtualization not supported on HA')
@pytest.mark.parametrize(
'info',
[
{'method': 'vm.flags', 'type': dict, 'keys': ('intel_vmx', 'amd_rvi')},
{'method': 'vm.cpu_model_choices', 'type': dict, 'keys': ('EPYC',)},
{'method': 'vm.bootloader_options', 'type': dict, 'keys': ('UEFI', 'UEFI_CSM')},
{'method': 'vm.get_available_memory', 'type': int},
{'method': 'vm.guest_architecture_and_machine_choices', 'type': dict, 'keys': ('i686', 'x86_64')},
{'method': 'vm.maximum_supported_vcpus', 'type': int},
{'method': 'vm.port_wizard', 'type': dict, 'keys': ('port', 'web')},
{'method': 'vm.random_mac', 'type': str},
{'method': 'vm.resolution_choices', 'type': dict, 'keys': ('1920x1200', '640x480')},
{'method': 'vm.device.bind_choices', 'type': dict, 'keys': ('0.0.0.0', '::')},
{'method': 'vm.device.iommu_enabled', 'type': bool},
{'method': 'vm.device.iotype_choices', 'type': dict, 'keys': ('NATIVE',)},
{'method': 'vm.device.nic_attach_choices', 'type': dict},
{'method': 'vm.device.usb_controller_choices', 'type': dict, 'keys': ('qemu-xhci',)},
{'method': 'vm.device.usb_passthrough_choices', 'type': dict},
{'method': 'vm.device.passthrough_device_choices', 'type': dict},
{'method': 'vm.device.pptdev_choices', 'type': dict}
],
ids=lambda x: x['method']
)
def test_002_vm_endpoint(info, request):
"""
Very basic behavior of various VM endpoints. Ensures they
return without error and that the type of response is what
we expect. If a dict is returned, we check that top-level
keys exist
"""
depends(request, ['VIRT_SUPPORTED'])
rv = call(info['method'])
assert isinstance(rv, info['type'])
if (keys := info.get('keys')):
assert all((i in rv for i in keys))
@pytest.mark.parametrize('disk_name', ['test zvol'])
def test_003_verify_disk_choice(disk_name):
with dataset(disk_name, {'type': 'VOLUME', 'volsize': 1048576, 'sparse': True}) as ds:
assert call('vm.device.disk_choices').get(f'/dev/zvol/{ds.replace(" ", "+")}') == ds
@pytest.mark.parametrize('vm_name', VmAssets.VM_NAMES)
@pytest.mark.dependency(name='VM_CREATED')
def test_010_create_vm(vm_name, request):
depends(request, ['VIRT_SUPPORTED'])
vm_payload = {
'name': vm_name,
'description': f'{vm_name} description',
'vcpus': 1,
'memory': 512,
'bootloader': 'UEFI',
'autostart': False,
}
vm = call('vm.create', vm_payload)
qry = call('vm.query', [['id', '=', vm['id']]], {'get': True})
assert all((vm_payload[key] == qry[key] for key in vm_payload))
VmAssets.VM_INFO.update({qry['name']: {'query_response': qry}})
@pytest.mark.parametrize('device', ['DISK', 'DISPLAY', 'NIC'])
@pytest.mark.dependency(name='ADD_DEVICES_TO_VM')
def test_011_add_devices_to_vm(device, request):
depends(request, ['VM_CREATED'])
for vm_name, info in VmAssets.VM_INFO.items():
if vm_name not in VmAssets.VM_DEVICES:
VmAssets.VM_DEVICES[vm_name] = dict()
dev_info = {
'dtype': device,
'vm': info['query_response']['id'],
}
if device == 'DISK':
zvol_name = f'{pool_name}/{device}_for_{vm_name}'
dev_info.update({
'attributes': {
'create_zvol': True,
'zvol_name': zvol_name,
'zvol_volsize': 1048576
}
})
elif device == 'DISPLAY':
dev_info.update({'attributes': {'resolution': '1024x768', 'password': 'displaypw'}})
elif device == 'NIC':
for nic_name in call('vm.device.nic_attach_choices'):
dev_info.update({'attributes': {'nic_attach': nic_name}})
break
else:
assert False, f'Unhandled device type: ({device!r})'
info = call('vm.device.create', dev_info)
VmAssets.VM_DEVICES[vm_name].update({device: info})
# only adding these devices to 1 VM
break
@pytest.mark.parametrize('vm_name', VmAssets.VM_NAMES)
def test_012_verify_devices_for_vm(vm_name, request):
depends(request, ['ADD_DEVICES_TO_VM'])
for device, info in VmAssets.VM_DEVICES[vm_name].items():
qry = call('vm.device.query', [['id', '=', info['id']]], {'get': True})
assert qry['dtype'] == device
assert qry['vm'] == VmAssets.VM_INFO[vm_name]['query_response']['id']
assert qry['attributes'] == VmAssets.VM_DEVICES[vm_name][device]['attributes']
@pytest.mark.parametrize('vm_name', VmAssets.VM_NAMES)
def test_013_delete_vm_devices(vm_name, request):
depends(request, ['ADD_DEVICES_TO_VM'])
for device, info in VmAssets.VM_DEVICES[vm_name].items():
opts = {}
if device == 'DISK':
opts = {'zvol': True}
call('vm.device.delete', info['id'], opts)
assert not call('vm.device.query', [['id', '=', info['id']]])
@pytest.mark.parametrize('vm_name', VmAssets.VM_NAMES)
@pytest.mark.dependency(name='VM_STARTED')
def test_014_start_vm(vm_name, request):
depends(request, ['VM_CREATED'])
_id = VmAssets.VM_INFO[vm_name]['query_response']['id']
call('vm.start', _id)
vm_status = call('vm.status', _id)
assert all((vm_status[key] == 'RUNNING' for key in ('state', 'domain_state')))
assert all((vm_status['pid'], isinstance(vm_status['pid'], int)))
@pytest.mark.parametrize('vm_name', VmAssets.VM_NAMES)
def test_015_query_vm_info(vm_name, request):
depends(request, ['VIRT_SUPPORTED', 'VM_CREATED', 'VM_STARTED'])
_id = VmAssets.VM_INFO[vm_name]['query_response']['id']
vm_string = f'{_id}_{vm_name}'
assert call('vm.get_console', _id) == vm_string
assert vm_string in call('vm.log_file_path', _id)
mem_keys = ('RNP', 'PRD', 'RPRD')
mem_info = call('vm.get_vmemory_in_use')
assert isinstance(mem_info, dict)
assert all((key in mem_info for key in mem_keys))
assert all((isinstance(mem_info[key], int) for key in mem_keys))
@pytest.mark.parametrize('vm_name', VmAssets.VM_NAMES)
@pytest.mark.dependency(name='VM_SUSPENDED')
def test_020_suspend_vm(vm_name, request):
depends(request, ['VIRT_SUPPORTED', 'VM_CREATED', 'VM_STARTED'])
_id = VmAssets.VM_INFO[vm_name]['query_response']['id']
call('vm.suspend', _id)
for retry in range(1, 4):
status = call('vm.status', _id)
if all((status['state'] == 'SUSPENDED', status['domain_state'] == 'PAUSED')):
break
else:
time.sleep(1)
else:
assert False, f'Timed out after {retry} seconds waiting on {vm_name!r} to suspend'
@pytest.mark.parametrize('vm_name', VmAssets.VM_NAMES)
@pytest.mark.dependency(name='VM_RESUMED')
def test_021_resume_vm(vm_name, request):
depends(request, ['VM_SUSPENDED'])
_id = VmAssets.VM_INFO[vm_name]['query_response']['id']
call('vm.resume', _id)
for retry in range(1, 4):
status = call('vm.status', _id)
if all((status['state'] == 'RUNNING', status['domain_state'] == 'RUNNING')):
break
else:
time.sleep(1)
else:
assert False, f'Timed out after {retry} seconds waiting on {vm_name!r} to resume'
@pytest.mark.skip(reason='Takes > 60 seconds and is flaky')
@pytest.mark.parametrize('vm_name', VmAssets.VM_NAMES)
@pytest.mark.dependency(name='VM_RESTARTED')
def test_022_restart_vm(vm_name, request):
depends(request, ['VM_RESUMED'])
_id = VmAssets.VM_INFO[vm_name]['query_response']['id']
call('vm.restart', _id, job=True)
status = call('vm.status', _id)
assert all((status['state'] == 'RUNNING', status['domain_state'] == 'RUNNING'))
@pytest.mark.parametrize('vm_name', VmAssets.VM_NAMES)
@pytest.mark.dependency(name='VM_POWERED_OFF')
def test_023_poweroff_vm(vm_name, request):
depends(request, ['VM_RESUMED'])
_id = VmAssets.VM_INFO[vm_name]['query_response']['id']
call('vm.poweroff', _id)
for retry in range(1, 4):
status = call('vm.status', _id)
if all((status['state'] == 'STOPPED', status['domain_state'] == 'SHUTOFF')):
break
else:
time.sleep(1)
else:
assert False, f'Timed out after {retry} seconds waiting on {vm_name!r} to poweroff'
@pytest.mark.parametrize('vm_name', VmAssets.VM_NAMES)
@pytest.mark.dependency(name='VM_UPDATED')
def test_024_update_powered_off_vm(vm_name, request):
depends(request, ['VM_POWERED_OFF'])
_id = VmAssets.VM_INFO[vm_name]['query_response']['id']
new_mem = 768
call('vm.update', _id, {'memory': new_mem})
assert call('vm.query', [['id', '=', _id]], {'get': True})['memory'] == new_mem
@pytest.mark.parametrize('vm_name', VmAssets.VM_NAMES)
def test_024_clone_powered_off_vm(vm_name, request):
depends(request, ['VM_POWERED_OFF'])
to_clone_id = VmAssets.VM_INFO[vm_name]['query_response']['id']
new_name = f'{vm_name}_clone'
call('vm.clone', to_clone_id, new_name)
qry = call('vm.query', [['name', '=', new_name]], {'get': True})
VmAssets.VM_INFO.update({new_name: {'query_response': qry}})
assert call('vm.get_console', qry['id']) == f'{qry["id"]}_{new_name}'
VmAssets.VM_DEVICES.update({new_name: dict()})
for dev in call('vm.device.query', [['vm', '=', qry['id']]]):
if dev['dtype'] in ('DISK', 'NIC', 'DEVICE'):
# add this to VM_DEVICES so we properly clean-up after
# the test module runs
VmAssets.VM_DEVICES[new_name].update({dev['dtype']: dev})
def test_025_cleanup_vms(request):
depends(request, ['VM_POWERED_OFF'])
for vm in call('vm.query'):
call('vm.delete', vm['id'])
assert not call('vm.query', [['name', '=', vm['id']]])
| 10,644 | Python | .py | 228 | 40.22807 | 106 | 0.618543 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,349 | test_pool_is_upgraded.py | truenas_middleware/tests/api2/test_pool_is_upgraded.py | import pytest
from middlewared.test.integration.assets.pool import another_pool, pool
from middlewared.test.integration.utils import call, ssh
@pytest.fixture(scope="module")
def outdated_pool():
with another_pool() as pool:
device = pool["topology"]["data"][0]["path"]
ssh(f"zpool export {pool['name']}")
ssh(f"zpool create {pool['name']} -o altroot=/mnt -o feature@sha512=disabled -f {device}")
yield pool
def test_is_upgraded():
pool_id = call("pool.query", [["name", "=", pool]])[0]["id"]
assert call("pool.is_upgraded", pool_id)
def test_is_outdated(outdated_pool):
assert call("pool.is_upgraded", outdated_pool["id"]) is False
def test_is_outdated_in_list(outdated_pool):
pool = call("pool.query", [["id", "=", outdated_pool["id"]]], {"extra": {"is_upgraded": True}})[0]
assert pool["is_upgraded"] is False
# Flaky as one-shot alert creation might be delayed until `alert.process_alerts` completion.
@pytest.mark.flaky(reruns=5, reruns_delay=5)
def test_is_outdated_alert(outdated_pool):
alerts = call("alert.list")
assert any((i["klass"] == "PoolUpgraded" and i["args"] == outdated_pool["name"] for i in alerts))
| 1,195 | Python | .py | 23 | 47.695652 | 102 | 0.683032 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,350 | test_pool_dataset_quota_alert.py | truenas_middleware/tests/api2/test_pool_dataset_quota_alert.py | import re
import pytest
from pytest_dependency import depends
from auto_config import pool_name, user, password
from functions import SSH_TEST
from middlewared.test.integration.utils import call
G = 1024 * 1024 * 1024
@pytest.mark.parametrize("datasets,expected_alerts", [
(
{
"": {
"used": 900,
"quota": 1 * G,
}
},
[
{"formatted": r"Quota exceeded on dataset tank/quota_test. Used 8|9[0-9.]+% \(8|9[0-9.]+ MiB of 1 GiB\)."},
]
),
(
{
"": {
"used": 118,
"quota": 10 * G,
"refquota": 1 * G,
}
},
[
# There was a false positive:
# {"formatted": r"Quota exceeded on dataset tank/quota_test. Used 91.[0-9]+% \(9.[0-9]+ GiB of 10 GiB\)."},
]
),
(
{
"": {
"used": 100,
"quota": 1000000000 * G,
}
},
[
# There should be no quota alerts if quota is set to a larger value than dataset size
]
),
])
def test_dataset_quota_alert(request, datasets, expected_alerts):
assert "" in datasets
try:
for dataset, params in datasets.items():
used = params.pop("used", None)
call("pool.dataset.create", {"name": f"{pool_name}/quota_test/{dataset}".rstrip("/"), **params})
if used is not None:
results = SSH_TEST(f'dd if=/dev/urandom of=/mnt/{pool_name}/quota_test/{dataset}/blob '
f'bs=1M count={used}', user, password)
assert results['result'] is True, results
call("alert.initialize")
call("core.bulk", "alert.process_alerts", [[]], job=True)
alerts = [alert for alert in call("alert.list") if alert["source"] == "Quota"]
assert len(alerts) == len(expected_alerts), alerts
for alert, expected_alert in zip(alerts, expected_alerts):
for k, v in expected_alert.items():
if k == "formatted":
assert re.match(v, alert[k]), (alert, expected_alert, k)
else:
assert alert[k] == v, (alert, expected_alert, k)
finally:
call("pool.dataset.delete", f"{pool_name}/quota_test", {
"recursive": True,
})
| 2,411 | Python | .py | 68 | 25.058824 | 119 | 0.509224 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,351 | test_quotas.py | truenas_middleware/tests/api2/test_quotas.py | from dataclasses import dataclass
import pytest
from middlewared.service_exception import ValidationErrors
from middlewared.test.integration.utils import call
from middlewared.test.integration.assets.account import user
from middlewared.test.integration.assets.pool import dataset
@dataclass(frozen=True)
class QuotaConfig:
# user quota value
uq_value: int = 1000000
# group quota value
gq_value: int = uq_value * 2
# dataset quota value
dq_value: int = gq_value + 10000
# dataset refquota value
drq_value: int = dq_value + 10000
# temp dataset name
ds_name: str = 'temp_quota_ds_name'
@pytest.fixture(scope='module')
def temp_ds():
with dataset(QuotaConfig.ds_name) as ds:
yield ds
@pytest.fixture(scope='module')
def temp_user(temp_ds):
user_info = {
'username': 'test_quota_user',
'full_name': 'Test Quota User',
'password': 'test1234',
'group_create': True,
}
with user(user_info) as u:
uid = call('user.get_instance', u['id'])['uid']
grp = call('group.query', [['group', '=', u['username']]], {'get': True})
yield {'uid': uid, 'gid': grp['gid'], 'user': u['username'], 'group': grp['group']}
@pytest.mark.parametrize('id_', ['0', 'root'])
@pytest.mark.parametrize(
'quota_type,error', [
(['USER', 'user quota on uid']),
(['USEROBJ', 'userobj quota on uid']),
(['GROUP', 'group quota on gid']),
(['GROUPOBJ', 'groupobj quota on gid']),
],
ids=[
'root USER quota is prohibited',
'root USEROBJ quota is prohibited',
'root GROUP quota is prohibited',
'root GROUPOBJ quota is prohibited',
],
)
def test_error(temp_ds, id_, quota_type, error):
"""Changing any quota type for the root user/group should be prohibited"""
with pytest.raises(ValidationErrors) as ve:
call('pool.dataset.set_quota', temp_ds, [{'quota_type': quota_type, 'id': id_, 'quota_value': 5242880}])
assert ve.value.errors[0].errmsg == f'Setting {error} [0] is not permitted'
def test_quotas(temp_ds, temp_user):
user, uid = temp_user['user'], temp_user['uid']
group, gid = temp_user['group'], temp_user['gid']
uq_value = QuotaConfig.uq_value
gq_value = QuotaConfig.gq_value
dq_value = QuotaConfig.dq_value
drq_value = QuotaConfig.drq_value
call('pool.dataset.set_quota', temp_ds, [
{'quota_type': 'USER', 'id': user, 'quota_value': uq_value},
{'quota_type': 'USEROBJ', 'id': user, 'quota_value': uq_value},
{'quota_type': 'GROUP', 'id': group, 'quota_value': gq_value},
{'quota_type': 'GROUPOBJ', 'id': group, 'quota_value': gq_value},
{'quota_type': 'DATASET', 'id': 'QUOTA', 'quota_value': dq_value},
{'quota_type': 'DATASET', 'id': 'REFQUOTA', 'quota_value': drq_value},
])
verify_info = (
(
{
'quota_type': 'USER',
'id': uid,
'quota': uq_value,
'obj_quota': uq_value,
'name': user
},
'USER',
),
(
{
'quota_type': 'GROUP',
'id': gid,
'quota': gq_value,
'obj_quota': gq_value,
'name': group
},
'GROUP',
),
(
{
'quota_type': 'DATASET',
'id': temp_ds,
'name': temp_ds,
'quota': dq_value,
'refquota': drq_value,
},
'DATASET',
),
)
for er, quota_type in verify_info:
for result in filter(lambda x: x['id'] == er['id'], call('pool.dataset.get_quota', temp_ds, quota_type)):
assert all((result[j] == er[j] for j in er)), result
| 3,834 | Python | .py | 104 | 28.730769 | 113 | 0.560818 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,352 | test_pool_scrub.py | truenas_middleware/tests/api2/test_pool_scrub.py | import errno
import pytest
from auto_config import pool_name
from middlewared.service_exception import ValidationError, ValidationErrors
from middlewared.test.integration.utils import call
@pytest.fixture(scope="module")
def scrub_info():
for i in call("pool.scrub.query", [["pool_name", "=", pool_name]]):
return i
else:
# by default, on pool creation a scrub task is created
assert False, f"Failed to find scrub job for {pool_name!r}"
def test_create_duplicate_scrub_fails(scrub_info):
with pytest.raises(ValidationErrors) as ve:
call(
"pool.scrub.create",
{
"pool": scrub_info["pool"],
"threshold": 1,
"description": "",
"schedule": {
"minute": "00",
"hour": "00",
"dom": "1",
"month": "1",
"dow": "1",
},
"enabled": True,
},
)
assert ve.value.errors == [
ValidationError(
"pool_scrub_create.pool",
"A scrub with this pool already exists",
errno.EINVAL,
)
]
def test_update_scrub(scrub_info):
assert call(
"pool.scrub.update",
scrub_info["id"],
{
"threshold": 2,
"description": "",
"schedule": {
"minute": "00",
"hour": "00",
"dom": "1",
"month": "1",
"dow": "1",
},
"enabled": True,
},
)
def test_delete_scrub(scrub_info):
call("pool.scrub.delete", scrub_info["id"])
assert call("pool.scrub.query", [["pool_name", "=", pool_name]]) == []
def test_create_scrub(scrub_info):
assert call(
"pool.scrub.create",
{
"pool": scrub_info["pool"],
"threshold": 1,
"description": "",
"schedule": {
"minute": "00",
"hour": "00",
"dom": "1",
"month": "1",
"dow": "1",
},
"enabled": True,
},
)
| 2,211 | Python | .py | 74 | 19.040541 | 75 | 0.460235 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,353 | test_278_freeipa.py | truenas_middleware/tests/api2/test_278_freeipa.py | #!/usr/bin/env python3
import pytest
import sys
import os
apifolder = os.getcwd()
sys.path.append(apifolder)
from functions import SSH_TEST
from middlewared.test.integration.assets.directory_service import ldap
from middlewared.test.integration.utils import call
from auto_config import ha, user, password
try:
from config import (
FREEIPA_IP,
FREEIPA_BASEDN,
FREEIPA_BINDDN,
FREEIPA_BINDPW,
FREEIPA_HOSTNAME,
)
except ImportError:
Reason = 'FREEIPA* variable are not setup in config.py'
pytestmark = pytest.mark.skipif(True, reason=Reason)
@pytest.fixture(scope="module")
def do_freeipa_connection():
# Confirm DNS forward
res = SSH_TEST(f"host {FREEIPA_HOSTNAME}", user, password)
assert res['result'] is True, res
# stdout: "<FREEIPA_HOSTNAME> has address <FREEIPA_IP>"
assert res['stdout'].split()[-1] == FREEIPA_IP
# DNS reverse
res = SSH_TEST(f"host {FREEIPA_IP}", user, password)
assert res['result'] is True, res
# stdout: <FREEIPA_IP_reverse_format>.in-addr.arpa domain name pointer <FREEIPA_HOSTNAME>.
assert res['stdout'].split()[-1] == FREEIPA_HOSTNAME + "."
with ldap(
FREEIPA_BASEDN,
FREEIPA_BINDDN,
FREEIPA_BINDPW,
FREEIPA_HOSTNAME,
validate_certificates=False,
) as ldap_conn:
yield ldap_conn
# Validate that our LDAP configuration alert goes away when it's disabled.
alerts = [alert['klass'] for alert in call('alert.list')]
# There's a one-shot alert that gets fired if we are an IPA domain
# connected via legacy mechanism.
assert 'IPALegacyConfiguration' not in alerts
def test_setup_and_enabling_freeipa(do_freeipa_connection):
# We are intentionally using an expired password in order to force
# a legacy-style LDAP bind. We need this support to not break
# existing FreeIPA users on update. This should be reworked in FT.
ds = call('directoryservices.status')
assert ds['type'] == 'LDAP'
assert ds['status'] == 'HEALTHY'
alerts = [alert['klass'] for alert in call('alert.list')]
# There's a one-shot alert that gets fired if we are an IPA domain
# connected via legacy mechanism.
assert 'IPALegacyConfiguration' in alerts
def test_verify_config(request):
ldap_config = call('ldap.config')
assert 'RFC2307BIS' == ldap_config['schema']
assert ldap_config['search_bases']['base_user'] == 'cn=users,cn=accounts,dc=tn,dc=ixsystems,dc=net'
assert ldap_config['search_bases']['base_group'] == 'cn=groups,cn=accounts,dc=tn,dc=ixsystems,dc=net'
assert ldap_config['search_bases']['base_netgroup'] == 'cn=ng,cn=compat,dc=tn,dc=ixsystems,dc=net'
assert ldap_config['server_type'] == 'FREEIPA'
def test_verify_that_the_freeipa_user_id_exist_on_the_nas(do_freeipa_connection):
"""
get_user_obj is a wrapper around the pwd module.
"""
pwd_obj = call('user.get_user_obj', {'username': 'ixauto_restricted', 'get_groups': True})
assert pwd_obj['pw_uid'] == 925000003
assert pwd_obj['pw_gid'] == 925000003
assert len(pwd_obj['grouplist']) >= 1, pwd_obj['grouplist']
def test_10_verify_support_for_netgroups(do_freeipa_connection):
"""
'getent netgroup' should be able to retrieve netgroup
"""
res = SSH_TEST("getent netgroup ixtestusers", user, password)
assert res['result'] is True, f"Failed to find netgroup 'ixgroup', returncode={res['returncode']}"
# Confirm expected set of users or hosts
ixgroup = res['stdout'].split()[1:]
# Confirm number of entries and some elements
assert len(ixgroup) == 3, ixgroup
assert any("testuser1" in sub for sub in ixgroup), ixgroup
| 3,702 | Python | .py | 83 | 39.662651 | 105 | 0.700222 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,354 | test_200_ftp.py | truenas_middleware/tests/api2/test_200_ftp.py | import contextlib
import copy
import json
import os
import subprocess
from ftplib import all_errors, error_temp
from time import sleep
from timeit import default_timer as timer
from types import SimpleNamespace
import pytest
from pytest_dependency import depends
from assets.websocket.server import reboot
from middlewared.test.integration.assets.account import user as ftp_user
from middlewared.test.integration.assets.pool import dataset as dataset_asset
from middlewared.test.integration.utils import call, ssh
from middlewared.test.integration.utils.client import truenas_server
from auto_config import password, pool_name, user
from functions import SSH_TEST, send_file
from protocols import ftp_connect, ftp_connection, ftps_connection
FTP_DEFAULT = {}
DB_DFLT = {}
INIT_DIRS_AND_FILES = {
'path': None,
'dirs': [
{'name': 'init_dir'},
{'name': 'init_ro_dir', 'perm': '-w',
'contents': ["ReadOnlyDir_file1", "ReadOnlyDir_file2"]}
],
'files': [{'name': 'init_file', 'contents': "Contents of init_file"},
{'name': 'init_ro_file', 'contents': "RO data", 'perm': '-w'}],
}
# ================= Utility Functions ==================
@pytest.fixture(scope='module')
def ftp_init_db_dflt():
# Get the 'default' settings from FTPModel
ftpconf_script = '#!/usr/bin/python3\n'
ftpconf_script += 'import json\n'
ftpconf_script += 'from middlewared.plugins.ftp import FTPModel\n'
ftpconf_script += 'FTPModel_defaults = {}\n'
ftpconf_script += 'for attrib in FTPModel.__dict__.keys():\n'
ftpconf_script += ' if attrib[:4] == "ftp_":\n'
ftpconf_script += ' try:\n'
ftpconf_script += ' val = getattr(getattr(FTPModel, attrib), "default").arg\n'
ftpconf_script += ' except AttributeError:\n'
ftpconf_script += ' val = None\n'
ftpconf_script += ' if not callable(val):\n'
ftpconf_script += ' FTPModel_defaults[attrib] = val\n'
ftpconf_script += 'print(json.dumps(FTPModel_defaults))\n'
cmd_file = open('ftpconf.py', 'w')
cmd_file.writelines(ftpconf_script)
cmd_file.close()
results = send_file('ftpconf.py', 'ftpconf.py', user, password, truenas_server.ip)
assert results['result'], str(results['output'])
rv_defaults = SSH_TEST("python3 ftpconf.py", user, password)
assert rv_defaults['result'], str(rv_defaults)
global FTP_DEFAULT
FTP_DEFAULT = json.loads(rv_defaults['stdout'].strip())
# clean up the temporary script
os.remove('ftpconf.py')
results = SSH_TEST('rm ftpconf.py', user, password)
assert results['result'] is True, results
# # Special cases: The default banner is in a file (see proftpd.conf.mako)
assert FTP_DEFAULT['ftp_banner'] is None, FTP_DEFAULT['ftp_banner']
# Make the default model keys match the DB names
global DB_DFLT
DB_DFLT = {k.replace('ftp_', ''): FTP_DEFAULT[k] for k in FTP_DEFAULT}
return DB_DFLT
def ftp_set_config(config={}):
# Fixup some settings
if config != {}:
tmpconf = config.copy()
if 'banner' in tmpconf and tmpconf['banner'] is None:
tmpconf['banner'] = ""
if 'anonpath' in tmpconf and tmpconf['anonpath'] is False:
tmpconf['anonpath'] = ""
if 'masqaddress' in tmpconf and tmpconf['masqaddress'] is None:
tmpconf['masqaddress'] = ''
if 'ssltls_certificate_id' in tmpconf and tmpconf['ssltls_certificate_id'] is None:
tmpconf.pop('ssltls_certificate_id')
if 'options' in tmpconf and tmpconf['options'] is None:
tmpconf['options'] = ''
call('ftp.update', tmpconf)
def parse_conf_file(file='proftpd'):
results = SSH_TEST(f"cat /etc/proftpd/{file}.conf", user, password)
assert results['result'], str(results)
lines = results['stdout'].splitlines()
rv = {}
context = [{'server': None}]
for line in lines:
line = line.lstrip()
if not line or line.startswith('#'):
continue
# Keep track of contexts
if line.startswith('<'):
if line[1] == "/":
context.pop()
continue
else:
c = line.split()[0][1:]
v = line.split()[1][:-1] if len(line.split()) > 1 else None
context.append({c: v})
continue
# Process the directive
if 1 < len(line.strip().split()):
# Trap TransferRate directive
if "TransferRate" == line.split()[0]:
tmp = line.split()
directive = ' '.join(tmp[:2])
value = ' '.join(tmp[2:])
else:
directive, value = line.strip().split(maxsplit=1)
else:
directive = line.strip()
value = None
entry = {directive: [copy.deepcopy(context), value]}
rv.update(entry)
return rv
def query_ftp_service():
return call('service.query', [['service', '=', 'ftp']], {'get': True})
def validate_proftp_conf():
'''
Confirm FTP configuration settings
NB: Avoid calling this for localuser* and anonuser* in the same test
'''
xlat = {True: "on", False: "off"}
# Retrieve result from the database
ftpConf = call('ftp.config')
parsed = parse_conf_file('proftpd')
# Sanity spot check settings in proftpd.conf
assert ftpConf['port'] == int(parsed['Port'][1])
assert ftpConf['clients'] == int(parsed['MaxClients'][1]), f"\nftpConf={ftpConf}\nparsed={parsed}"
assert ftpConf['ipconnections'] == int(parsed['MaxConnectionsPerHost'][1])
assert ftpConf['loginattempt'] == int(parsed['MaxLoginAttempts'][1])
assert ftpConf['timeout'] == int(parsed['TimeoutIdle'][1])
assert ftpConf['timeout_notransfer'] == int(parsed['TimeoutNoTransfer'][1])
# Confirm that rootlogin has been removed.
assert ftpConf.get('rootlogin') is None
if ftpConf['onlyanonymous']:
assert 'User' in parsed
assert ftpConf['anonpath'] == parsed['User'][0][1]['Anonymous'], f"parsed['User'] = {parsed['User']}"
assert parsed['UserAlias'][1] == 'anonymous ftp'
assert parsed['Group'][1] == 'ftp'
assert 'LOGIN' == parsed['AllowAll'][0][2]['Limit'], \
f"AllowAll must be within <imit LOGIN>, {parsed['AllowAll']}"
else:
assert parsed['User'][1] == 'nobody'
if ftpConf['onlylocal']:
assert 'AllowAll' in parsed
assert 'LOGIN' == parsed['AllowAll'][0][1]['Limit'], \
f"AllowAll must be within <imit LOGIN>, {parsed['AllowAll']}"
else:
if not ftpConf['onlyanonymous']:
assert 'AllowAll' not in parsed
# The absence of onlyanonymous and onlyonly mean some settings are present
if not (ftpConf['onlyanonymous'] or ftpConf['onlylocal']):
assert 'DenyAll' in parsed
assert 'LOGIN' == parsed['DenyAll'][0][1]['Limit']
# Confirm rootlogin has been removed.
assert 'root' not in parsed['AllowGroup']
# The banner is saved to a file
rv_motd = SSH_TEST("cat /etc/proftpd/proftpd.motd", user, password)
assert rv_motd['result'], str(rv_motd)
motd = rv_motd['stdout'].strip()
if ftpConf['banner']:
assert motd == ftpConf['banner'], f"\nproftpd.motd = \'{motd}\'\nbanner = \'{ftpConf['banner']}\'"
expect_umask = f"{ftpConf['filemask']} {ftpConf['dirmask']}"
assert expect_umask == parsed['Umask'][1], \
f"Found unexpected Umask entry: expected '{expect_umask}', found '{parsed['Umask'][1]}'"
assert xlat[ftpConf['fxp']] == parsed['AllowForeignAddress'][1]
if ftpConf['resume']:
assert xlat[ftpConf['resume']] == parsed['AllowRetrieveRestart'][1]
assert xlat[ftpConf['resume']] == parsed['AllowStoreRestart'][1]
# The DefaultRoot setting is defined completly in proftpd.conf.mako as '~ !root'
if ftpConf['defaultroot']:
assert parsed['DefaultRoot'][1] == "~ !root"
assert xlat[ftpConf['ident']] == parsed['IdentLookups'][1]
assert xlat[ftpConf['reversedns']] == parsed['UseReverseDNS'][1]
if ftpConf['masqaddress']:
assert ftpConf['masqaddress'] == parsed['MasqueradeAddress'][1]
if ftpConf['passiveportsmin']:
expect_setting = f"{ftpConf['passiveportsmin']} {ftpConf['passiveportsmax']}"
assert expect_setting == parsed['PassivePorts'][1], \
f"Found unexpected PassivePorts entry: expected '{expect_setting}', found '{parsed['PassivePorts'][1]}'"
if ftpConf['localuserbw']:
assert ftpConf['localuserbw'] == int(parsed['TransferRate STOR'][1])
if ftpConf['localuserdlbw']:
assert ftpConf['localuserdlbw'] == int(parsed['TransferRate RETR'][1])
if ftpConf['anonuserbw']:
assert ftpConf['anonuserbw'] == int(parsed['TransferRate STOR'][1])
if ftpConf['anonuserdlbw']:
assert ftpConf['anonuserdlbw'] == int(parsed['TransferRate RETR'][1])
if ftpConf['tls']:
parsed = parsed | parse_conf_file('tls')
# These two are 'fixed' settings in proftpd.conf.mako, but they are important
assert parsed['TLSEngine'][1] == 'on'
assert parsed['TLSProtocol'][1] == 'TLSv1.2 TLSv1.3'
if 'TLSOptions' in parsed:
# Following the same method from proftpd.conf.mako
tls_options = []
for k, v in [
('allow_client_renegotiations', 'AllowClientRenegotiations'),
('allow_dot_login', 'AllowDotLogin'),
('allow_per_user', 'AllowPerUser'),
('common_name_required', 'CommonNameRequired'),
('enable_diags', 'EnableDiags'),
('export_cert_data', 'ExportCertData'),
('no_empty_fragments', 'NoEmptyFragments'),
('no_session_reuse_required', 'NoSessionReuseRequired'),
('stdenvvars', 'StdEnvVars'),
('dns_name_required', 'dNSNameRequired'),
('ip_address_required', 'iPAddressRequired'),
]:
if ftpConf[f'tls_opt_{k}']:
tls_options.append(v)
assert set(tls_options) == set(parsed['TLSOptions'][1].split()), \
f"--- Unexpected difference ---\ntls_options:\n{set(tls_options)}"\
f"\nparsed['TLSOptions']\n{set(parsed['TLSOptions'][1].split())}"
assert ftpConf['tls_policy'] == parsed['TLSRequired'][1]
# Do a sanity check on the certificate entries
assert 'TLSRSACertificateFile' in parsed
assert 'TLSRSACertificateKeyFile' in parsed
# Return the current welcome message
return ftpConf, motd
@contextlib.contextmanager
def ftp_configure(changes=None):
'''
Apply requested FTP configuration changes.
Restore original setting when done
'''
changes = changes or {}
ftpConf = call('ftp.config')
restore_keys = set(ftpConf) & set(changes)
restore_items = {key: ftpConf[key] for key in restore_keys}
if changes:
try:
call('ftp.update', changes)
yield
finally:
# Restore settings
call('ftp.update', restore_items)
# Validate the restore
validate_proftp_conf()
def ftp_set_service_enable_state(state=None):
'''
Get and return the current state struct
Set the requested state
'''
restore_setting = None
if state is not None:
assert isinstance(state, bool)
# save current setting
restore_setting = query_ftp_service()['enable']
# update to requested setting
call('service.update', 'ftp', {'enable': state})
return restore_setting
@contextlib.contextmanager
def ftp_server(service_state=None):
'''
Start FTP server with current config
Stop server when done
'''
# service 'enable' state
if service_state is not None:
restore_state = ftp_set_service_enable_state(service_state)
try:
# Start FTP service
call('service.start', 'ftp', {'silent': False})
yield
finally:
# proftpd can core dump if stopped while it's busy
# processing a prior config change. Give it a sec.
sleep(1)
call('service.stop', 'ftp', {'silent': False})
# Restore original service state
if service_state is not None:
ftp_set_service_enable_state(restore_state)
@contextlib.contextmanager
def ftp_anon_ds_and_srvr_conn(dsname='ftpdata', FTPconfig=None, useFTPS=None, withConn=None, **kwargs):
FTPconfig = FTPconfig or {}
withConn = withConn or True
with dataset_asset(dsname, **kwargs) as ds:
ds_path = f"/mnt/{ds}"
# Add files and dirs
ftp_dirs_and_files = INIT_DIRS_AND_FILES.copy()
ftp_dirs_and_files['path'] = ds_path
ftp_init_dirs_and_files(ftp_dirs_and_files)
with ftp_server():
anon_config = {
"onlyanonymous": True,
"anonpath": ds_path,
"onlylocal": False,
**FTPconfig
}
with ftp_configure(anon_config):
ftpConf, motd = validate_proftp_conf()
if withConn:
with (ftps_connection if useFTPS else ftp_connection)(truenas_server.ip) as ftp:
yield SimpleNamespace(ftp=ftp, dirs_and_files=ftp_dirs_and_files,
ftpConf=ftpConf, motd=motd)
@contextlib.contextmanager
def ftp_user_ds_and_srvr_conn(dsname='ftpdata', username="FTPlocal", FTPconfig=None, useFTPS=False, **kwargs):
FTPconfig = FTPconfig or {}
with dataset_asset(dsname, **kwargs) as ds:
ds_path = f"/mnt/{ds}"
with ftp_user({
"username": username,
"group_create": True,
"home": ds_path,
"full_name": username + " User",
"password": "secret",
"home_create": False,
"smb": False,
"groups": [call('group.query', [['name', '=', 'ftp']], {'get': True})['id']],
}):
# Add dirs and files
ftp_dirs_and_files = INIT_DIRS_AND_FILES.copy()
ftp_dirs_and_files['path'] = ds_path
ftp_init_dirs_and_files(ftp_dirs_and_files)
with ftp_server():
with ftp_configure(FTPconfig):
ftpConf, motd = validate_proftp_conf()
with (ftps_connection if useFTPS else ftp_connection)(truenas_server.ip) as ftp:
yield SimpleNamespace(ftp=ftp, dirs_and_files=ftp_dirs_and_files, ftpConf=ftpConf, motd=motd)
def ftp_get_users():
'''
Return a list of active users
NB: ftp service should be running when called
'''
ssh_out = SSH_TEST("ftpwho -o json", user, password)
assert ssh_out['result'], str(ssh_out)
output = ssh_out['output']
# Strip off trailing bogus data
joutput = output[:output.rindex('}') + 1]
whodata = json.loads(joutput)
return whodata['connections']
# For resume xfer test
def upload_partial(ftp, src, tgt, NumKiB=128):
with open(src, 'rb') as file:
ftp.voidcmd('TYPE I')
with ftp.transfercmd(f'STOR {os.path.basename(tgt)}', None) as conn:
blksize = NumKiB // 8
for xfer in range(0, 8):
# Send some of the file
buf = file.read(1024 * blksize)
assert buf, "Unexpected local read error"
conn.sendall(buf)
def download_partial(ftp, src, tgt, NumKiB=128):
with open(tgt, 'wb') as file:
ftp.voidcmd('TYPE I')
with ftp.transfercmd(f'RETR {os.path.basename(src)}', None) as conn:
NumXfers = NumKiB // 8
for xfer in range(0, NumXfers):
# Receive and write some of the file
data = conn.recv(8192)
assert data, "Unexpected receive error"
file.write(data)
def ftp_upload_binary_file(ftpObj, source, target, offset=None):
"""
Upload a file to the FTP server
INPUT:
source is the full-path to local file
target is the name to use on the FTP server
RETURN:
Elapsed time to upload file
"""
assert ftpObj is not None
assert source is not None
assert target is not None
with open(source, 'rb') as fp:
if offset:
fp.seek(offset)
start = timer()
ftpObj.storbinary(f'STOR {os.path.basename(target)}', fp, rest=offset)
et = timer() - start
return et
def ftp_download_binary_file(ftpObj, source, target, offset=None):
"""
Download a file from the FTP server
INPUT:
source is the name of the file on the FTP server
target is full-path name on local host
RETURN:
Elapsed time to download file
"""
assert ftpObj is not None
assert source is not None
assert target is not None
opentype = 'ab' if offset else 'wb'
with open(target, opentype) as fp:
start = timer()
ftpObj.retrbinary(f'RETR {os.path.basename(source)}', fp.write, rest=offset)
et = timer() - start
return et
def ftp_create_local_file(LocalPathName="", content=None):
'''
Create a local file
INPUT:
If 'content' is:
- None, then create with touch
- 'int', then it represents the size in KiB to fill with random data
- 'str', then write that to the file
If 'content is not None, 'int' or 'str', then assert
RETURN:
tuple: (size_in_bytes, sha256_checksum)
'''
assert LocalPathName != "", "empty file name"
b = '' if isinstance(content, str) else 'b'
# Create a local file
with open(LocalPathName, 'w' + b) as f:
if (content is None) or isinstance(content, str):
content = content or ""
f.write(content)
elif isinstance(content, int):
f.write(os.urandom(1024 * content))
else:
assert True, f"Cannot create with content: '{content}'"
# Confirm existence
assert os.path.exists(LocalPathName)
localsize = os.path.getsize(LocalPathName)
res = subprocess.run(["sha256sum", LocalPathName], capture_output=True)
local_chksum = res.stdout.decode().split()[0]
return (localsize, local_chksum)
def ftp_create_remote_file(RemotePathName="", content=None):
'''
Create a remote file
INPUT:
If 'content' is:
- None, then create with touch
- 'int', then it represents the size in KiB to fill with random data
- 'str', then write that to the file
If 'content is not None, 'int' or 'str', then assert
RETURN:
tuple: (size_in_bytes, sha256_checksum)
'''
assert RemotePathName != "", "empty file name"
if content is None:
ssh(f'touch {RemotePathName}')
elif isinstance(content, int):
ssh(f"dd if=/dev/urandom of={RemotePathName} bs=1K count={content}", complete_response=True)
elif isinstance(content, str):
ssh(f'echo "{content}" > {RemotePathName}')
else:
assert True, f"Cannot create with content: '{content}'"
# Get and return the details
remotesize = ssh(f"du -b {RemotePathName}").split()[0]
remote_chksum = ssh(f"sha256sum {RemotePathName}").split()[0]
return (remotesize, remote_chksum)
def ftp_init_dirs_and_files(items=None):
if items is not None:
assert items['path'] is not None
path = items['path']
for d in items['dirs']:
res = SSH_TEST(f"mkdir -p {path}/{d['name']}", user, password)
assert res['result'], str(res)
thispath = f"{path}/{d['name']}"
if 'contents' in d:
for f in d['contents']:
res = SSH_TEST(f"touch {thispath}/{f}", user, password)
assert res['result'], str(res)
if 'perm' in d:
res = SSH_TEST(f"chmod {d['perm']} {thispath}", user, password)
assert res['result'], str(res)
for f in items['files']:
res = SSH_TEST(f"echo \'{f['contents']}\' > \'{path}/{f['name']}\'", user, password)
assert res['result'], str(res)
if 'perm' in f:
res = SSH_TEST(f"chmod {f['perm']} {path}/{f['name']}", user, password)
assert res['result'], str(res)
def init_test_data(type='unknown', data=None):
assert data is not None
new_test_data = {}
new_test_data['type'] = type
new_test_data['ftp'] = data.ftp
new_test_data['ftpConf'] = data.ftpConf
new_test_data['motd'] = data.motd
new_test_data['dirs_and_files'] = data.dirs_and_files
return new_test_data
def ftp_ipconnections_test(test_data=None, *extra):
'''
Test FTP MaxConnectionsPerHost conf setting.
The DB equivalent is ipconnections.
NB1: This is called with an existing connection
'''
assert test_data['ftp'] is not None
ftpConf = test_data['ftpConf']
ConnectionLimit = int(ftpConf['ipconnections'])
# We already have one connection
NumConnects = 1
NewConnects = []
while NumConnects < ConnectionLimit:
try:
ftpConn = ftp_connect(truenas_server.ip)
except all_errors as e:
assert False, f"Unexpected connection error: {e}"
NewConnects.append(ftpConn)
NumConnects += 1
CurrentFtpUsers = ftp_get_users()
assert len(CurrentFtpUsers) == ConnectionLimit
try:
# This next connect should fail
ftp_connect(truenas_server.ip)
except all_errors as e:
# An expected error
assert NumConnects == ConnectionLimit
assert e.args[0].startswith('530')
assert f"maximum number of connections ({ConnectionLimit})" in e.args[0]
finally:
# Clean up extra connections
for conn in NewConnects:
conn.quit()
def ftp_dir_listing_test(test_data=None, *extra):
'''
Get a directory listing
'''
assert test_data is not None
ftp = test_data['ftp']
listing = [name for name, facts in list(ftp.mlsd())]
expected = test_data['dirs_and_files']
# Get expected
for f in expected['files']:
assert f['name'] in listing, f"Did not find {f['name']}"
for d in expected['dirs']:
assert f['name'] in listing, f"Did not find {f['name']}"
def ftp_download_files_test(test_data=None, run_data=None):
'''
Retrieve files from server and confirm contents
'''
assert test_data is not None
ftp = test_data['ftp']
expected_contents = None
for f in run_data:
if f['contents'] is None:
continue
expected_contents = f['contents']
found_contents = []
cmd = f"RETR {f['name']}"
try:
res = ftp.retrlines(cmd, found_contents.append)
assert f['expect_to_pass'] is True, \
f"Expected file download failure for {f['name']}, but passed: {f}"
assert res.startswith('226 Transfer complete'), "Detected download failure"
assert expected_contents in found_contents
except all_errors as e:
assert f['expect_to_pass'] is False, \
f"Expected file download success for {f['name']}, but failed: {e.args}"
def ftp_upload_files_test(test_data=None, run_data=None):
'''
Upload files to the server
'''
localfile = "/tmp/ftpfile"
assert test_data is not None
assert run_data != []
ftp = test_data['ftp']
try:
for f in run_data:
if 'content' in f and isinstance(f['content'], str):
ftp_create_local_file(localfile, f['content'])
with open(localfile, 'rb') as tmpfile:
try:
cmd = f"STOR {f['name']}"
res = ftp.storlines(cmd, tmpfile)
assert f['expect_to_pass'] is True, \
f"Expected file add failure for {f['name']}, but passed: {f}"
assert res.startswith('226 Transfer complete'), "Detected upload failure"
except all_errors as e:
assert f['expect_to_pass'] is False, \
f"Expected file add success for {f['name']}, but failed: {e.args}"
finally:
# Clean up
if os.path.exists(localfile):
os.remove(localfile)
def ftp_delete_files_test(test_data=None, run_data=None):
'''
Delete files on the server
'''
assert test_data is not None
assert run_data != []
ftp = test_data['ftp']
for f in run_data:
try:
ftp.delete(f['name'])
assert f['expect_to_pass'] is True, \
f"Expected file delete failure for {f['name']}, but passed: {f}"
except all_errors as e:
assert f['expect_to_pass'] is False, \
f"Expected file delete success for {f['name']}, but failed: {e.args}"
def ftp_add_dirs_test(test_data=None, run_data=None):
'''
Create directories on the server
'''
assert test_data is not None
assert run_data != []
ftp = test_data['ftp']
for d in run_data:
try:
res = ftp.mkd(d['name'])
assert d['name'] in res
except all_errors as e:
assert d['expect_to_pass'] is False, \
f"Expected deletion success for {d['name']}, but failed: {e.args}"
def ftp_remove_dirs_test(test_data=None, run_data=None):
'''
Delete directories on the server
'''
assert test_data is not None
assert run_data != []
ftp = test_data['ftp']
for d in run_data:
try:
ftp.rmd(d['name'])
assert d['expect_to_pass'] is True, \
f"Expected deletion failure for {d['name']}, but passed: {d}"
except all_errors as e:
assert d['expect_to_pass'] is False, \
f"Expected deletion success for {d['name']}, but failed: {e.args}"
#
# ================== TESTS =========================
#
@pytest.mark.dependency(name='init_dflt_config')
def test_001_validate_default_configuration(request, ftp_init_db_dflt):
'''
Confirm the 'default' settings in the DB are in sync with what
is specified in the FTPModel class. These can get out of sync
with migration code.
NB1: This expects FTP to be in the default configuration
'''
ftp_set_config(DB_DFLT)
with ftp_server():
# Get the DB settings
db = call('ftp.config')
# Check each setting
diffs = {}
for setting in set(DB_DFLT) & set(db):
# Special cases: ftp_anonpath is 'nullable' in the DB, but the default is False
if setting == "anonpath" and (db[setting] == '' or db[setting] is None):
db[setting] = False
# Special cases: Restore 'None' for empty string
if setting in ['banner', 'options', 'masqaddress'] and db[setting] == '':
db[setting] = None
if DB_DFLT[setting] != db[setting]:
diffs.update({setting: [DB_DFLT[setting], db[setting]]})
assert len(diffs) == 0, f"Found mismatches: [DB_DFLT, db]\n{diffs}"
def test_005_ftp_service_at_boot(request):
'''
Confirm we can enable FTP service at boot and restore current setting
'''
# Get the current state and set the new state
restore_setting = ftp_set_service_enable_state(True)
assert restore_setting is False, f"Unexpected service at boot setting: enable={restore_setting}, expected False"
# Confirm we toggled the setting
res = query_ftp_service()['enable']
assert res is True, res
# Restore original setting
ftp_set_service_enable_state(restore_setting)
def test_010_ftp_service_start(request):
'''
Confirm we can start the FTP service with the default config
Confirm the proftpd.conf file was generated
'''
# Start FTP service
with ftp_server():
# Validate the service is running via our API
assert query_ftp_service()['state'] == 'RUNNING'
# Confirm we have /etc/proftpd/proftpd.conf
rv_conf = SSH_TEST("ls /etc/proftpd/proftpd.conf", user, password)
assert rv_conf['result'], str(rv_conf)
def test_015_ftp_configuration(request):
'''
Confirm config changes get reflected in proftpd.conf
'''
depends(request, ["init_dflt_config"], scope="session")
with ftp_server():
changes = {
'clients': 100,
'ipconnections': 10,
'loginattempt': 100,
'banner': 'A banner to remember',
'onlylocal': True,
'fxp': True
}
with ftp_configure(changes):
validate_proftp_conf()
def test_017_ftp_port(request):
'''
Confirm config changes get reflected in proftpd.conf
'''
depends(request, ["init_dflt_config"], scope="session")
with ftp_server():
assert query_ftp_service()['state'] == 'RUNNING'
# Confirm FTP is listening on the default port
res = SSH_TEST("ss -tlpn", user, password)
sslist = res['output'].splitlines()
ftp_entry = [line for line in sslist if "ftp" in line]
ftpPort = ftp_entry[0].split()[3][2:]
assert ftpPort == "21", f"Expected default FTP port, but found {ftpPort}"
# Test port change
changes = {'port': 22222}
with ftp_configure(changes):
validate_proftp_conf()
res = SSH_TEST("ss -tlpn", user, password)
sslist = res['output'].splitlines()
ftp_entry = [line for line in sslist if "ftp" in line]
ftpPort = ftp_entry[0].split()[3][2:]
assert ftpPort == "22222", f"Expected '22222' FTP port, but found {ftpPort}"
# @pytest.mark.parametrize("NumTries,expect_to_pass"m )
@pytest.mark.parametrize('NumFailedTries,expect_to_pass', [
(2, True),
(3, False)
])
def test_020_login_attempts(request, NumFailedTries, expect_to_pass):
'''
Test our ability to change and trap excessive failed login attempts
1) Test good password before running out of tries
2) Test good password after running out of tries
'''
depends(request, ["init_dflt_config"], scope="session")
login_setup = {
"onlylocal": True,
"loginattempt": 3,
}
with ftp_user_ds_and_srvr_conn('ftplocalDS', 'FTPfatfingeruser', login_setup) as loginftp:
MaxTries = loginftp.ftpConf['loginattempt']
ftpObj = loginftp.ftp
for login_attempt in range(0, NumFailedTries):
try:
# Attempt login with bad password
ftpObj.login(user='FTPfatfingeruser', passwd="secrfet")
except all_errors as all_e:
assert True, f"Unexpected login failure: {all_e}"
except EOFError as eof_e:
assert True, f"Unexpected disconnect: {eof_e}"
if expect_to_pass:
# Try with correct password
ftpObj.login(user='FTPfatfingeruser', passwd="secret")
assert expect_to_pass is True
else:
with pytest.raises(Exception):
# Try with correct password, but already exceeded number of tries
ftpObj.login(user='FTPfatfingeruser', passwd="secret")
assert login_attempt < MaxTries, "Failed to limit login attempts"
def test_030_root_login(request):
'''
"Allow Root Login" setting has been removed.
Confirm we block root login.
'''
depends(request, ["init_dflt_config"], scope="session")
with ftp_anon_ds_and_srvr_conn('anonftpDS') as ftpdata:
ftpObj = ftpdata.ftp
try:
res = ftpObj.login(user, password)
assert True, f"Unexpected behavior: root login was supposed to fail, but login response is {res}"
except all_errors:
pass
@pytest.mark.parametrize('setting,ftpConfig', [
(True, {"onlyanonymous": True, "anonpath": "anonftpDS", "onlylocal": False}),
(False, {"onlyanonymous": False, "anonpath": "", "onlylocal": True}),
])
def test_031_anon_login(request, setting, ftpConfig):
'''
Test the WebUI "Allow Anonymous Login" setting.
In our DB the setting is "onlyanonymous" and an "Anonymous" section in proftpd.conf.
'''
depends(request, ["init_dflt_config"], scope="session")
if setting is True:
# Fixup anonpath
ftpConfig['anonpath'] = f"/mnt/{pool_name}/{ftpConfig['anonpath']}"
with ftp_anon_ds_and_srvr_conn('anonftpDS', ftpConfig) as ftpdata:
ftpObj = ftpdata.ftp
try:
res = ftpObj.login()
assert setting is True, \
f"Unexpected behavior: onlyanonymous={ftpConfig['onlyanonymous']}, but login successfull: {res}"
# The following assumes the login was successfull
assert res.startswith('230')
ftpusers = ftp_get_users()
assert 'ftp' == ftpusers[0]['user']
except all_errors as e:
assert setting is False, f"Unexpected failure, onlyanonymous={setting}, but got {e}"
@pytest.mark.parametrize('localuser,expect_to_pass', [
("FTPlocaluser", True),
("BadUser", False)
])
def test_032_local_login(request, localuser, expect_to_pass):
depends(request, ["init_dflt_config"], scope="session")
with ftp_user_ds_and_srvr_conn('ftplocalDS', 'FTPlocaluser', {"onlylocal": True}) as ftpdata:
ftpObj = ftpdata.ftp
try:
ftpObj.login(localuser, 'secret')
assert expect_to_pass, f"Unexpected behavior: {user} should not have been allowed to login"
except all_errors as e:
assert not expect_to_pass, f"Unexpected behavior: {user} should have been allowed to login. {e}"
def test_040_reverse_dns(request):
depends(request, ["init_dflt_config"], scope="session")
ftp_conf = {"onlylocal": True, "reversedns": True}
with ftp_user_ds_and_srvr_conn('ftplocalDS', 'FTPlocaluser', ftp_conf) as ftpdata:
ftpObj = ftpdata.ftp
try:
ftpObj.login('FTPlocaluser', 'secret')
except all_errors as e:
assert False, f"Login failed with reverse DNS enabled. {e}"
@pytest.mark.parametrize('masq_type, expect_to_pass',
[("hostname", True), ("ip_addr", True), ("invalid.domain", False)])
def test_045_masquerade_address(request, masq_type, expect_to_pass):
'''
TrueNAS tooltip:
Public IP address or hostname. Set if FTP clients cannot connect through a NAT device.
We test masqaddress with: hostname, IP address and an invalid fqdn.
'''
depends(request, ["init_dflt_config"], scope="session")
netconfig = call('network.configuration.config')
if masq_type == 'hostname':
masqaddr = netconfig['hostname']
if netconfig['domain'] and netconfig['domain'] != "local":
masqaddr = masqaddr + "." + netconfig['domain']
elif masq_type == 'ip_addr':
masqaddr = truenas_server.ip
else:
masqaddr = masq_type
ftp_conf = {"onlylocal": True, "masqaddress": masqaddr}
with pytest.raises(Exception) if not expect_to_pass else contextlib.nullcontext():
with ftp_user_ds_and_srvr_conn('ftplocalDS', 'FTPlocaluser', ftp_conf) as ftpdata:
ftpObj = ftpdata.ftp
try:
ftpObj.login('FTPlocaluser', 'secret')
res = ftpObj.sendcmd('PASV')
assert res.startswith("227 Entering Passive Mode")
srvr_ip, p1, p2 = res.split('(', 1)[1].split(')')[0].rsplit(',', 2)
srvr_ip = srvr_ip.replace(',', '.')
# If the masquerade is our hostname the presented IP address will
# be the 'local' IP address
if masq_type == "hostname":
assert srvr_ip == '127.0.0.1'
else:
assert srvr_ip == truenas_server.ip
except all_errors as e:
assert False, f"FTP failed with masqaddres = '{masqaddr}'. {e}"
@pytest.mark.parametrize('testing,ftpConfig,expect_to_pass', [
("config", {"passiveportsmin": 100}, False),
("config", {"passiveportsmin": 3000, "passiveportsmax": 2000}, False),
("config", {"passiveportsmin": 2000, "passiveportsmax": 2000}, False),
("run", {"passiveportsmin": 22222, "passiveportsmax": 22223}, True),
])
def test_050_passive_ports(request, testing, ftpConfig, expect_to_pass):
'''
Test the passive port range setting.
NB: The proFTPd documentation for this setting states:
| Should no open ports be found within the configured range, the server will default
| to a random kernel-assigned port, and a message logged.
'''
depends(request, ["init_dflt_config"], scope="session")
if testing == 'config':
try:
with ftp_configure(ftpConfig):
assert expect_to_pass is True
except Exception as e:
assert expect_to_pass is False, f"{e['error']}"
else:
with ftp_anon_ds_and_srvr_conn('anonftpDS', ftpConfig) as ftpdata:
ftpObj = ftpdata.ftp
try:
res = ftpObj.login()
# The confirm the login was successfull
assert res.startswith('230')
res = ftpObj.sendcmd('PASV')
assert res.startswith("227 Entering Passive Mode")
# The response includes the server IP and passive port
# Convert '227 Entering Passive Mode (a,b,c,d,e,f)' to ['a,b,c,d', 'e', 'f']
srvr_ip, p1, p2 = res.split('(', 1)[1].split(')')[0].rsplit(',', 2)
# Calculate the passive port
pasv_port = int(p1) * 256 + int(p2)
assert srvr_ip.replace(',', '.') == truenas_server.ip
assert pasv_port == ftpdata.ftpConf['passiveportsmin']
except all_errors as e:
assert expect_to_pass is False, f"Unexpected failure, {e}"
def test_055_no_activity_timeout(request):
'''
Test the WebUI "Timeout" setting. In our DB it is "timeout" and "TimeoutIdle" in proftpd.conf.
| The TimeoutIdle directive configures the maximum number of seconds that proftpd will
! allow clients to stay connected without receiving any data on either the control or data connection
'''
depends(request, ["init_dflt_config"], scope="session")
with ftp_anon_ds_and_srvr_conn('anonftpDS', {'timeout': 3}) as ftpdata:
ftpObj = ftpdata.ftp
try:
ftpObj.login()
sleep(ftpdata.ftpConf['timeout'] + 1)
ftpObj.nlst()
assert False, "Unexpected behavior: 'Activity Timeout' did not occur. "\
"Expected listing to fail, but it succeeded."
except all_errors as e:
chkstr = f"Idle timeout ({ftpdata.ftpConf['timeout']} seconds)"
assert chkstr in str(e), e
def test_056_no_xfer_timeout(request):
'''
This tests the WebUI "Notransfer Timeout" setting. In our DB it is "timeout_notransfer"
and "TimeoutNoTranfer" in proftpd.conf.
| The TimeoutNoTransfer directive configures the maximum number of seconds a client
| is allowed to spend connected, after authentication, without issuing a data transfer command
| which results in a data connection (i.e. sending/receiving a file, or requesting a directory listing)
'''
depends(request, ["init_dflt_config"], scope="session")
with ftp_anon_ds_and_srvr_conn('anonftpDS', {'timeout_notransfer': 3}) as ftpdata:
ftpObj = ftpdata.ftp
try:
ftpObj.login()
sleep(ftpdata.ftpConf['timeout_notransfer'] + 1)
ftpObj.nlst()
assert False, "Unexpected behavior: 'No Transfer Timeout' did not occur. "\
"Expected listing to fail, but it succeeded."
except all_errors as e:
chkstr = f"No transfer timeout ({ftpdata.ftpConf['timeout_notransfer']} seconds)"
assert chkstr in str(e), e
@pytest.mark.flaky(reruns=5, reruns_delay=5) # Can sometimes getoside the range
@pytest.mark.parametrize('testwho,ftp_setup_func', [
('anon', ftp_anon_ds_and_srvr_conn),
('local', ftp_user_ds_and_srvr_conn),
])
def test_060_bandwidth_limiter(request, testwho, ftp_setup_func):
FileSize = 1024 # KiB
ulRate = 64 # KiB
dlRate = 128 # KiB
ulConf = testwho + 'userbw'
dlConf = testwho + 'userdlbw'
depends(request, ["init_dflt_config"], scope="session")
ftp_anon_bw_limit = {
ulConf: ulRate, # upload limit
dlConf: dlRate # download limit
}
ftpfname = "BinaryFile"
with ftp_setup_func(FTPconfig=ftp_anon_bw_limit) as ftpdata:
ftpObj = ftpdata.ftp
localfname = f"/tmp/{ftpfname}"
if testwho == 'anon':
results = SSH_TEST(f"chown ftp {ftpdata.ftpConf['anonpath']}", user, password)
assert results['result'] is True, results
try:
if testwho == 'anon':
ftpObj.login()
else:
ftpObj.login('FTPlocal', 'secret')
ftpObj.voidcmd('TYPE I')
# Create local binary file
with open(localfname, 'wb') as f:
f.write(os.urandom(1024 * FileSize))
ElapsedTime = int(ftp_upload_binary_file(ftpObj, localfname, ftpfname))
xfer_rate = FileSize // ElapsedTime
# This typically will match exactly, but in actual testing this might vary
assert (ulRate - 8) <= xfer_rate <= (ulRate + 20), \
f"Failed upload rate limiter: Expected {ulRate}, but sensed rate is {xfer_rate}"
ElapsedTime = int(ftp_download_binary_file(ftpObj, ftpfname, localfname))
xfer_rate = FileSize // ElapsedTime
# Allow for variance
assert (dlRate - 8) <= xfer_rate <= (dlRate + 20), \
f"Failed download rate limiter: Expected {dlRate}, but sensed rate is {xfer_rate}"
except all_errors as e:
assert False, f"Unexpected failure: {e}"
finally:
# Clean up
if os.path.exists(localfname):
os.remove(localfname)
@pytest.mark.parametrize('fmask,f_expect,dmask,d_expect', [
("000", "0666", "000", "0777"),
("007", "0660", "002", "0775"),
])
def test_065_umask(request, fmask, f_expect, dmask, d_expect):
depends(request, ["init_dflt_config"], scope="session")
localfile = "/tmp/localfile"
fname = "filemask" + fmask
dname = "dirmask" + dmask
ftp_create_local_file(localfile, "Contents of local file")
ftp_umask = {
'filemask': fmask,
'dirmask': dmask
}
with ftp_anon_ds_and_srvr_conn('anonftpDS', ftp_umask, mode='777') as ftpdata:
ftpObj = ftpdata.ftp
try:
ftpObj.login()
# Add file and make a directory
with open(localfile, 'rb') as tmpfile:
res = ftpObj.storlines(f'STOR {fname}', tmpfile)
assert "Transfer complete" in res
res = ftpObj.mkd(dname)
assert dname in res
ftpdict = dict(ftpObj.mlsd())
assert ftpdict[fname]['unix.mode'] == f_expect, ftpdict[fname]
assert ftpdict[dname]['unix.mode'] == d_expect, ftpdict[dname]
except all_errors as e:
assert False, f"Unexpected failure: {e}"
finally:
# Clean up
if os.path.exists(localfile):
os.remove(localfile)
@pytest.mark.dependency(depends=['init_dflt_config'])
@pytest.mark.parametrize(
'ftpConf,expect_to_pass', [
({}, False),
({'resume': True}, True)
],
ids=[
"resume xfer: blocked",
"resume xfer: allowed"
]
)
@pytest.mark.parametrize(
'direction,create_src,xfer_partial,xfer_remainder', [
('upload', ftp_create_local_file, upload_partial, ftp_upload_binary_file),
('download', ftp_create_remote_file, download_partial, ftp_download_binary_file)
],
ids=[
"upload",
"download"
]
)
def test_070_resume_xfer(
ftpConf, expect_to_pass, direction, create_src, xfer_partial, xfer_remainder
):
# # ---------- helper functions ---------
def get_tgt_size(ftp, tgt, direction):
if direction == 'upload':
ftp.voidcmd('TYPE I')
return ftp.size(os.path.basename(tgt))
else:
return os.path.getsize(tgt)
def get_tgt_chksum(tgt, direction):
if direction == 'upload':
return ssh(f"sha256sum {tgt}").split()[0]
else:
res = subprocess.run(["sha256sum", tgt], capture_output=True)
assert res.returncode == 0
return res.stdout.decode().split()[0]
try:
# Run test
with ftp_anon_ds_and_srvr_conn('anonftpDS', ftpConf, withConn=False, mode='777') as ftpdata:
src_path = {'upload': "/tmp", 'download': f"{ftpdata.ftpConf['anonpath']}"}
tgt_path = {'upload': f"{ftpdata.ftpConf['anonpath']}", "download": "/tmp"}
# xfer test
try:
# Create a 1MB source binary file.
src_pathname = '/'.join([src_path[direction], 'srcfile'])
tgt_pathname = '/'.join([tgt_path[direction], 'tgtfile'])
src_size, src_chksum = create_src(src_pathname, 1024)
ftpObj = ftp_connect(truenas_server.ip)
ftpObj.login()
xfer_partial(ftpObj, src_pathname, tgt_pathname, 768)
# Quit to simulate loss of connection
try:
ftpObj.quit()
except error_temp:
# May generate a quit error that we ignore for this test
pass
ftpObj = None
sleep(1)
# Attempt resume to complete the upload
ftpObj = ftp_connect(truenas_server.ip)
ftpObj.login()
xfer_remainder(ftpObj, src_pathname, tgt_pathname, get_tgt_size(ftpObj, tgt_pathname, direction))
except all_errors as e:
assert not expect_to_pass, f"Unexpected failure in resumed {direction} test: {e}"
if not expect_to_pass:
assert "Restart not permitted" in str(e), str(e)
if expect_to_pass:
# Check upload result
tgt_size = get_tgt_size(ftpObj, tgt_pathname, direction)
assert int(tgt_size) == int(src_size), \
f"Failed {direction} size test. Expected {src_size}, found {tgt_size}"
tgt_chksum = get_tgt_chksum(tgt_pathname, direction)
assert src_chksum == tgt_chksum, \
f"Failed {direction} checksum test. Expected {src_chksum}, found {tgt_chksum}"
finally:
try:
[os.remove(file) for file in ['/tmp/srcfile', '/tmp/tgtfile']]
except OSError:
pass
class UserTests:
"""
Run the same suite of tests for all users
"""
ftp_user_tests = [
(ftp_dir_listing_test, []),
(ftp_ipconnections_test, []),
(ftp_download_files_test, [
{'name': 'init_file', 'contents': "Contents of init_file", 'expect_to_pass': True},
{'name': 'init_ro_file', 'contents': "RO data", 'expect_to_pass': True},
]),
(ftp_upload_files_test, [
{'name': 'DeleteMeFile', 'content': 'To be deleted', 'expect_to_pass': True},
{'name': 'init_ro_file', 'expect_to_pass': False},
]),
(ftp_delete_files_test, [
{'name': 'DeleteMeFile', 'expect_to_pass': True},
{'name': 'bogus_file', 'expect_to_pass': False},
{'name': 'init_ro_dir/ReadOnlyDir_file1', 'expect_to_pass': False},
]),
(ftp_add_dirs_test, [
{'name': 'DeleteMeDir', 'expect_to_pass': True},
]),
(ftp_remove_dirs_test, [
{'name': 'DeleteMeDir', 'expect_to_pass': True},
{'name': 'bogus_dir', 'expect_to_pass': False},
{'name': 'init_ro_dir', 'expect_to_pass': False},
])
]
@pytest.mark.parametrize("user_test,run_data", ftp_user_tests)
def test_080_ftp_user(self, setup, user_test, run_data):
try:
user_test(setup, run_data)
except all_errors as e:
assert e is None, f"FTP error: {e}"
class TestAnonUser(UserTests):
"""
Create a dataset with some data to be used for anonymous FTP
Start FTP server configured for anonymous
Create an anonymous FTP connection and login
"""
@pytest.fixture(scope='class')
def setup(self, request):
depends(request, ["init_dflt_config"], scope="session")
with ftp_anon_ds_and_srvr_conn('anonftpDS') as anonftp:
# Make the directory owned by the anonymous ftp user
anon_path = anonftp.dirs_and_files['path']
results = SSH_TEST(f"chown ftp {anon_path}", user, password)
assert results['result'] is True, results
login_error = None
ftpObj = anonftp.ftp
try:
res = ftpObj.login()
assert res.startswith('230 Anonymous access granted')
# anonymous clients should not get the welcome message
assert anonftp.motd.splitlines()[0] not in res
# Run anonymous user tests with updated data
yield init_test_data('Anon', anonftp)
except all_errors as e:
login_error = e
assert login_error is None
class TestLocalUser(UserTests):
@pytest.fixture(scope='class')
def setup(self, request):
depends(request, ["init_dflt_config"], scope="session")
local_setup = {
"onlylocal": True,
}
with ftp_user_ds_and_srvr_conn('ftplocalDS', 'FTPlocaluser', local_setup) as localftp:
login_error = None
ftpObj = localftp.ftp
try:
res = ftpObj.login(user='FTPlocaluser', passwd="secret")
assert res.startswith('230')
# local users should get the welcome message
assert localftp.motd.splitlines()[0] in res
ftpusers = ftp_get_users()
assert "FTPlocaluser" == ftpusers[0]['user']
# Run the user tests with updated data
yield init_test_data('Local', localftp)
except all_errors as e:
login_error = e
assert login_error is None
class TestFTPSUser(UserTests):
@pytest.fixture(scope='class')
def setup(self, request):
depends(request, ["init_dflt_config"], scope="session")
# We include tls_opt_no_session_reuse_required because python
# ftplib has a long running issue with support for it.
tls_setup = {
"tls": True,
"tls_opt_no_session_reuse_required": True,
"ssltls_certificate": 1
}
with ftp_user_ds_and_srvr_conn('ftpslocalDS', 'FTPSlocaluser', tls_setup, useFTPS=True) as tlsftp:
ftpsObj = tlsftp.ftp
login_error = None
try:
res = ftpsObj.login(user='FTPSlocaluser', passwd="secret")
assert res.startswith('230')
# local users should get the welcome message
assert tlsftp.motd.splitlines()[0] in res
ftpusers = ftp_get_users()
assert "FTPSlocaluser" == ftpusers[0]['user']
# Run the user tests with updated data
yield init_test_data('FTPS', tlsftp)
except all_errors as e:
login_error = e
assert login_error is None
@pytest.mark.skip(reason="Enable this when Jenkins infrastructure is better able to handle this test")
def test_085_ftp_service_starts_after_reboot():
'''
NAS-123024
There is a bug in the Debian Bookwork proftpd install package
that enables proftpd.socket which blocks proftpd.service from starting.
We fixed this by disabling proftpd.socket. There is a different fix
in a Bookworm update that involves refactoring the systemd unit files.
'''
with ftp_server(True): # start ftp and configure it to start at boot
rv = query_ftp_service()
assert rv['state'] == 'RUNNING'
assert rv['enable'] is True
reboot(truenas_server.ip)
# wait for box to reboot
max_wait = 60
ftp_state = None
for retry in range(max_wait):
try:
ftp_state = query_ftp_service()
break
except Exception:
sleep(1)
continue
# make sure ftp service started after boot
assert ftp_state, 'Failed to query ftp service state after {max_wait!r} seconds'
assert ftp_state['state'] == 'RUNNING', f'Expected ftp service to be running, found {ftp_state["state"]!r}'
def test_100_ftp_service_stop():
call('service.stop', 'ftp', {'silent': False})
rv = query_ftp_service()
assert rv['state'] == 'STOPPED'
assert rv['enable'] is False
| 53,332 | Python | .py | 1,215 | 34.760494 | 117 | 0.602045 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,355 | test_007_early_settings.py | truenas_middleware/tests/api2/test_007_early_settings.py | import stat
from middlewared.test.integration.utils import call
# this is found in middlewared.plugins.sysctl.sysctl_info
# but the client running the tests isn't guaranteed to have
# the middlewared application installed locally
DEFAULT_ARC_MAX_FILE = '/var/run/middleware/default_arc_max'
def test_sysctl_arc_max_is_set():
"""Middleware should have created this file and written a number
to it early in the boot process. That's why we check it here in
this test so early"""
assert call('filesystem.stat', DEFAULT_ARC_MAX_FILE)['size']
def test_data_dir_perms():
default_dir_mode = 0o700
default_file_mode = 0o600
data_subsystems_mode = 0o755
def check_permissions(directory):
contents = call('filesystem.listdir', directory)
for i in contents:
i_path = i['path']
i_mode = stat.S_IMODE(i['mode'])
if i['type'] == 'DIRECTORY':
assert i_mode == data_subsystems_mode, \
f'Incorrect permissions for {i_path}, should be {stat.S_IMODE(data_subsystems_mode):#o}'
check_permissions(i_path)
# Check perms of `/data`
data_dir_mode = call('filesystem.stat', '/data')['mode']
assert stat.S_IMODE(data_dir_mode) == data_subsystems_mode, \
f'Incorrect permissions for /data, should be {stat.S_IMODE(data_subsystems_mode):#o}'
# Check perms of contents `/data`
data_contents = call('filesystem.listdir', '/data')
for item in data_contents:
item_path = item['path']
if item_path == '/data/subsystems':
continue
item_mode = stat.S_IMODE(item['mode'])
desired_mode = default_dir_mode if item['type'] == 'DIRECTORY' else default_file_mode
assert item_mode == desired_mode, \
f'Incorrect permissions for {item_path}, should be {stat.S_IMODE(desired_mode):#o}'
# Check perms of `/data/subsystems`
ss_dir_mode = stat.S_IMODE(call('filesystem.stat', '/data/subsystems')['mode'])
assert ss_dir_mode == data_subsystems_mode, \
f'Incorrect permissions for /data/subsystems, should be {stat.S_IMODE(data_subsystems_mode):#o}'
# Check perms of contents of `/data/subsystems` recursively
check_permissions('/data/subsystems')
| 2,269 | Python | .py | 44 | 44.409091 | 108 | 0.66757 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,356 | test_job_lock.py | truenas_middleware/tests/api2/test_job_lock.py | import contextlib
import errno
import os
import time
import pytest
from middlewared.service_exception import CallError
from middlewared.test.integration.assets.account import unprivileged_user_client
from middlewared.test.integration.utils import call, mock, ssh
@pytest.mark.flaky(reruns=5, reruns_delay=5)
def test_jobs_execute_in_parallel():
with mock("test.test1", """
from middlewared.service import job
@job()
def mock(self, job, *args):
import time
time.sleep(5)
"""):
start = time.monotonic()
j1 = call("test.test1")
j2 = call("test.test1")
j3 = call("test.test1")
call("core.job_wait", j1, job=True)
call("core.job_wait", j2, job=True)
call("core.job_wait", j3, job=True)
assert time.monotonic() - start < 6
@pytest.mark.flaky(reruns=5, reruns_delay=5)
def test_jobs_execute_sequentially_when_there_is_a_lock():
with mock("test.test1", """
from middlewared.service import job
@job(lock="test")
def mock(self, job, *args):
import time
time.sleep(5)
"""):
start = time.monotonic()
j1 = call("test.test1")
j2 = call("test.test1")
j3 = call("test.test1")
call("core.job_wait", j1, job=True)
call("core.job_wait", j2, job=True)
call("core.job_wait", j3, job=True)
assert time.monotonic() - start >= 15
@pytest.mark.flaky(reruns=5, reruns_delay=5)
def test_lock_with_argument():
with mock("test.test1", """
from middlewared.service import job
@job(lock=lambda args: f"test.{args[0]}")
def mock(self, job, s):
import time
time.sleep(5)
"""):
start = time.monotonic()
j1 = call("test.test1", "a")
j2 = call("test.test1", "b")
j3 = call("test.test1", "a")
call("core.job_wait", j1, job=True)
call("core.job_wait", j2, job=True)
call("core.job_wait", j3, job=True)
assert 10 <= time.monotonic() - start < 15
@pytest.mark.flaky(reruns=5, reruns_delay=5)
def test_lock_queue_size():
try:
with mock("test.test1", """
from middlewared.service import job
@job(lock="test", lock_queue_size=1)
def mock(self, job, *args):
with open("/tmp/test", "a") as f:
f.write("a\\n")
import time
time.sleep(5)
"""):
j1 = call("test.test1")
j2 = call("test.test1")
j3 = call("test.test1")
j4 = call("test.test1")
call("core.job_wait", j1, job=True)
call("core.job_wait", j2, job=True)
call("core.job_wait", j3, job=True)
call("core.job_wait", j4, job=True)
assert ssh("cat /tmp/test") == "a\na\n"
assert j3 == j2
assert j4 == j2
finally:
with contextlib.suppress(FileNotFoundError):
os.unlink("/tmp/test")
def test_call_sync_a_job_with_lock():
with mock("test.test1", """
from middlewared.service import job
def mock(self):
return self.middleware.call_sync("test.test2").wait_sync()
"""):
with mock("test.test2", """
from middlewared.service import job
@job(lock="test")
def mock(self, job, *args):
return 42
"""):
assert call("test.test1") == 42
@pytest.mark.flaky(reruns=5, reruns_delay=5)
def test_lock_queue_unprivileged_user_can_access_own_jobs():
with unprivileged_user_client(allowlist=[{"method": "CALL", "resource": "test.test1"}]) as c:
with mock("test.test1", """
from middlewared.service import job
@job(lock="test", lock_queue_size=1)
def mock(self, job, *args):
import time
time.sleep(5)
"""):
j1 = c.call("test.test1")
j2 = c.call("test.test1")
j3 = c.call("test.test1")
assert j3 == j2
call("core.job_wait", j1, job=True)
call("core.job_wait", j2, job=True)
@pytest.mark.flaky(reruns=5, reruns_delay=5)
def test_lock_queue_unprivileged_user_cant_access_others_jobs():
with unprivileged_user_client(allowlist=[{"method": "CALL", "resource": "test.test1"}]) as c:
with mock("test.test1", """
from middlewared.service import job
@job(lock="test", lock_queue_size=1)
def mock(self, job, *args):
import time
time.sleep(5)
"""):
j1 = call("test.test1")
j2 = call("test.test1")
try:
with pytest.raises(CallError) as ve:
c.call("test.test1")
assert ve.value.errno == errno.EBUSY
finally:
call("core.job_wait", j1, job=True)
call("core.job_wait", j2, job=True)
| 5,058 | Python | .py | 133 | 27.924812 | 97 | 0.552242 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,357 | test_disk_zfs_guid.py | truenas_middleware/tests/api2/test_disk_zfs_guid.py | from middlewared.test.integration.utils import call
from middlewared.test.integration.utils.mock import mock
from middlewared.test.integration.utils.mock_db import mock_table_contents
from middlewared.test.integration.utils.time_utils import utc_now
DISK_TEMPLATE = {
"disk_subsystem": "scsi",
"disk_number": 2160,
"disk_serial": "",
"disk_lunid": None,
"disk_size": "17179869184",
"disk_description": "",
"disk_transfermode": "Auto",
"disk_hddstandby": "Always On",
"disk_advpowermgmt": "Disabled",
"disk_togglesmart": True,
"disk_smartoptions": "",
"disk_expiretime": None,
"disk_enclosure_slot": None,
"disk_passwd": "",
"disk_critical": None,
"disk_difference": None,
"disk_informational": None,
"disk_model": "VBOX_HARDDISK",
"disk_rotationrate": None,
"disk_type": "HDD",
"disk_kmip_uid": None,
"disk_zfs_guid": None,
"disk_bus": "ATA"
}
def test_does_not_set_zfs_guid_for_expired_disk():
with mock_table_contents(
"storage.disk",
[
{**DISK_TEMPLATE, "disk_identifier": "{serial}1", "disk_name": "sda", "disk_expiretime": utc_now()},
{**DISK_TEMPLATE, "disk_identifier": "{serial}2", "disk_name": "sda"},
],
):
with mock("pool.flatten_topology", return_value=[
{"type": "DISK", "disk": "sda", "guid": "guid1"},
]):
call("disk.sync_zfs_guid", {
"topology": "MOCK",
})
assert call(
"datastore.query", "storage.disk", [["disk_identifier", "=", "{serial}1"]], {"get": True},
)["disk_zfs_guid"] is None
assert call(
"datastore.query", "storage.disk", [["disk_identifier", "=", "{serial}2"]], {"get": True},
)["disk_zfs_guid"] == "guid1"
def test_does_not_return_expired_disks_with_same_guid():
with mock_table_contents(
"storage.disk",
[
{**DISK_TEMPLATE, "disk_identifier": "{serial}1", "disk_name": "sda", "disk_expiretime": utc_now(),
"disk_zfs_guid": "guid1"},
{**DISK_TEMPLATE, "disk_identifier": "{serial}2", "disk_name": "sda", "disk_zfs_guid": "guid1"},
]
):
assert call("disk.disk_by_zfs_guid", "guid1")["identifier"] == "{serial}2"
| 2,323 | Python | .py | 59 | 31.932203 | 112 | 0.578644 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,358 | test_420_smb.py | truenas_middleware/tests/api2/test_420_smb.py | import pytest
import sys
import os
import secrets
import string
import uuid
from time import sleep
apifolder = os.getcwd()
sys.path.append(apifolder)
from protocols import smb_connection
from utils import create_dataset
from auto_config import pool_name
from middlewared.test.integration.assets.account import user
from middlewared.test.integration.assets.smb import smb_share
from middlewared.test.integration.assets.pool import dataset as make_dataset
from middlewared.test.integration.utils import call, ssh
from middlewared.test.integration.utils.system import reset_systemd_svcs
AUDIT_WAIT = 10
SMB_NAME = "TestCifsSMB"
SHAREUSER = 'smbuser420'
PASSWD = ''.join(secrets.choice(string.ascii_letters + string.digits) for i in range(10))
@pytest.fixture(scope='module')
def smb_info():
with make_dataset('smb-cifs', data={'share_type': 'SMB'}) as ds:
with user({
'username': SHAREUSER,
'full_name': SHAREUSER,
'group_create': True,
'password': PASSWD
}, get_instance=False):
with smb_share(os.path.join('/mnt', ds), SMB_NAME, {
'purpose': 'NO_PRESET',
}) as s:
try:
call('smb.update', {
'guest': SHAREUSER
})
call('service.update', 'cifs', {'enable': True})
call('service.start', 'cifs')
yield {'dataset': ds, 'share': s}
finally:
call('smb.update', {
'guest': 'nobody'
})
call('service.stop', 'cifs')
call('service.update', 'cifs', {'enable': False})
@pytest.fixture(scope='function')
def enable_guest(smb_info):
smb_id = smb_info['share']['id']
call('sharing.smb.update', smb_id, {'guestok': True})
try:
yield
finally:
call('sharing.smb.update', smb_id, {'guestok': False})
@pytest.fixture(scope='function')
def enable_aapl():
reset_systemd_svcs('smbd')
call('smb.update', {'aapl_extensions': True})
try:
yield
finally:
call('smb.update', {'aapl_extensions': False})
@pytest.fixture(scope='function')
def enable_smb1():
reset_systemd_svcs('smbd')
call('smb.update', {'enable_smb1': True})
try:
yield
finally:
call('smb.update', {'enable_smb1': False})
@pytest.fixture(scope='function')
def enable_recycle_bin(smb_info):
smb_id = smb_info['share']['id']
call('sharing.smb.update', smb_id, {'recyclebin': True})
try:
yield
finally:
call('sharing.smb.update', smb_id, {'recyclebin': False})
@pytest.mark.parametrize('proto,runas', [
('SMB1', 'GUEST'),
('SMB2', 'GUEST'),
('SMB1', SHAREUSER),
('SMB2', SHAREUSER)
])
def test__basic_smb_ops(enable_smb1, enable_guest, proto, runas):
with smb_connection(
share=SMB_NAME,
username=runas,
password=PASSWD,
smb1=(proto == 'SMB1')
) as c:
filename1 = f'testfile1_{proto.lower()}_{runas}.txt'
filename2 = f'testfile2_{proto.lower()}_{runas}.txt'
dirname = f'testdir_{proto.lower()}_{runas}.txt'
fd = c.create_file(filename1, 'w')
c.write(fd, b'foo')
val = c.read(fd, 0, 3)
c.close(fd, True)
assert val == b'foo'
c.mkdir(dirname)
fd = c.create_file(f'{dirname}/{filename2}', 'w')
c.write(fd, b'foo2')
val = c.read(fd, 0, 4)
c.close(fd, True)
assert val == b'foo2'
c.rmdir(dirname)
# DELETE_ON_CLOSE flag was set prior to closing files
# and so root directory should be empty
assert c.ls('/') == []
def test__change_sharing_smd_home_to_true(smb_info):
reset_systemd_svcs('smbd')
smb_id = smb_info['share']['id']
share = call('sharing.smb.update', smb_id, {'home': True})
try:
share_path = call('smb.getparm', 'path', 'homes')
assert share_path == f'{share["path_local"]}/%U'
finally:
new_info = call('sharing.smb.update', smb_id, {'home': False})
share_path = call('smb.getparm', 'path', new_info['name'])
assert share_path == share['path_local']
obey_pam_restrictions = call('smb.getparm', 'obey pam restrictions', 'GLOBAL')
assert obey_pam_restrictions is False
def test__change_timemachine_to_true(enable_aapl, smb_info):
smb_id = smb_info['share']['id']
call('sharing.smb.update', smb_id, {'timemachine': True})
try:
share_info = call('sharing.smb.query', [['id', '=', smb_id]], {'get': True})
assert share_info['timemachine'] is True
enabled = call('smb.getparm', 'fruit:time machine', share_info['name'])
assert enabled == 'True'
vfs_obj = call('smb.getparm', 'vfs objects', share_info['name'])
assert 'fruit' in vfs_obj
finally:
call('sharing.smb.update', smb_id, {'timemachine': False})
def do_recycle_ops(c, has_subds=False):
# Our recycle repository should be auto-created on connect.
fd = c.create_file('testfile.txt', 'w')
c.write(fd, b'foo')
c.close(fd, True)
# Above close op also deleted the file and so
# we expect file to now exist in the user's .recycle directory
fd = c.create_file(f'.recycle/{SHAREUSER}/testfile.txt', 'r')
val = c.read(fd, 0, 3)
c.close(fd)
assert val == b'foo'
# re-open so that we can set DELETE_ON_CLOSE
# this verifies that SMB client can purge file from recycle bin
c.close(c.create_file(f'.recycle/{SHAREUSER}/testfile.txt', 'w'), True)
assert c.ls(f'.recycle/{SHAREUSER}/') == []
if not has_subds:
return
# nested datasets get their own recycle bin to preserve atomicity of
# rename op.
fd = c.create_file('subds/testfile2.txt', 'w')
c.write(fd, b'boo')
c.close(fd, True)
fd = c.create_file(f'subds/.recycle/{SHAREUSER}/testfile2.txt', 'r')
val = c.read(fd, 0, 3)
c.close(fd)
assert val == b'boo'
c.close(c.create_file(f'subds/.recycle/{SHAREUSER}/testfile2.txt', 'w'), True)
assert c.ls(f'subds/.recycle/{SHAREUSER}/') == []
def test__recyclebin_functional_test(enable_recycle_bin, smb_info):
with create_dataset(f'{smb_info["dataset"]}/subds', {'share_type': 'SMB'}):
with smb_connection(
share=SMB_NAME,
username=SHAREUSER,
password=PASSWD,
) as c:
do_recycle_ops(c, True)
@pytest.mark.parametrize('smb_config', [
{'global': {'aapl_extensions': True}, 'share': {'aapl_name_mangling': True}},
{'global': {'aapl_extensions': True}, 'share': {'aapl_name_mangling': False}},
{'global': {'aapl_extensions': False}, 'share': {}},
])
def test__recyclebin_functional_test_subdir(smb_info, smb_config):
tmp_ds = f"{pool_name}/recycle_test"
tmp_ds_path = f'/mnt/{tmp_ds}/subdir'
tmp_share_name = 'recycle_test'
reset_systemd_svcs('smbd')
call('smb.update', smb_config['global'])
# basic tests of recyclebin operations
with create_dataset(tmp_ds, {'share_type': 'SMB'}):
ssh(f'mkdir {tmp_ds_path}')
with smb_share(tmp_ds_path, tmp_share_name, {
'purpose': 'NO_PRESET',
'recyclebin': True
} | smb_config['share']):
with smb_connection(
share=tmp_share_name,
username=SHAREUSER,
password=PASSWD,
) as c:
do_recycle_ops(c)
# more abusive test where first TCON op is opening file in subdir to delete
with create_dataset(tmp_ds, {'share_type': 'SMB'}):
ops = [
f'mkdir {tmp_ds_path}',
f'mkdir {tmp_ds_path}/subdir',
f'touch {tmp_ds_path}/subdir/testfile',
f'chown {SHAREUSER} {tmp_ds_path}/subdir/testfile',
]
ssh(';'.join(ops))
with smb_share(tmp_ds_path, tmp_share_name, {
'purpose': 'NO_PRESET',
'recyclebin': True
} | smb_config['share']):
with smb_connection(
share=tmp_share_name,
username=SHAREUSER,
password=PASSWD,
) as c:
fd = c.create_file('subdir/testfile', 'w')
c.write(fd, b'boo')
c.close(fd, True)
fd = c.create_file(f'.recycle/{SHAREUSER}/subdir/testfile', 'r')
val = c.read(fd, 0, 3)
c.close(fd)
assert val == b'boo'
def test__netbios_name_change_check_sid():
""" changing netbiosname should not alter our local sid value """
orig = call('smb.config')
new_sid = call('smb.update', {'netbiosname': 'nb_new'})['cifs_SID']
try:
assert new_sid == orig['cifs_SID']
localsid = call('smb.groupmap_list')['localsid']
assert new_sid == localsid
finally:
call('smb.update', {'netbiosname': orig['netbiosname']})
AUDIT_FIELDS = [
'audit_id', 'timestamp', 'address', 'username', 'session', 'service',
'service_data', 'event', 'event_data', 'success'
]
def validate_vers(vers, expected_major, expected_minor):
assert 'major' in vers, str(vers)
assert 'minor' in vers, str(vers)
assert vers['major'] == expected_major
assert vers['minor'] == expected_minor
def validate_svc_data(msg, svc):
assert 'service_data' in msg, str(msg)
svc_data = msg['service_data']
for key in ['vers', 'service', 'session_id', 'tcon_id']:
assert key in svc_data, str(svc_data)
assert svc_data['service'] == svc
assert isinstance(svc_data['session_id'], str)
assert svc_data['session_id'].isdigit()
assert isinstance(svc_data['tcon_id'], str)
assert svc_data['tcon_id'].isdigit()
def validate_event_data(event_data, schema):
event_data_keys = set(event_data.keys())
schema_keys = set(schema['_attrs_order_'])
assert event_data_keys == schema_keys
def validate_audit_op(msg, svc):
schema = call(
'audit.json_schemas',
[['_name_', '=', f'audit_entry_smb_{msg["event"].lower()}']],
{
'select': [
['_attrs_order_', 'attrs'],
['properties.event_data', 'event_data']
],
}
)
assert schema is not [], str(msg)
schema = schema[0]
for key in schema['attrs']:
assert key in msg, str(msg)
validate_svc_data(msg, svc)
try:
aid_guid = uuid.UUID(msg['audit_id'])
except ValueError:
raise AssertionError(f'{msg["audit_id"]}: malformed UUID')
assert str(aid_guid) == msg['audit_id']
try:
sess_guid = uuid.UUID(msg['session'])
except ValueError:
raise AssertionError(f'{msg["session"]}: malformed UUID')
assert str(sess_guid) == msg['session']
validate_event_data(msg['event_data'], schema['event_data'])
def do_audit_ops(svc):
with smb_connection(
share=svc,
username=SHAREUSER,
password=PASSWD,
) as c:
fd = c.create_file('testfile.txt', 'w')
for i in range(0, 3):
c.write(fd, b'foo')
c.read(fd, 0, 3)
c.close(fd, True)
sleep(AUDIT_WAIT)
return call('auditbackend.query', 'SMB', [['event', '!=', 'AUTHENTICATION']])
def test__audit_log(request):
def get_event(event_list, ev_type):
for e in event_list:
if e['event'] == ev_type:
return e
return None
with make_dataset('smb-audit', data={'share_type': 'SMB'}) as ds:
with smb_share(os.path.join('/mnt', ds), 'SMB_AUDIT', {
'purpose': 'NO_PRESET',
'guestok': True,
'audit': {'enable': True}
}) as s:
events = do_audit_ops(s['name'])
assert len(events) > 0
for ev_type in ['CONNECT', 'DISCONNECT', 'CREATE', 'CLOSE', 'READ', 'WRITE']:
assert get_event(events, ev_type) is not None, str(events)
for event in events:
validate_audit_op(event, s['name'])
new_data = call('sharing.smb.update', s['id'], {'audit': {'ignore_list': ['builtin_users']}})
assert new_data['audit']['enable'], str(new_data['audit'])
assert new_data['audit']['ignore_list'] == ['builtin_users'], str(new_data['audit'])
# Verify that being member of group in ignore list is sufficient to avoid new messages
# By default authentication attempts are always logged
assert do_audit_ops(s['name']) == events
new_data = call('sharing.smb.update', s['id'], {'audit': {'watch_list': ['builtin_users']}})
assert new_data['audit']['enable'], str(new_data['audit'])
assert new_data['audit']['ignore_list'] == ['builtin_users'], str(new_data['audit'])
assert new_data['audit']['watch_list'] == ['builtin_users'], str(new_data['audit'])
# Verify that watch_list takes precedence
# By default authentication attempts are always logged
new_events = do_audit_ops(s['name'])
assert len(new_events) > len(events)
new_data = call('sharing.smb.update', s['id'], {'audit': {'enable': False}})
assert new_data['audit']['enable'] is False, str(new_data['audit'])
assert new_data['audit']['ignore_list'] == ['builtin_users'], str(new_data['audit'])
assert new_data['audit']['watch_list'] == ['builtin_users'], str(new_data['audit'])
# Verify that disabling audit prevents new messages from being written
assert do_audit_ops(s['name']) == new_events
@pytest.mark.parametrize('torture_test', [
'local.binding',
'local.ntlmssp',
'local.smbencrypt',
'local.messaging',
'local.irpc',
'local.strlist',
'local.file',
'local.str',
'local.time',
'local.datablob',
'local.binsearch',
'local.asn1',
'local.anonymous_shared',
'local.strv',
'local.strv_util',
'local.util',
'local.idtree',
'local.dlinklist',
'local.genrand',
'local.iconv',
'local.socket',
'local.pac',
'local.share',
'local.loadparm',
'local.charset',
'local.convert_string',
'local.string_case_handle',
'local.tevent_req',
'local.util_str_escape',
'local.talloc',
'local.replace',
'local.crypto.md4'
])
def test__local_torture(request, torture_test):
ssh(f'smbtorture //127.0.0.1 {torture_test}')
| 14,505 | Python | .py | 366 | 31.737705 | 105 | 0.590993 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,359 | test_encrypted_dataset_services_restart.py | truenas_middleware/tests/api2/test_encrypted_dataset_services_restart.py | import contextlib
import pytest
from pytest_dependency import depends
from middlewared.test.integration.utils import call
from middlewared.test.integration.assets.pool import dataset
import os
import sys
sys.path.append(os.getcwd())
PASSPHRASE = 'testing123'
@contextlib.contextmanager
def enable_auto_start(service_name):
service = call('service.query', [['service', '=', service_name]], {'get': True})
try:
yield call('service.update', service['id'], {'enable': True})
finally:
call('service.update', service['id'], {'enable': False})
@contextlib.contextmanager
def start_service(service_name):
try:
yield call('service.start', service_name)
finally:
call('service.stop', service_name)
@contextlib.contextmanager
def lock_dataset(dataset_name):
try:
yield call('pool.dataset.lock', dataset_name, {'force_umount': True}, job=True)
finally:
call(
'pool.dataset.unlock', dataset_name, {
'datasets': [{'passphrase': PASSPHRASE, 'name': dataset_name}]
},
job=True,
)
def test_service_restart_on_unlock_dataset(request):
service_name = 'smb'
registered_name = 'cifs'
with dataset('testsvcunlock', data={
'encryption': True,
'encryption_options': {
'algorithm': 'AES-256-GCM',
'pbkdf2iters': 350000,
'passphrase': PASSPHRASE,
},
'inherit_encryption': False
}) as ds:
path = f'/mnt/{ds}'
share = call(f'sharing.{service_name}.create', {'path': path, 'name': 'smb-dataset'})
assert share['locked'] is False
with start_service(registered_name) as service_started:
assert service_started is True
call('service.stop', registered_name)
assert call('service.started', registered_name) is False
with enable_auto_start(registered_name):
with lock_dataset(ds):
assert call(f'sharing.{service_name}.get_instance', share['id'])['locked'] is True
assert call('service.started', registered_name) is False
assert call(f'sharing.{service_name}.get_instance', share['id'])['locked'] is False
assert call('service.started', registered_name) is True
| 2,329 | Python | .py | 58 | 32.206897 | 102 | 0.634309 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,360 | test_reporting_netdataweb.py | truenas_middleware/tests/api2/test_reporting_netdataweb.py | import pytest
import requests
from requests.auth import HTTPBasicAuth
from middlewared.test.integration.assets.account import unprivileged_user_client
from middlewared.test.integration.utils import call, url
def test_netdata_web_login_succeed():
password = call('reporting.netdataweb_generate_password')
r = requests.get(f'{url()}/netdata/', auth=HTTPBasicAuth('root', password))
assert r.status_code == 200
def test_netdata_web_login_fail():
r = requests.get(f'{url()}/netdata/')
assert r.status_code == 401
@pytest.mark.parametrize("role,expected", [
(["FULL_ADMIN"], True),
(["READONLY_ADMIN"], True),
])
def test_netdata_web_login_unprivileged_succeed(role, expected):
with unprivileged_user_client(roles=role) as c:
me = c.call('auth.me')
password = c.call('reporting.netdataweb_generate_password')
r = requests.get(f'{url()}/netdata/', auth=HTTPBasicAuth(me['pw_name'], password))
assert (r.status_code == 200) is expected
| 1,001 | Python | .py | 22 | 41.272727 | 90 | 0.718107 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,361 | test_docker_roles.py | truenas_middleware/tests/api2/test_docker_roles.py | import pytest
from middlewared.test.integration.assets.roles import common_checks
@pytest.mark.parametrize('method, role, valid_role, valid_role_exception', (
('docker.status', 'DOCKER_READ', True, False),
('docker.status', 'DOCKER_WRITE', True, False),
('docker.status', 'CATALOG_READ', False, False),
('docker.config', 'DOCKER_READ', True, False),
('docker.config', 'DOCKER_WRITE', True, False),
('docker.config', 'CATALOG_READ', False, False),
('docker.lacks_nvidia_drivers', 'DOCKER_READ', True, False),
('docker.lacks_nvidia_drivers', 'DOCKER_WRITE', True, False),
('docker.lacks_nvidia_drivers', 'CATALOG_READ', False, False),
('docker.update', 'DOCKER_READ', False, False),
('docker.update', 'DOCKER_WRITE', True, True),
))
def test_apps_roles(unprivileged_user_fixture, method, role, valid_role, valid_role_exception):
common_checks(unprivileged_user_fixture, method, role, valid_role, valid_role_exception=valid_role_exception)
| 988 | Python | .py | 17 | 54.117647 | 113 | 0.704545 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,362 | test_pool_attach.py | truenas_middleware/tests/api2/test_pool_attach.py | from middlewared.test.integration.assets.pool import another_pool
from middlewared.test.integration.utils import call, ssh
def test_attach_raidz1_vdev():
with another_pool(topology=(6, lambda disks: {
"data": [
{
"type": "RAIDZ1",
"disks": disks[0:3]
},
{
"type": "RAIDZ1",
"disks": disks[3:6]
},
],
})) as pool:
disk = call("disk.get_unused")[0]["name"]
call("pool.attach", pool["id"], {
"target_vdev": pool["topology"]["data"][0]["guid"],
"new_disk": disk,
}, job=True)
pool = call("pool.get_instance", pool["id"])
assert pool["expand"]["state"] == "FINISHED"
| 766 | Python | .py | 22 | 24.545455 | 65 | 0.5 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,363 | test_iscsi_auth_network.py | truenas_middleware/tests/api2/test_iscsi_auth_network.py | import contextlib
import ipaddress
import socket
import pytest
from middlewared.test.integration.assets.iscsi import target_login_test
from middlewared.test.integration.assets.pool import dataset
from middlewared.test.integration.utils import call, ssh
from middlewared.test.integration.utils.client import truenas_server
@pytest.fixture(scope="module")
def my_ip4():
"""See which of my IP addresses will be used to connect."""
# Things can be complicated e.g. my NAT between the test runner
# and the target system Therefore, first try using ssh into the
# remote system and see what it thinks our IP address is.
try:
myip = ipaddress.ip_address(ssh('echo $SSH_CLIENT').split()[0])
if myip.version != 4:
raise ValueError("Not a valid IPv4 address")
return str(myip)
except Exception:
# Fall back
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(2)
result = sock.connect_ex((truenas_server.ip, 80))
assert result == 0
myip = sock.getsockname()[0]
sock.close()
# Check that we have an IPv4 address
socket.inet_pton(socket.AF_INET, myip)
return myip
@contextlib.contextmanager
def portal():
portal_config = call('iscsi.portal.create', {'listen': [{'ip': truenas_server.ip}], 'discovery_authmethod': 'NONE'})
try:
yield portal_config
finally:
call('iscsi.portal.delete', portal_config['id'])
@contextlib.contextmanager
def initiator():
initiator_config = call('iscsi.initiator.create', {})
try:
yield initiator_config
finally:
# Very likely that already cleaned up (by removing only target using it)
if call('iscsi.initiator.query', [['id', '=', initiator_config['id']]]):
call('iscsi.initiator.delete', initiator_config['id'])
@contextlib.contextmanager
def target(target_name, groups):
target_config = call('iscsi.target.create', {'name': target_name, 'groups': groups})
try:
yield target_config
finally:
call('iscsi.target.delete', target_config['id'])
@contextlib.contextmanager
def extent(extent_name, zvol_name=None):
zvol_name = zvol_name or extent_name
with dataset(zvol_name, {'type': 'VOLUME', 'volsize': 51200, 'volblocksize': '512', 'sparse': True}) as zvol:
extent_config = call('iscsi.extent.create', {'name': extent_name, 'disk': f'zvol/{zvol}'})
try:
yield extent_config
finally:
call('iscsi.extent.delete', extent_config['id'])
@contextlib.contextmanager
def target_extent(target_id, extent_id, lun_id):
target_extent_config = call(
'iscsi.targetextent.create', {'target': target_id, 'extent': extent_id, 'lunid': lun_id}
)
try:
yield target_extent_config
finally:
call('iscsi.targetextent.delete', target_extent_config['id'])
@contextlib.contextmanager
def configured_target_to_extent():
with portal() as portal_config:
with initiator() as initiator_config:
with target(
'test-target', groups=[{
'portal': portal_config['id'],
'initiator': initiator_config['id'],
'auth': None,
'authmethod': 'NONE'
}]
) as target_config:
with extent('test_extent') as extent_config:
with target_extent(target_config['id'], extent_config['id'], 1):
yield {
'extent': extent_config,
'target': target_config,
'global': call('iscsi.global.config'),
'portal': portal_config,
}
@contextlib.contextmanager
def configure_iscsi_service():
with configured_target_to_extent() as iscsi_config:
try:
call('service.start', 'iscsitarget')
assert call('service.started', 'iscsitarget') is True
yield iscsi_config
finally:
call('service.stop', 'iscsitarget')
@pytest.mark.parametrize('valid', [True, False])
def test_iscsi_auth_networks(valid):
with configure_iscsi_service() as config:
call(
'iscsi.target.update',
config['target']['id'],
{'auth_networks': [] if valid else ['8.8.8.8/32']}
)
portal_listen_details = config['portal']['listen'][0]
assert target_login_test(
f'{portal_listen_details["ip"]}:{portal_listen_details["port"]}',
f'{config["global"]["basename"]}:{config["target"]["name"]}',
) is valid
@pytest.mark.parametrize('valid', [True, False])
def test_iscsi_auth_networks_exact_ip(my_ip4, valid):
with configure_iscsi_service() as config:
call(
'iscsi.target.update',
config['target']['id'],
{'auth_networks': [f"{my_ip4}/32"] if valid else ['8.8.8.8/32']}
)
portal_listen_details = config['portal']['listen'][0]
assert target_login_test(
f'{portal_listen_details["ip"]}:{portal_listen_details["port"]}',
f'{config["global"]["basename"]}:{config["target"]["name"]}',
) is valid
@pytest.mark.parametrize('valid', [True, False])
def test_iscsi_auth_networks_netmask_24(my_ip4, valid):
# good_ip will be our IP with the last byte cleared.
good_ip = '.'.join(my_ip4.split('.')[:-1] + ['0'])
# bad_ip will be our IP with the second last byte changed and last byte cleared
n = (int(my_ip4.split('.')[2]) + 1) % 256
bad_ip = '.'.join(good_ip.split('.')[:2] + [str(n), '0'])
with configure_iscsi_service() as config:
call(
'iscsi.target.update',
config['target']['id'],
{'auth_networks': ["8.8.8.8/24", f"{good_ip}/24"] if valid else ["8.8.8.8/24", f"{bad_ip}/24"]}
)
portal_listen_details = config['portal']['listen'][0]
assert target_login_test(
f'{portal_listen_details["ip"]}:{portal_listen_details["port"]}',
f'{config["global"]["basename"]}:{config["target"]["name"]}',
) is valid
@pytest.mark.parametrize('valid', [True, False])
def test_iscsi_auth_networks_netmask_16(my_ip4, valid):
# good_ip will be our IP with the second last byte changed and last byte cleared
n = (int(my_ip4.split('.')[2]) + 1) % 256
good_ip = '.'.join(my_ip4.split('.')[:2] + [str(n), '0'])
# bad_ip will be the good_ip with the second byte changed
ip_list = good_ip.split('.')
n = (int(ip_list[1]) + 1) % 256
bad_ip = '.'.join([ip_list[0], str(n)] + ip_list[-2:])
with configure_iscsi_service() as config:
call(
'iscsi.target.update',
config['target']['id'],
{'auth_networks': ["8.8.8.8/16", f"{good_ip}/16"] if valid else ["8.8.8.8/16", f"{bad_ip}/16"]}
)
portal_listen_details = config['portal']['listen'][0]
assert target_login_test(
f'{portal_listen_details["ip"]}:{portal_listen_details["port"]}',
f'{config["global"]["basename"]}:{config["target"]["name"]}',
) is valid
| 7,218 | Python | .py | 164 | 35.439024 | 120 | 0.600313 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,364 | test_large_message.py | truenas_middleware/tests/api2/test_large_message.py | import pytest
from middlewared.service_exception import ValidationErrors
from middlewared.test.integration.utils.client import client
from truenas_api_client import ClientException
MSG_TOO_BIG_ERR = 'Max message length is 64 kB'
def test_large_message_default():
LARGE_PAYLOAD_1 = 'x' * 65537
with pytest.raises(ClientException) as ce:
with client() as c:
c.call('filesystem.mkdir', LARGE_PAYLOAD_1)
assert MSG_TOO_BIG_ERR in ce.value.error
def test_large_message_extended():
LARGE_PAYLOAD_1 = 'x' * 65537
LARGE_PAYLOAD_2 = 'x' * 2097153
# NOTE: we are intentionally passing an invalid payload here
# to avoid writing unnecessary file to VM FS. If it fails with
# ValidationErrors instead of a ClientException then we know that
# the call passed through the size check.
with pytest.raises(ValidationErrors):
with client() as c:
c.call('filesystem.file_receive', LARGE_PAYLOAD_1)
with pytest.raises(ClientException) as ce:
with client() as c:
c.call('filesystem.file_receive', LARGE_PAYLOAD_2)
assert MSG_TOO_BIG_ERR in ce.value.error
def test_large_message_unauthenticated():
LARGE_PAYLOAD = 'x' * 10000
with pytest.raises(ClientException) as ce:
with client(auth=None) as c:
c.call('filesystem.file_receive', LARGE_PAYLOAD)
assert 'Anonymous connection max message length' in ce.value.error
| 1,448 | Python | .py | 31 | 40.677419 | 70 | 0.718059 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,365 | test_core_download.py | truenas_middleware/tests/api2/test_core_download.py | import requests
from middlewared.test.integration.utils.client import truenas_server
from middlewared.test.integration.utils import call
def test_get_download_for_config_dot_save():
# set up core download
job_id, url = call('core.download', 'config.save', [], 'freenas.db')
# download from URL
rv = requests.get(f'http://{truenas_server.ip}{url}')
assert rv.status_code == 200
assert len(rv.content) > 0
| 432 | Python | .py | 10 | 39.4 | 72 | 0.727273 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,366 | test_boot_format.py | truenas_middleware/tests/api2/test_boot_format.py | from middlewared.test.integration.utils import call
def test_optimal_disk_usage():
disk = call('disk.get_unused')[0]
data_size = (
disk['size'] -
1 * 1024 * 1024 - # BIOS boot
512 * 1024 * 1024 - # EFI
73 * 512 # GPT + alignment
)
# Will raise an exception if we fail to format the disk with given harsh restrictions
call('boot.format', disk['name'], {'size': data_size})
| 429 | Python | .py | 11 | 33.090909 | 89 | 0.617788 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,367 | test_pool_dataset_details.py | truenas_middleware/tests/api2/test_pool_dataset_details.py | import pytest
from middlewared.test.integration.assets.cloud_sync import local_ftp_task
from middlewared.test.integration.assets.pool import dataset, pool
from middlewared.test.integration.utils import call, ssh
@pytest.fixture(scope="module")
def cloud_sync_fixture():
with dataset("test_pool_dataset_details") as test_ds:
with dataset("test_pool_dataset_details_other") as other_ds:
with local_ftp_task({
"path": f"/mnt/{pool}",
}) as task:
ssh(f"mkdir -p /mnt/{test_ds}/subdir")
ssh(f"mkdir -p /mnt/{other_ds}/subdir")
yield test_ds, other_ds, task
@pytest.mark.parametrize("path,count", [
# A task that backs up the parent dataset backs up the child dataset too
(lambda test_ds, other_ds: f"/mnt/{pool}", 1),
# A task that backs up the dataself itself
(lambda test_ds, other_ds: f"/mnt/{test_ds}", 1),
# A task that backs up only the part of the dataset should not count
(lambda test_ds, other_ds: f"/mnt/{test_ds}/subdir", 0),
# Unrelated datasets should not count too
(lambda test_ds, other_ds: f"/mnt/{other_ds}", 0),
(lambda test_ds, other_ds: f"/mnt/{other_ds}/subdir", 0),
])
def test_cloud_sync(cloud_sync_fixture, path, count):
test_ds, other_ds, task = cloud_sync_fixture
call("cloudsync.update", task["id"], {"path": path(test_ds, other_ds)})
result = call("pool.dataset.details")
details = [
ds
for ds in result
if ds["name"] == test_ds
][0]
assert details["cloudsync_tasks_count"] == count
| 1,596 | Python | .py | 35 | 39.171429 | 76 | 0.648875 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,368 | iscsi.py | truenas_middleware/tests/api2/assets/websocket/iscsi.py | import contextlib
from time import sleep
from middlewared.test.integration.utils import call
@contextlib.contextmanager
def initiator(comment='Default initiator', initiators=[]):
payload = {
'comment': comment,
'initiators': initiators,
}
initiator_config = call('iscsi.initiator.create', payload)
try:
yield initiator_config
finally:
call('iscsi.initiator.delete', initiator_config['id'])
@contextlib.contextmanager
def portal(listen=[{'ip': '0.0.0.0'}], comment='Default portal', discovery_authmethod='NONE'):
payload = {
'listen': listen,
'comment': comment,
'discovery_authmethod': discovery_authmethod
}
portal_config = call('iscsi.portal.create', payload)
try:
yield portal_config
finally:
call('iscsi.portal.delete', portal_config['id'])
@contextlib.contextmanager
def initiator_portal():
with initiator() as initiator_config:
with portal() as portal_config:
yield {
'initiator': initiator_config,
'portal': portal_config,
}
@contextlib.contextmanager
def alua_enabled(delay=10):
payload = {'alua': True}
call('iscsi.global.update', payload)
if delay:
sleep(delay)
call('iscsi.alua.wait_for_alua_settled', 5, 8)
try:
yield
finally:
payload = {'alua': False}
call('iscsi.global.update', payload)
if delay:
sleep(delay)
@contextlib.contextmanager
def target(target_name, groups, alias=None):
payload = {
'name': target_name,
'groups': groups,
}
if alias:
payload.update({'alias': alias})
target_config = call('iscsi.target.create', payload)
try:
yield target_config
finally:
call('iscsi.target.delete', target_config['id'], True)
@contextlib.contextmanager
def target_extent_associate(target_id, extent_id, lun_id=0):
alua_enabled = call('iscsi.global.alua_enabled')
payload = {
'target': target_id,
'lunid': lun_id,
'extent': extent_id
}
associate_config = call('iscsi.targetextent.create', payload)
if alua_enabled:
# Give a little time for the STANDBY target to surface
sleep(2)
try:
yield associate_config
finally:
call('iscsi.targetextent.delete', associate_config['id'], True)
if alua_enabled:
sleep(2)
def _extract_luns(rl):
"""
Return a list of LUNs.
:param rl: a ReportLuns instance (response)
:return result a list of int LUNIDs
Currently the results from pyscsi.ReportLuns.unmarshall_datain are (a) subject
to change & (b) somewhat lacking for our purposes. Therefore we will parse
the datain here in a manner more useful for us.
"""
result = []
# First 4 bytes are LUN LIST LENGTH
lun_list_length = int.from_bytes(rl.datain[:4], "big")
# Next 4 Bytes are RESERVED
# Remaining bytes are LUNS (8 bytes each)
luns = rl.datain[8:]
assert len(luns) >= lun_list_length
for i in range(0, lun_list_length, 8):
lun = luns[i: i + 8]
addr_method = (lun[0] >> 6) & 0x3
assert addr_method == 0, f"Unsupported Address Method: {addr_method}"
if addr_method == 0:
# peripheral device addressing method, don't care about bus.
result.append(lun[1])
return result
def verify_luns(s, expected_luns):
"""
Verify that the supplied SCSI has the expected LUNs.
:param s: a pyscsi.SCSI instance
:param expected_luns: a list of int LUNIDs
"""
s.testunitready()
# REPORT LUNS
rl = s.reportluns()
data = rl.result
assert isinstance(data, dict), data
assert 'luns' in data, data
# Check that we only have LUN 0
luns = _extract_luns(rl)
assert len(luns) == len(expected_luns), luns
assert set(luns) == set(expected_luns), luns
def read_capacity16(s):
# READ CAPACITY (16)
data = s.readcapacity16().result
return (data['returned_lba'] + 1 - data['lowest_aligned_lba']) * data['block_length']
def verify_capacity(s, expected_capacity):
"""
Verify that the supplied SCSI has the expected capacity.
:param s: a pyscsi.SCSI instance
:param expected_capacity: an int
"""
s.testunitready()
returned_size = read_capacity16(s)
assert returned_size == expected_capacity
def TUR(s):
"""
Perform a TEST UNIT READY.
:param s: a pyscsi.SCSI instance
"""
s.testunitready()
def _serial_number(s):
x = s.inquiry(evpd=1, page_code=0x80)
return x.result['unit_serial_number'].decode('utf-8')
def _device_identification(s):
result = {}
x = s.inquiry(evpd=1, page_code=0x83)
for desc in x.result['designator_descriptors']:
if desc['designator_type'] == 4:
result['relative_target_port_identifier'] = desc['designator']['relative_port']
if desc['designator_type'] == 5:
result['target_port_group'] = desc['designator']['target_portal_group']
if desc['designator_type'] == 3 and desc['designator']['naa'] == 6:
items = (desc['designator']['naa'],
desc['designator']['ieee_company_id'],
desc['designator']['vendor_specific_identifier'],
desc['designator']['vendor_specific_identifier_extension']
)
result['naa'] = "0x{:01x}{:06x}{:09x}{:016x}".format(*items)
return result
def verify_ha_device_identification(s, naa, relative_target_port_identifier, target_port_group):
x = _device_identification(s)
assert x['naa'] == naa, x
assert x['relative_target_port_identifier'] == relative_target_port_identifier, x
assert x['target_port_group'] == target_port_group, x
def verify_ha_inquiry(s, serial_number, naa, tpgs=0,
vendor='TrueNAS', product_id='iSCSI Disk'):
"""
Verify that the supplied SCSI has the expected INQUIRY response.
:param s: a pyscsi.SCSI instance
"""
TUR(s)
inq = s.inquiry().result
assert inq['t10_vendor_identification'].decode('utf-8').startswith(vendor)
assert inq['product_identification'].decode('utf-8').startswith(product_id)
if tpgs is not None:
assert inq['tpgs'] == tpgs
assert serial_number == _serial_number(s)
assert naa == _device_identification(s)['naa']
| 6,428 | Python | .py | 176 | 29.960227 | 96 | 0.642409 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,369 | service.py | truenas_middleware/tests/api2/assets/websocket/service.py | import contextlib
import os
import sys
from time import sleep
apifolder = os.getcwd()
sys.path.append(apifolder)
from middlewared.test.integration.utils import call
@contextlib.contextmanager
def ensure_service_started(service_name, delay=0):
old_value = call('service.started', service_name)
if old_value:
yield
else:
call('service.start', service_name)
if delay:
sleep(delay)
try:
yield
finally:
call('service.stop', service_name)
if delay:
sleep(delay)
@contextlib.contextmanager
def ensure_service_stopped(service_name, delay=0):
old_value = call('service.started', service_name)
if not old_value:
yield
else:
call('service.stop', service_name)
if delay:
sleep(delay)
try:
yield
finally:
call('service.start', service_name)
if delay:
sleep(delay)
@contextlib.contextmanager
def ensure_service_enabled(service_name):
"""Ensure that the specified service is enabled.
When finished restore the service config to the state
upon call."""
old_config = call('service.query', [['service', '=', service_name]])[0]
try:
if old_config['enable']:
# No change necessary
yield
else:
# Change necessary, so restore when done
call('service.update', old_config['id'], {'enable': True})
try:
yield
finally:
call('service.update', old_config['id'], {'enable': False})
finally:
# Also restore the current state (if necessary)
new_config = call('service.query', [['service', '=', service_name]])[0]
if new_config['state'] != old_config['state']:
if old_config['state'] == 'RUNNING':
call('service.start', service_name)
else:
call('service.stop', service_name)
@contextlib.contextmanager
def ensure_service_disabled(service_name):
"""Ensure that the specified service is disabled.
When finished restore the service config to the state
upon call."""
old_config = call('service.query', [['service', '=', service_name]])[0]
try:
if not old_config['enable']:
# No change necessary
yield
else:
# Change necessary, so restore when done
call('service.update', old_config['id'], {'enable': False})
try:
yield
finally:
call('service.update', old_config['id'], {'enable': True})
finally:
# Also restore the current state (if necessary)
new_config = call('service.query', [['service', '=', service_name]])[0]
if new_config['state'] != old_config['state']:
if old_config['state'] == 'RUNNING':
call('service.start', service_name)
else:
call('service.stop', service_name)
| 3,032 | Python | .py | 87 | 25.908046 | 79 | 0.582822 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,370 | server.py | truenas_middleware/tests/api2/assets/websocket/server.py | from time import sleep
from middlewared.test.integration.utils.client import client
from functions import ping_host
def reboot(ip, service_name=None):
"""Reboot the TrueNAS at the specified IP.
Return when it has rebooted."""
with client(host_ip=ip) as c:
# we call this method to "reboot" the system
# because it causes the system to go offline
# immediately (kernel panic). We don't care
# about clean shutdowns here, we're more
# interested in the box rebooting as quickly
# as possible.
c.call('failover.become_passive')
# Wait for server to reappear
ping_count, reappear_time = 1, 120
reappeared = ping_host(ip, ping_count, reappear_time)
assert reappeared, f'TrueNAS at IP: {ip!r} did not come back online after {reappear_time!r} seconds'
# TrueNAS network comes back before websocket
# server is fully operational so account for this
api_ready_time = 30
for i in range(api_ready_time):
try:
with client(host_ip=ip) as c:
if c.call('system.ready'):
break
except Exception:
pass
else:
sleep(1)
else:
assert False, f'TrueNAS at ip: {ip!r} failed to respond after {reappear_time + api_ready_time!r} seconds'
if service_name:
total_wait = 60
for i in range(total_wait):
try:
with client(host_ip=ip) as c:
rv = c.call('service.query', [['service', '=', service_name]], {'get': True})
if rv['state'] == 'RUNNING':
break
except Exception:
pass
else:
sleep(1)
else:
assert False, f'Service: {service_name!r} on IP: {ip!r} not running following reboot'
| 1,852 | Python | .py | 46 | 30.521739 | 113 | 0.595 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,371 | ms_rpc.py | truenas_middleware/tests/protocols/ms_rpc.py | import re
import subprocess
from collections import namedtuple
from functions import SRVTarget, get_host_ip
RE_SAMR_ENUMDOMAINS = re.compile(r"name:\[(?P<name>\w+)\] idx:\[(?P<idx>\w+)\]")
RE_SAMR_ENUMDOMUSER = re.compile(r"user:\[(?P<user>\w+)\] rid:\[(?P<rid>\w+)\]")
class MS_RPC():
"""
Thin wrapper around rpcclient. As needed we can use python bindings.
and use this to hold state.
"""
def __init__(self, **kwargs):
self.user = kwargs.get('username')
self.passwd = kwargs.get('password')
self.workgroup = kwargs.get('workgroup')
self.kerberos = kwargs.get('use_kerberos', False)
self.realm = kwargs.get('realm')
self.host = kwargs.get('host', get_host_ip(SRVTarget.DEFAULT))
self.smb1 = kwargs.get('smb1', False)
def connect(self):
# currently connect() and disconnect() are no-ops
# This is placeholder for future python binding usage.
return
def disconnect(self):
return
def __enter__(self):
self.connect()
return self
def __exit__(self, tp, value, traceback):
self.disconnect()
def _get_connection_subprocess_args(self):
# NOTE: on failure rpcclient will return 1 with error written to stdout
args = ['rpcclient']
if self.kerberos:
args.extend(['--use-kerberos', 'required'])
else:
args.extend(['-U', f'{self.user}%{self.passwd}'])
if self.workgroup:
args.extend(['-W', self.workgroup])
if self.realm:
args.extend(['--realm', self.realm])
if self.smb1:
args.extend(['-m', 'NT1'])
args.append(self.host)
return args
# SAMR
def _parse_samr_results(self, results, regex, to_convert):
output = []
for line in results.splitlines():
if not (m:= regex.match(line.strip())):
continue
entry = m.groupdict()
entry[to_convert] = int(entry[to_convert], 16)
output.append(entry)
return output
def domains(self):
cmd = self._get_connection_subprocess_args()
cmd.extend(['-c', 'enumdomains'])
rpc_proc = subprocess.run(cmd, capture_output=True)
if rpc_proc.returncode != 0:
raise RuntimeError(rpc_proc.stdout.decode())
return self._parse_samr_results(
rpc_proc.stdout.decode(),
RE_SAMR_ENUMDOMAINS,
'idx'
)
def users(self):
cmd = self._get_connection_subprocess_args()
cmd.extend(['-c', 'enumdomusers'])
rpc_proc = subprocess.run(cmd, capture_output=True)
if rpc_proc.returncode != 0:
raise RuntimeError(rpc_proc.stdout.decode())
return self._parse_samr_results(
rpc_proc.stdout.decode(),
RE_SAMR_ENUMDOMUSER,
'rid'
)
# SRVSVC
def shares(self):
shares = []
entry = None
cmd = self._get_connection_subprocess_args()
cmd.extend(['-c', 'netshareenumall'])
rpc_proc = subprocess.run(cmd, capture_output=True)
if rpc_proc.returncode != 0:
raise RuntimeError(rpc_proc.stdout.decode())
for idx, line in enumerate(rpc_proc.stdout.decode().splitlines()):
k, v = line.strip().split(':', 1)
# use modulo wrap-around to create new entries based on stdout
if idx % 4 == 0:
entry = {k: v.strip()}
shares.append(entry)
else:
entry.update({k: v.strip()})
return shares
| 3,631 | Python | .py | 95 | 28.957895 | 80 | 0.578468 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,372 | smb_proto.py | truenas_middleware/tests/protocols/smb_proto.py | import sys
import enum
import subprocess
from functions import SRVTarget, get_host_ip
from platform import system
# sys.real_prefix only found in old virtualenv
# if detected set local site-packages to use for samba
# In recent virtual version sys.base_prefix is to be use.
if getattr(sys, "real_prefix", None):
major_v = sys.version_info.major
minor_v = sys.version_info.minor
if system() == 'Linux':
sys.path.append(f'{sys.real_prefix}/lib/python{major_v}/dist-packages')
else:
sys.path.append(f'{sys.real_prefix}/lib/python{major_v}.{minor_v}/site-packages')
elif sys.prefix != sys.base_prefix:
major_v = sys.version_info.major
minor_v = sys.version_info.minor
if system() == 'Linux':
sys.path.append(f'{sys.base_prefix}/lib/python{major_v}/dist-packages')
else:
sys.path.append(f'{sys.base_prefix}/lib/python{major_v}.{minor_v}/site-packages')
from samba.samba3 import libsmb_samba_internal as libsmb
from samba.dcerpc import security
from samba.samba3 import param as s3param
from samba import credentials
from samba import NTSTATUSError
libsmb_has_rename = 'rename' in dir(libsmb.Conn)
class ACLControl(enum.IntFlag):
SEC_DESC_OWNER_DEFAULTED = 0x0001
SEC_DESC_GROUP_DEFAULTED = 0x0002
SEC_DESC_DACL_PRESENT = 0x0004
SEC_DESC_DACL_DEFAULTED = 0x0008
SEC_DESC_SACL_PRESENT = 0x0010
SEC_DESC_SACL_DEFAULTED = 0x0020
SEC_DESC_DACL_TRUSTED = 0x0040
SEC_DESC_SERVER_SECURITY = 0x0080
SEC_DESC_DACL_AUTO_INHERIT_REQ = 0x0100
SEC_DESC_SACL_AUTO_INHERIT_REQ = 0x0200
SEC_DESC_DACL_AUTO_INHERITED = 0x0400
SEC_DESC_SACL_AUTO_INHERITED = 0x0800
SEC_DESC_DACL_PROTECTED = 0x1000
SEC_DESC_SACL_PROTECTED = 0x2000
SEC_DESC_RM_CONTROL_VALID = 0x4000
SEC_DESC_SELF_RELATIVE = 0x8000
class SMBEncryption(enum.IntEnum):
""" Specify SMB encryption level for client. Used during negotiate """
DEFAULT = credentials.SMB_ENCRYPTION_DEFAULT
DESIRED = credentials.SMB_ENCRYPTION_DESIRED
REQUIRED = credentials.SMB_ENCRYPTION_REQUIRED
class SMB(object):
"""
Python implementation of basic SMB operations for protocol testing.
This provides sufficient functionality to connect to remote SMB share,
create and delete files, read, write, and list, make, and remove
directories.
Basic workflow can be something like this:
c = SMB.connect(<ip address>, <share>, <username>, <password>)
c.mkdir("testdir")
fh = c.create_file("testdir/testfile")
c.write(fh, b"Test base stream")
fh2 = c.create_file("testdir/testfile:stream")
c.write(fh, b"Test alternate data stream")
c.read(fh)
c.read(fh2)
c.close(fh, True)
c.ls("testdir")
c.disconnect()
"""
def __init__(self, **kwargs):
self._connection = None
self._open_files = {}
self._cred = None
self._lp = None
self._user = None
self._share = None
self._host = None
self._smb1 = False
def connect(self, **kwargs):
host = kwargs.get("host", get_host_ip(SRVTarget.DEFAULT))
share = kwargs.get("share")
encryption = SMBEncryption[kwargs.get("encryption", "DEFAULT")]
username = kwargs.get("username")
domain = kwargs.get("domain")
password = kwargs.get("password")
smb1 = kwargs.get("smb1", False)
self._lp = s3param.get_context()
self._lp.load_default()
self._cred = credentials.Credentials()
self._cred.guess(self._lp)
self._cred.set_smb_encryption(encryption)
if username is not None:
self._cred.set_username(username)
if password is not None:
self._cred.set_password(password)
if domain is not None:
self._cred.set_domain(domain)
self._host = host
self._share = share
self._smb1 = smb1
self._username = username
self._password = password
self._domain = domain
self._connection = libsmb.Conn(
host,
share,
self._lp,
self._cred,
force_smb1=smb1,
)
def get_smb_encryption(self):
return SMBEncryption(self._cred.get_smb_encryption()).name
def disconnect(self):
open_files = list(self._open_files.keys())
try:
for f in open_files:
self.close(f)
except NTSTATUSError:
pass
del(self._connection)
del(self._cred)
del(self._lp)
def show_connection(self):
return {
"connected": self._connection.chkpath(''),
"host": self._host,
"share": self._share,
"smb1": self._smb1,
"username": self._user,
"open_files": self._open_files,
}
def mkdir(self, path):
return self._connection.mkdir(path)
def rmdir(self, path):
return self._connection.rmdir(path)
def ls(self, path):
return self._connection.list(path)
def create_file(self, file, mode, attributes=None, do_create=False):
dosmode = 0
f = None
for char in str(attributes):
if char == "h":
dosmode += libsmb.FILE_ATTRIBUTE_HIDDEN
elif char == "r":
dosmode += libsmb.FILE_ATTRIBUTE_READONLY
elif char == "s":
dosmode += libsmb.FILE_ATTRIBUTE_SYSTEM
elif char == "a":
dosmode += libsmb.FILE_ATTRIBUTE_ARCHIVE
if mode == "r":
f = self._connection.create(
file,
CreateDisposition=1 if not do_create else 3,
DesiredAccess=security.SEC_GENERIC_READ,
FileAttributes=dosmode,
)
elif mode == "w":
f = self._connection.create(
file,
CreateDisposition=3,
DesiredAccess=security.SEC_GENERIC_ALL,
FileAttributes=dosmode,
)
self._open_files[f] = {
"filename": file,
"fh": f,
"mode": mode,
"attributes": dosmode
}
return f
def close(self, idx, delete=False):
if delete:
self._connection.delete_on_close(
self._open_files[idx]["fh"],
True
)
self._connection.close(self._open_files[idx]["fh"])
self._open_files.pop(idx)
return self._open_files
def read(self, idx=0, offset=0, cnt=1024):
return self._connection.read(
self._open_files[idx]["fh"], offset, cnt
)
def write(self, idx=0, data=None, offset=0):
return self._connection.write(
self._open_files[idx]["fh"], data, offset
)
def rename(self, src, dst):
if libsmb_has_rename:
return self._connection.rename(src, dst)
cmd = [
"smbclient", f"//{self._host}/{self._share}",
"-U", f"{self._username}%{self._password}",
]
if self._smb1:
cmd.extend(["-m", "NT1"])
cmd.extend(["-c", f'rename {src} {dst}'])
cl = subprocess.run(cmd, capture_output=True)
if cl.returncode != 0:
raise RuntimeError(cl.stdout.decode())
def _parse_quota(self, quotaout):
ret = []
for entry in quotaout:
e = entry.split(":")
if len(e) != 2:
continue
user = e[0].strip()
used, soft, hard = e[1].split("/")
ret.append({
"user": user,
"used": int(used.strip()),
"soft_limit": int(soft.strip()) if soft.strip() != "NO LIMIT" else None,
"hard_limit": int(hard.strip()) if hard.strip() != "NO LIMIT" else None,
})
return ret
def get_shadow_copies(self, **kwargs):
snaps = []
host = kwargs.get("host", get_host_ip(SRVTarget.DEFAULT))
share = kwargs.get("share")
path = kwargs.get("path", "/")
username = kwargs.get("username")
password = kwargs.get("password")
smb1 = kwargs.get("smb1", False)
cmd = [
"smbclient", f"//{host}/{share}",
"-U", f"{username}%{password}",
]
if smb1:
cmd.extend(["-m", "NT1"])
cmd.extend(["-c", f'allinfo {path}'])
cl = subprocess.run(cmd, capture_output=True)
if cl.returncode != 0:
raise RuntimeError(cl.stderr.decode())
client_out = cl.stdout.decode().splitlines()
for i in client_out:
if i.startswith("@GMT"):
snaps.append(i)
return snaps
def get_quota(self, **kwargs):
host = kwargs.get("host", get_host_ip(SRVTarget.DEFAULT))
share = kwargs.get("share")
username = kwargs.get("username")
password = kwargs.get("password")
do_list = kwargs.get("list")
smb1 = kwargs.get("smb1", False)
cmd = [
"smbcquotas", f"//{host}/{share}",
"-U", f"{username}%{password}",
]
if do_list:
cmd.append("-L")
if smb1:
cmd.extend(["-m", "NT1"])
smbcquotas = subprocess.run(cmd, capture_output=True)
quotaout = smbcquotas.stdout.decode().splitlines()
return self._parse_quota(quotaout)
def set_quota(self, **kwargs):
host = kwargs.get("host", get_host_ip(SRVTarget.DEFAULT))
share = kwargs.get("share")
username = kwargs.get("username")
password = kwargs.get("password")
target = kwargs.get("target")
hard_limit = kwargs.get("hardlimit", 0)
soft_limit = kwargs.get("softlimit", 0)
smb1 = kwargs.get("smb1", False)
cmd = [
"smbcquotas", f"//{host}/{share}",
"-S", f"UQLIM:{target}:{soft_limit}/{hard_limit}",
"-U", f"{username}%{password}",
]
if smb1:
cmd.extend(["-m", "NT1"])
smbcquotas = subprocess.run(cmd, capture_output=True)
quotaout = smbcquotas.stdout.decode().splitlines()
return self._parse_quota(quotaout)
def set_sd(self, idx, secdesc, security_info):
self._connection.set_sd(self._open_files[idx]["fh"], secdesc, security_info)
def get_sd(self, idx, security_info):
return self._connection.get_sd(self._open_files[idx]["fh"], security_info)
def inherit_acl(self, path, action):
cmd = [
"smbcacls", f"//{self._host}/{self._share}",
"-U", f"{self._username}%{self._password}"
]
if action in ["ALLOW", "REMOVE", "COPY"]:
cmd.extend(["-I", action.lower()])
elif action == "PROPAGATE":
cmd.append('--propagate-iheritance')
else:
raise ValueError(f"{action}: invalid action")
if self._smb1:
cmd.extend(["-m", "NT1"])
cmd.append(path)
cl = subprocess.run(cmd, capture_output=True)
if cl.returncode != 0:
raise RuntimeError(cl.stdout.decode() or cl.stderr.decode())
| 11,277 | Python | .py | 296 | 28.885135 | 89 | 0.573155 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,373 | ftp_proto.py | truenas_middleware/tests/protocols/ftp_proto.py | import contextlib
import ssl
from ftplib import FTP, FTP_TLS
# See docs at:
# https://docs.python.org/3/library/ftplib.html
def ftp_connect(host, port=0):
"""
Connect to the specified host, returning an FTP object from ftplib.
"""
ftp = FTP(host, port)
return ftp
def ftps_connect(host, ctx=None):
"""
Connect to the specified host, returning an FTP_TLS object from ftplib.
Use a simple TLS setup.
"""
if ctx is None:
ctx = ssl._create_unverified_context()
ftps = FTP_TLS(host, context=ctx)
ftps.auth()
ftps.prot_p()
return ftps
@contextlib.contextmanager
def ftp_connection(host, port=0):
"""
Factory function to connect to the specified host
RETURN: FTP object from ftplib.
EXAMPLE USAGE:
with ftp_connection(<hostname | ip address>) as ftp:
ftp.login()
print(ftp.mlsd())
"""
ftp = ftp_connect(host, port=0)
try:
yield ftp
finally:
ftp.close()
@contextlib.contextmanager
def ftps_connection(host, ctx=None):
"""
Factory function to connect to the specified host
The TLS connection does not allow port selection
RETURN: FTP_TLS object from ftplib.
EXAMPLE USAGE:
with ftps_connection(<hostname | ip address>) as ftps:
ftp.login()
print(ftps.mlsd())
"""
ftps = ftps_connect(host, ctx)
try:
yield ftps
finally:
ftps.close()
| 1,438 | Python | .py | 53 | 22.075472 | 75 | 0.661572 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,374 | __init__.py | truenas_middleware/tests/protocols/__init__.py | import contextlib
from functions import DELETE, POST
from .ftp_proto import ftp_connect, ftps_connect, ftp_connection, ftps_connection # noqa
from .iscsi_proto import initiator_name_supported, iscsi_scsi_connect, iscsi_scsi_connection # noqa
from .iSNSP.client import iSNSPClient
from .ms_rpc import MS_RPC # noqa
from .nfs_proto import SSH_NFS # noqa
from .smb_proto import SMB
@contextlib.contextmanager
def smb_connection(**kwargs):
c = SMB()
c.connect(**kwargs)
try:
yield c
finally:
c.disconnect()
@contextlib.contextmanager
def smb_share(path, options=None):
results = POST("/sharing/smb/", {
"path": path,
**(options or {}),
})
assert results.status_code == 200, results.text
id = results.json()["id"]
try:
yield id
finally:
result = DELETE(f"/sharing/smb/id/{id}/")
assert result.status_code == 200, result.text
@contextlib.contextmanager
def nfs_share(path, options=None):
results = POST("/sharing/nfs/", {
"path": path,
**(options or {}),
})
assert results.status_code == 200, results.text
id = results.json()["id"]
try:
yield id
finally:
result = DELETE(f"/sharing/nfs/id/{id}/")
assert result.status_code == 200, result.text
@contextlib.contextmanager
def isns_connection(host, initiator_iqn, **kwargs):
c = iSNSPClient(host, initiator_iqn, **kwargs)
try:
c.connect()
c.register_initiator()
yield c
finally:
c.deregister_initiator()
c.close()
| 1,584 | Python | .py | 52 | 25.134615 | 100 | 0.655036 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,375 | iscsi_proto.py | truenas_middleware/tests/protocols/iscsi_proto.py | import contextlib
import inspect
from pyscsi.pyscsi.scsi import SCSI
from pyscsi.utils import init_device
def initiator_name_supported():
"""
Returns whether a non-None initiator name may be supplied.
This can have an impact on what kinds of tests can be run.
"""
return 'initiator_name' in inspect.signature(init_device).parameters
def iscsi_scsi_connect(host, iqn, lun=0, user=None, secret=None, target_user=None, target_secret=None, initiator_name=None):
"""
Connect to the specified target, returning a SCSI object from python-scsi.
See docs at:
https://github.com/python-scsi/python-scsi/blob/master/pyscsi/pyscsi/scsi.py
Basic workflow can be something like this:
s = iscsi_scsi_connect(<ip address>, <iqn> , <lun>)
s.testunitready()
pprint.pprint(s.inquiry().result)
s.device.close()
"""
hil = f"{host}/{iqn}/{lun}"
if user is None and secret is None:
device_str = f"iscsi://{hil}"
elif user and secret:
if target_user is None and target_secret is None:
# CHAP
device_str = f"iscsi://{user}%{secret}@{hil}"
elif target_user and target_secret:
# Mutual CHAP
device_str = f"iscsi://{user}%{secret}@{hil}?target_user={target_user}&target_password={target_secret}"
else:
raise ValueError("If either of target_user and target_secret is set, then both should be set.")
else:
raise ValueError("If either of user and secret is set, then both should be set.")
if initiator_name:
if not initiator_name_supported():
raise ValueError("Initiator name supplied, but not supported.")
device = init_device(device_str, initiator_name=initiator_name)
else:
device = init_device(device_str)
s = SCSI(device)
s.blocksize = 512
return s
@contextlib.contextmanager
def iscsi_scsi_connection(host, iqn, lun=0, user=None, secret=None, target_user=None, target_secret=None, initiator_name=None):
"""
Factory function to connect to the specified target, returning a SCSI
object from python-scsi.
See docs at:
https://github.com/python-scsi/python-scsi/blob/master/pyscsi/pyscsi/scsi.py
Basic workflow can be something like this:
with iscsi_scsi_connection(<ip address>, <iqn> , <lun>) as s:
s.testunitready()
inqdata = s.inquiry().result
"""
s = iscsi_scsi_connect(host, iqn, lun, user, secret, target_user, target_secret, initiator_name)
try:
yield s
finally:
s.device.close()
| 2,583 | Python | .py | 61 | 36.032787 | 127 | 0.678771 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,376 | nfs_proto.py | truenas_middleware/tests/protocols/nfs_proto.py | import sys
from functions import SSH_TEST, SRVTarget, get_host_ip
from platform import system
# sys.real_prefix only found in old virtualenv
# if detected set local site-packages to use for samba
# In recent virtual version sys.base_prefix is to be use.
if getattr(sys, "real_prefix", None):
major_v = sys.version_info.major
minor_v = sys.version_info.minor
if system() == 'Linux':
sys.path.append(f'{sys.real_prefix}/lib/python{major_v}/dist-packages')
else:
sys.path.append(f'{sys.real_prefix}/lib/python{major_v}.{minor_v}/site-packages')
elif sys.prefix != sys.base_prefix:
major_v = sys.version_info.major
minor_v = sys.version_info.minor
if system() == 'Linux':
sys.path.append(f'{sys.base_prefix}/lib/python{major_v}/dist-packages')
else:
sys.path.append(f'{sys.base_prefix}/lib/python{major_v}.{minor_v}/site-packages')
class NFS(object):
perms = [
"READ_DATA",
"WRITE_DATA",
"EXECUTE",
"APPEND_DATA",
"DELETE_CHILD",
"DELETE",
"READ_ATTRIBUTES",
"WRITE_ATTRIBUTES",
"READ_NAMED_ATTRS",
"WRITE_NAMED_ATTRS",
"READ_ACL",
"WRITE_ACL",
"WRITE_OWNER",
"SYNCHRONIZE",
]
flags = [
"FILE_INHERIT",
"DIRECTORY_INHERIT",
"INHERIT_ONLY",
"NO_PROPAGATE_INHERIT",
"INHERITED"
]
def __init__(self, hostname, path, **kwargs):
self._path = path
self._hostname = hostname or get_host_ip(SRVTarget.DEFAULT)
self._version = kwargs.get('vers', 3)
self._localpath = kwargs.get('localpath', '/mnt/testnfs')
self._mounted = False
self._user = kwargs.get('user')
self._password = kwargs.get('password')
self._use_kerberos = kwargs.get('kerberos', False)
self._ip = kwargs.get('ip')
self._client_platform = kwargs.get('platform')
self._options = kwargs.get('options')
def mount(self):
raise NotImplementedError
def umount(self):
raise NotImplementedError
def __enter__(self):
self.mount()
return self
def __exit__(self, typ, value, traceback):
self.umount()
class SSH_NFS(NFS):
def __init__(self, hostname, path, **kwargs):
super().__init__(hostname, path, **kwargs)
self._mount_user = kwargs.get('mount_user', self._user)
self._mount_password = kwargs.get('mount_password', self._password)
def acl_from_text(self, text):
out = []
for e in text.splitlines():
if not e or e.startswith('#'):
continue
entry = {
"tag": None,
"id": -1,
"perms": {x: False for x in self.perms},
"flags": {x: False for x in self.flags},
"type": None
}
tp, flags, principal, perms = e.split(":")
entry["type"] = "ALLOW" if tp == "A" else "DENY"
if principal in ["OWNER@", "GROUP@", "EVERYONE@"]:
entry["tag"] = principal.lower()
else:
entry["tag"] = "GROUP" if "g" in flags else "USER"
if principal.isdigit():
entry["id"] = int(principal)
else:
entry["id"] = None
entry['who'] = principal
for c in flags:
if c == 'f':
entry['flags']['FILE_INHERIT'] = True
elif c == 'd':
entry['flags']['DIRECTORY_INHERIT'] = True
elif c == 'i':
entry['flags']['INHERIT_ONLY'] = True
elif c == 'n':
entry['flags']['NO_PROPAGATE_INHERIT'] = True
for c in perms:
if c == 'r':
entry['perms']['READ_DATA'] = True
elif c == 'w':
entry['perms']['WRITE_DATA'] = True
elif c == 'a':
entry['perms']['APPEND_DATA'] = True
elif c == 'D':
entry['perms']['DELETE_CHILD'] = True
elif c == 'd':
entry['perms']['DELETE'] = True
elif c == 'x':
entry['perms']['EXECUTE'] = True
elif c == 't':
entry['perms']['READ_ATTRIBUTES'] = True
elif c == 'T':
entry['perms']['WRITE_ATTRIBUTES'] = True
elif c == 'n':
entry['perms']['READ_NAMED_ATTRS'] = True
elif c == 'N':
entry['perms']['WRITE_NAMED_ATTRS'] = True
elif c == 'c':
entry['perms']['READ_ACL'] = True
elif c == 'C':
entry['perms']['WRITE_ACL'] = True
elif c == 'o':
entry['perms']['WRITE_OWNER'] = True
elif c == 'y':
entry['perms']['SYNCHRONIZE'] = True
out.append(entry)
return out
def _ace_to_text(self, ace):
out = "A:" if ace['type'] == 'ALLOW' else "D:"
for k, v in ace['flags'].items():
if not v:
continue
if k == 'FILE_INHERIT':
out += "f"
elif k == 'DIRECTORY_INHERIT':
out += "d"
elif k == 'INHERIT_ONLY':
out += "i"
elif k == 'NO_PROPAGATE_INHERIT':
out += "n"
if ace["tag"] in ["group@", "GROUP"]:
out += "g"
out += ":"
if ace["tag"] in ("everyone@", "group@", "owner@"):
out += ace["tag"].upper()
else:
out += str(ace["id"])
out += ":"
for k, v in ace['perms'].items():
if not v:
continue
if k == 'READ_DATA':
out += "r"
elif k == 'WRITE_DATA':
out += "w"
elif k == 'APPEND_DATA':
out += "a"
elif k == 'DELETE_CHILD':
out += "D"
elif k == 'DELETE':
out += "d"
elif k == 'EXECUTE':
out += "x"
elif k == 'READ_ATTRIBUTES':
out += "t"
elif k == 'WRITE_ATTRIBUTES':
out += "T"
elif k == 'READ_NAMED_ATTRS':
out += "n"
elif k == 'WRITE_NAMED_ATTRS':
out += "N"
elif k == 'READ_ACL':
out += "c"
elif k == 'WRITE_ACL':
out += "C"
elif k == 'WRITE_OWNER':
out += "o"
elif k == 'SYNCHRONIZE':
out += "y"
return out
def acl_to_text(self, acl):
out = []
for ace in acl:
out.append(self._ace_to_text(ace))
return ','.join(out)
def validate(self, path):
if not self._mounted:
raise RuntimeError("Export is not mounted")
if path.startswith("/"):
raise ValueError(f"{path}: absolute paths are not supported")
return
def mkdir(self, path):
mkdir = SSH_TEST(
f"mkdir -p {self._localpath}/{path}",
self._user, self._password, self._ip
)
if mkdir['result'] is False:
raise RuntimeError(mkdir['stderr'])
def rmdir(self, path):
rmdir = SSH_TEST(
f"rmdir {self._localpath}/{path}",
self._user, self._password, self._ip
)
if rmdir['result'] is False:
raise RuntimeError(rmdir['stderr'])
def ls(self, path):
ls = SSH_TEST(
f"ls {self._localpath}/{path}",
self._user, self._password, self._ip
)
if ls['result'] is False:
raise RuntimeError(ls['stderr'])
return ls['stdout']
def rename(self, src, dst):
mv = SSH_TEST(
f"mv {self._localpath}/{src} {self._localpath}/{dst}",
self._user, self._password, self._ip
)
if mv['result'] is False:
raise RuntimeError(mv['stderr'])
def unlink(self, path):
rm = SSH_TEST(
f"rm {self._localpath}/{path}",
self._user, self._password, self._ip
)
if rm['result'] is False:
raise RuntimeError(rm['stderr'])
def getacl(self, path):
self.validate(path)
getfacl = SSH_TEST(
f"nfs4_getfacl {self._localpath}/{path}",
self._user, self._password, self._ip
)
if getfacl['result'] is False:
raise RuntimeError(getfacl['stderr'])
return self.acl_from_text(getfacl['stdout'])
def setacl(self, path, acl):
self.validate(path)
acl_spec = self.acl_to_text(acl)
setfacl = SSH_TEST(
f"nfs4_setfacl {self._localpath}/{path} -s {acl_spec}",
self._user, self._password, self._ip
)
if setfacl['result'] is False:
raise RuntimeError(setfacl['stderr'])
def getaclflag(self, path):
self.validate(path)
# nfs4_getfacl has no knowledge of acl_flags, use nfs4xfr_getfacl instead
getfacl = SSH_TEST(
f"nfs4xdr_getfacl {self._localpath}/{path}",
self._user, self._password, self._ip
)
if getfacl['result'] is False:
raise RuntimeError(getfacl['stderr'])
for line in getfacl['stdout'].split('\n'):
if line.startswith('# ACL flags:'):
return line.split(':')[1].strip()
raise RuntimeError('Could not find acl_flag')
def setaclflag(self, path, value):
self.validate(path)
# nfs4_setfacl has no knowledge of acl_flags, use nfs4xfr_setfacl instead
getfacl = SSH_TEST(
f"nfs4xdr_setfacl -p {value} {self._localpath}/{path}",
self._user, self._password, self._ip
)
if getfacl['result'] is False:
raise RuntimeError(getfacl['stderr'])
def getxattr(self, path, xattr_name):
self.validate(path)
cmd = ['getfattr', '--only-values', '-m', xattr_name, f'{self._localpath}/{path}']
getxattr = SSH_TEST(' '.join(cmd), self._user, self._password, self._ip)
if getxattr['result'] is False:
raise RuntimeError(getxattr['stderr'])
return getxattr['stdout']
def setxattr(self, path, xattr_name, value):
self.validate(path)
cmd = ['setfattr', '-n', xattr_name, '-v', value, f'{self._localpath}/{path}']
setxattr = SSH_TEST(' '.join(cmd), self._user, self._password, self._ip)
if setxattr['result'] is False:
raise RuntimeError(setxattr['stderr'])
def create(self, path, is_dir=False):
self.validate(path)
create = SSH_TEST(
f'{"mkdir" if is_dir else "touch"} {self._localpath}/{path}',
self._user, self._password, self._ip
)
if create['result'] is False:
raise RuntimeError(create['stderr'])
def server_side_copy(self, path1, path2):
"""
Currently this is a hack and so writes a default payload to fd1 and then
does copy_file_range() to duplicate to fd2
"""
self.validate(path1)
self.validate(path2)
python_script = [
"import os",
f"file1 = open('{self._localpath}/{path1}', 'w')",
"file1.write('canary')",
"file1.flush()",
"os.fsync(file1.fileno())",
f"srcfd = os.open('{self._localpath}/{path1}', os.O_CREAT | os.O_RDWR)",
f"dstfd = os.open('{self._localpath}/{path2}', os.O_CREAT | os.O_RDWR)",
"written = os.copy_file_range(srcfd, dstfd, len('canary'))",
"assert written == len('canary')"
]
cmd = ['python3', '-c']
cmd.append(f'"{";".join(python_script)}"')
rv = SSH_TEST(' '.join(cmd), self._user, self._password, self._ip)
if rv['result'] is False:
raise RuntimeError(rv['stderr'])
def mount(self):
mkdir = SSH_TEST(f"mkdir -p {self._localpath}", self._mount_user, self._mount_password, self._ip)
if mkdir['result'] is False:
raise RuntimeError(mkdir['stderr'])
mnt_opts = f'vers={self._version}'
if self._use_kerberos:
mnt_opts += ',sec=krb5'
if self._options:
mnt_opts += ',' + ','.join(self._options)
cmd = ['mount.nfs', '-o', mnt_opts, f'{self._hostname}:{self._path}', self._localpath]
do_mount = SSH_TEST(" ".join(cmd), self._mount_user, self._mount_password, self._ip)
if do_mount['result'] is False:
raise RuntimeError(do_mount['stderr'])
self._mounted = True
def umount(self):
if not self._mounted:
return
do_umount = SSH_TEST(f"umount -f {self._localpath}", self._mount_user, self._mount_password, self._ip)
if do_umount['result'] is False:
raise RuntimeError(do_umount['stderr'])
# Remove the mount dir
rmdir = SSH_TEST(f"rm -rf {self._localpath}", self._mount_user, self._mount_password, self._ip)
if rmdir['result'] is False:
raise RuntimeError(rmdir['stderr'])
self._mounted = False
| 13,408 | Python | .py | 342 | 27.809942 | 110 | 0.506343 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,377 | client.py | truenas_middleware/tests/protocols/iSNSP/client.py | import socket
from .exceptions import *
from .packet import *
class iSNSPClient(object):
def __init__(self, host, initiator_iqn, port=3205):
self.host = host
if initiator_iqn:
self.source = iSNSPAttribute.iSCSIName(initiator_iqn)
else:
self.source = None
self.port = port
self.txnid = 1
self.sock = None
def connect(self, timeout=10):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((self.host, self.port))
if timeout:
self.sock.settimeout(timeout)
def close(self):
if self.sock:
self.sock.close()
def register_initiator(self, iqn=None):
if not self.source:
self.source = iSNSPAttribute.iSCSIName(iqn)
eid = iSNSPAttribute.EntityIdentifier('')
delimiter = iSNSPAttribute.Delimiter()
iscsi_name = iSNSPAttribute.iSCSIName(iqn) if iqn else self.source
node_type = iSNSPAttribute.iSCSINodeType(2)
flags = iSNSPFlags(client=True, first=True, last=True)
pkt = iSNSPPacket.DevAttrReg(flags, self.txnid, 0,
[self.source, eid, delimiter, iscsi_name,
node_type])
rpkt = self.send_packet(pkt)
if rpkt.function != 'DevAttrRegRsp':
raise iSNSPException('Invalid response type', response)
def list_targets(self, verbose=False):
result = []
next_iscsi_name = iSNSPAttribute.iSCSIName('')
delimiter = iSNSPAttribute.Delimiter()
target_node_type = iSNSPAttribute.iSCSINodeType(1)
flags = iSNSPFlags(client=True, first=True, last=True)
while True:
pkt = iSNSPPacket.DevGetNext(flags, self.txnid, 0,
[self.source,
next_iscsi_name,
delimiter,
target_node_type])
try:
rpkt = self.send_packet(pkt)
if verbose:
for p in rpkt.payload:
print(p)
if rpkt.payload[1].tag == 'iSCSI Name':
next_iscsi_name = rpkt.payload[1]
result.append(next_iscsi_name.val)
else:
raise iSNSPException('Invalid response attribute', rpkt)
except StopIteration:
break
return result
def fetch_eids(self, verbose=False):
result = []
eid = iSNSPAttribute.EntityIdentifier(bytes())
delimiter = iSNSPAttribute.Delimiter()
flags = iSNSPFlags(client=True, first=True, last=True)
while True:
pkt = iSNSPPacket.DevGetNext(flags, self.txnid, 0,
[self.source, eid, delimiter])
try:
rpkt = self.send_packet(pkt)
if verbose:
for p in rpkt.payload:
print(p)
if rpkt.payload[1].tag == 'Entity Identifier':
eid = rpkt.payload[1]
result.append(eid)
else:
raise iSNSPException('Invalid response attribute', rpkt)
except StopIteration:
break
return result
def deregister_initiator(self, iqn=None):
delimiter = iSNSPAttribute.Delimiter()
flags = iSNSPFlags(client=True, first=True, last=True)
iscsi_name = iSNSPAttribute.iSCSIName(iqn) if iqn else self.source
pkt = iSNSPPacket.DevDereg(flags, self.txnid, 0,
[self.source, delimiter, iscsi_name])
rpkt = self.send_packet(pkt)
if rpkt.function != 'DevDeregRsp':
raise iSNSPException('Invalid response type', response)
def send(self, msg, msglen):
totalsent = 0
while totalsent < msglen:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
def recv_packet(self):
length_calculated = False
chunks = []
bytes_required = iSNSPPacket.HEADER_LENGTH
bytes_received = 0
while bytes_received < bytes_required:
chunk = self.sock.recv(min(bytes_required - bytes_received, 4096))
if chunk == b'':
raise RuntimeError("socket connection broken")
chunks.append(chunk)
bytes_received = bytes_received + len(chunk)
if not length_calculated and bytes_received >= iSNSPPacket.HEADER_LENGTH:
pdu_len = iSNSPPacket.pdu_length(b''.join(chunks))
length_calculated = True
bytes_required = iSNSPPacket.HEADER_LENGTH + pdu_len
return b''.join(chunks)
def send_packet(self, pkt):
msg = pkt.asbytes
self.send(msg, len(msg))
data = self.recv_packet()
_txnid = self.txnid
self.txnid += 1
response = iSNSPPacket.from_bytes(data)
status = response.payload[0]
if status == ResponseStatus.NO_SUCH_ENTRY:
raise StopIteration
if status != ResponseStatus.SUCCESSFUL:
raise iSNSPException('Invalid response', status)
if response.txnid != _txnid:
raise iSNSPException('Invalid response txnid', response)
return response
| 5,535 | Python | .py | 128 | 30.03125 | 85 | 0.563404 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,378 | packet.py | truenas_middleware/tests/protocols/iSNSP/packet.py | import struct
from dataclasses import dataclass
from enum import Enum
from typing import ClassVar, Dict, List, Optional
from .exceptions import MalformedPacketError
class ResponseStatus(Enum):
SUCCESSFUL = 0
UNKNOWN_ERROR = 1
MESSAGE_FORMAT_ERROR = 2
INVALID_REGISTRATION = 3
RESERVED = 4
INVALID_QUERY = 5
SOURCE_UNKNOWN = 6
SOURCE_ABSENT = 7
SOURCE_UNAUTHORIZED = 8
NO_SUCH_ENTRY = 9
VERSION_NOT_SUPPORTED = 10
INTERNAL_ERROR = 11
BUSY = 12
OPTION_NOT_UNDERSTOOD = 13
INVALID_UPDATE = 14
MESSAGE_NOT_SUPPORTED = 15
SCN_EVENT_REJECTED = 16
SCN_REGISTRATION_REJECTED = 17
ATTRIBUTE_NOT_IMPLEMENTED = 18
FC_DOMAIN_ID_NOT_AVAILABLE = 19
FC_DOMAIN_ID_NOT_ALLOCATED = 20
ESI_NOT_AVAILABLE = 21
INVALID_DEREGISTRATION = 22
REGISTRATION_FEATURE_NOT_SUPPORTED = 23
@dataclass
class iSNSPFlags(object):
client: bool = False
server: bool = False
auth: bool = False
replace: bool = False
last: bool = False
first: bool = False
@property
def int(self):
val = 0
val |= 0x8000 if self.client else 0
val |= 0x4000 if self.server else 0
val |= 0x2000 if self.auth else 0
val |= 0x1000 if self.replace else 0
val |= 0x0800 if self.last else 0
val |= 0x0400 if self.first else 0
return val
@property
def asbytes(self):
return self.int.to_bytes(2, byteorder='big')
@classmethod
def from_val(cls, val: int):
client = (val & 0x8000) == 0x8000
server = (val & 0x4000) == 0x4000
auth = (val & 0x2000) == 0x2000
replace = (val & 0x1000) == 0x1000
last = (val & 0x0800) == 0x0800
first = (val & 0x0400) == 0x0400
return cls(client, server, auth, replace, last, first)
@dataclass
class iSNSPAttribute(object):
"""
This class models a iSNSP attribute which is contained in a iSNSP packet's
payload. From RFC 4171:
Byte MSb LSb
Offset 0 31
+--------------------------------------------+
0 | Attribute Tag | 4 Bytes
+--------------------------------------------+
4 | Attribute Length (N) | 4 Bytes
+--------------------------------------------+
8 | |
| Attribute Value | N Bytes
| |
+--------------------------------------------+
Total Length = 8 + N
"""
tag: str # 4 octets
length: int # 4 octets
val: bytes
tag_map: ClassVar[Dict[int, str]] = {
0: 'Delimiter',
1: 'Entity Identifier',
2: 'Entity Protocol',
3: 'Management IP Address',
4: 'Timestamp',
5: 'Protocol Version Range',
6: 'Registration Period',
7: 'Entity Index',
8: 'Entity Next Index',
11: 'Entity ISAKMP Phase-1',
12: 'Entity Certificate',
16: 'Portal IP Address',
17: 'Portal TCP/UDP Port',
18: 'Portal Symbolic Name',
19: 'ESI Interval',
20: 'ESI Port',
22: 'Portal Index',
23: 'SCN Port',
24: 'Portal Next Index',
27: 'Portal Security Bitmap',
28: 'Portal ISAKMP Phase-1',
29: 'Portal ISAKMP Phase-2',
31: 'Portal Certificate',
32: 'iSCSI Name',
33: 'iSCSI Node Type',
34: 'iSCSI Alias',
35: 'iSCSI SCN Bitmap',
36: 'iSCSI Node Index',
37: 'WWNN Token',
38: 'iSCSI Node Next Index',
42: 'iSCSI AuthMethod',
48: 'PG iSCSI Name',
49: 'PG Portal IP Addr',
50: 'PG Portal TCP/UDP Port',
51: 'PG Tag (PGT)',
52: 'PG Index',
53: 'PG Next Index',
64: 'FC Port Name WWPN',
65: 'Port ID',
66: 'FC Port Type',
67: 'Symbolic Port Name',
68: 'Fabric Port Name',
69: 'Hard Address',
70: 'Port IP-Address',
71: 'Class of Service',
72: 'FC-4 Types',
73: 'FC-4 Descriptor',
74: 'FC-4 Features',
75: 'iFCP SCN bitmap',
76: 'Port Role',
77: 'Permanent Port Name',
95: 'FC-4 Type Code',
96: 'FC Node Name WWNN',
97: 'Symbolic Node Name',
98: 'Node IP-Address',
99: 'Node IPA',
101: 'Proxy iSCSI Name',
128: 'Switch Name',
129: 'Preferred ID',
130: 'Assigned ID',
131: 'Virtual_Fabric_ID',
256: 'iSNS Server Vendor OUI',
2049: 'DD_Set ID',
2050: 'DD_Set Sym Name',
2051: 'DD_Set Status',
2052: 'DD_Set_Next_ID',
2065: 'DD_ID',
2066: 'DD_Symbolic Name',
2067: 'DD_Member iSCSI Index',
2068: 'DD_Member iSCSI Name',
2069: 'DD_Member FC Port Name',
2070: 'DD_Member Portal Index',
2071: 'DD_Member Portal IP Addr',
2072: 'DD_Member Portal TCP/UDP',
2078: 'DD_Features',
2079: 'DD_ID Next ID',
}
inv_tag_map: ClassVar[Dict[str, int]] = {v: k for k, v in tag_map.items()}
packet_fmt: ClassVar[str] = '!LL'
variable_length: ClassVar[List[int]] = [1, 11, 12, 18, 28, 29, 31, 32, 34,
42, 48, 67, 73, 97, 101, 131, 2050,
2066, 2068]
string_attrs: ClassVar[List[int]] = [1, 18, 32, 34, 48, 67, 73, 97, 101,
131, 2050, 2066, 2068]
@property
def asbytes(self):
tagval = self.inv_tag_map[self.tag]
if tagval in self.variable_length:
# Were we passed in a string?
if isinstance(self.val, str):
data = bytearray(self.val, 'utf-8')
elif isinstance(self.val, bytes):
data = bytearray(self.val)
elif isinstance(self.val, bytearray):
data = self.val
else:
raise ValueError('Invalid type for value')
# Terminate if necessary
if len(data):
if data[len(data) - 1] != 0:
data += b'\0'
# Pad as necessary
while len(data) % 4 != 0:
data += b'\0'
else:
data = self.val
self.length = len(data)
packet_head = [
tagval,
self.length,
]
encoded_packet = struct.pack(self.packet_fmt, *packet_head)
encoded_packet += data
return encoded_packet
@classmethod
def from_bytes(cls, packet: bytes):
"""
Given a iSNSP attribute in bytes / wire format return a iSNSPAttribute
object.
"""
try:
decoded_packet = [
field.rstrip(b'\x00') if isinstance(field, bytes) else field
for field in struct.unpack(
cls.packet_fmt, packet[:8]
)
]
except Exception as e:
raise MalformedPacketError(f'Unable to parse iSNSP attribute: {e}')
data = packet[8: 8 + decoded_packet[1]]
if decoded_packet[0] in cls.string_attrs:
data = data.decode('utf-8').rstrip('\x00')
decoded_packet[0] = cls.tag_map[decoded_packet[0]]
decoded_packet.append(data)
return cls(*decoded_packet)
@classmethod
def Delimiter(cls):
"""
Convenient constructor for a iSNSP Delimiter attr.
"""
return cls(
'Delimiter',
0,
bytes())
@classmethod
def iSCSIName(cls, name):
"""
Convenient constructor for a iSNSP iSCSI Name attr.
"""
return cls(
'iSCSI Name',
0,
name)
@classmethod
def EntityIdentifier(cls, name):
"""
Convenient constructor for a iSNSP Entity Identifier attr.
"""
return cls(
'Entity Identifier',
0,
name)
@classmethod
def PortalIPAddress(cls, name):
"""
Convenient constructor for a iSNSP Portal IP Address attr.
"""
return cls(
'Portal IP Address',
0,
name)
@classmethod
def iSCSINodeType(cls, val):
"""
Convenient constructor for a iSCSI Node Type attr.
"""
return cls(
'iSCSI Node Type',
4,
val.to_bytes(4, byteorder='big'))
@dataclass
class iSNSPPacket(object):
"""
This class models a iSNSP packet. From RFC 4171:
Byte MSb LSb
Offset 0 15 16 31
+---------------------+----------------------+
0 | iSNSP VERSION | FUNCTION ID | 4 Bytes
+---------------------+----------------------+
4 | PDU LENGTH | FLAGS | 4 Bytes
+---------------------+----------------------+
8 | TRANSACTION ID | SEQUENCE ID | 4 Bytes
+---------------------+----------------------+
12 | |
| PDU PAYLOAD | N Bytes
| ... |
+--------------------------------------------+
12+N | AUTHENTICATION BLOCK (Multicast/Broadcast) | L Bytes
+--------------------------------------------+
Total Length = 12 + N + L
"""
version: int # 2 octets - 0x0001
function: str # 2 octets
pdulen: int # 2 octets
flags: iSNSPFlags # 2 octets
txnid: int # 2 octets - a unique value for each concurrently
# outstanding request message.
seqid: int # 2 octets - unique value for each PDU within a single
# transaction. The SEQUENCE_ID value of the
# first PDU transmitted in a given iSNS
# message MUST be zero (0), and each
# SEQUENCE_ID value in each PDU MUST be
# numbered sequentially in the order in
# which the PDUs are transmitted.
payload: list[iSNSPAttribute]
payload_offset: ClassVar[int] = 12
packet_fmt: ClassVar[str] = '!HHHHHH'
func_map: ClassVar[Dict[int, str]] = {
0x0001: 'DevAttrReg',
0x0002: 'DevAttrQry',
0x0003: 'DevGetNext',
0x0004: 'DevDereg',
0x0005: 'SCNReg',
0x0006: 'SCNDereg',
0x0007: 'SCNEvent',
0x0008: 'SCN',
0x0009: 'DDReg',
0x000A: 'DDDereg',
0x000B: 'DDSReg',
0x000C: 'DDSDereg',
0x000D: 'ESI',
0x000E: 'Heartbeat',
0x0011: 'RqstDomId',
0x0012: 'RlseDomId',
0x0013: 'GetDomId',
0x8001: 'DevAttrRegRsp',
0x8002: 'DevAttrQryRsp',
0x8003: 'DevGetNextRsp',
0x8004: 'DevDeregRsp',
0x8005: 'SCNRegRsp',
0x8006: 'SCNDeregRsp',
0x8007: 'SCNEventRsp',
0x8008: 'SCNRsp',
0x8009: 'DDRegRsp',
0x800A: 'DDDeregRsp',
0x800B: 'DDSRegRsp',
0x800C: 'DDSDeregRsp',
0x800D: 'ESIRsp',
0x8011: 'RqstDomIdRsp',
0x8012: 'RlseDomIdRsp',
0x8013: 'GetDomIdRsp',
}
ifunc_map: ClassVar[Dict[str, int]] = {v: k for k, v in func_map.items()}
HEADER_LENGTH = 12
@property
def asbytes(self):
payload_bytes = bytes()
for attr in self.payload:
payload_bytes += attr.asbytes
self.pdulen = len(payload_bytes)
packet_head = [
self.version,
self.ifunc_map[self.function],
self.pdulen,
self.flags.int,
self.txnid,
self.seqid,
]
encoded_packet = struct.pack(self.packet_fmt, *packet_head)
encoded_packet += payload_bytes
return encoded_packet
@property
def msg_type(self) -> Optional[str]:
if msg_type_option := self.options.by_code(53):
return list(msg_type_option.value.values())[0]
else:
return None
@classmethod
def pdu_length(cls, packet: bytes):
try:
decoded_packet = [
field.rstrip(b'\x00') if isinstance(field, bytes) else field
for field in struct.unpack(
cls.packet_fmt, packet[: cls.payload_offset]
)
]
except Exception as e:
raise MalformedPacketError(f'Unable to parse iSNSP packet: {e}')
return decoded_packet[2]
@classmethod
def from_bytes(cls, packet: bytes):
"""
Given a iSNSP packet in bytes / wire format return a iSNSPPacket
object.
"""
try:
decoded_packet = [
field.rstrip(b'\x00') if isinstance(field, bytes) else field
for field in struct.unpack(
cls.packet_fmt, packet[: cls.payload_offset]
)
]
except Exception as e:
raise MalformedPacketError(f'Unable to parse iSNSP packet: {e}')
# Decode the function
# decoded_packet[0] = cls.op_map[decoded_packet[0]]
decoded_packet[1] = cls.func_map[decoded_packet[1]]
flags = iSNSPFlags.from_val(decoded_packet[3])
decoded_packet[3] = flags
# Handle payload
_data = packet[cls.payload_offset:]
payload = []
# If this is a response from the server, then the first part of the
# payload is the status.
if flags.server:
payload.append(ResponseStatus(int.from_bytes(_data[:4], 'big')))
_data = _data[4:]
while _data:
attr = iSNSPAttribute.from_bytes(_data)
_data = _data[8 + attr.length:]
payload.append(attr)
decoded_packet.append(payload)
return cls(*decoded_packet)
@classmethod
def DevGetNext(
cls,
flags: iSNSPFlags,
txnid: int,
seqid: int,
payload: list[iSNSPAttribute],
):
"""
Convenient constructor for a iSNSP DevGetNext packet.
"""
return cls(
1,
'DevGetNext',
0,
flags,
txnid,
seqid,
payload)
@classmethod
def DevAttrQry(
cls,
flags: iSNSPFlags,
txnid: int,
seqid: int,
payload: list[iSNSPAttribute],
):
"""
Convenient constructor for a iSNSP DevAttrQry packet.
"""
return cls(
1,
'DevAttrQry',
0,
flags,
txnid,
seqid,
payload)
@classmethod
def DevAttrReg(
cls,
flags: iSNSPFlags,
txnid: int,
seqid: int,
payload: list[iSNSPAttribute],
):
"""
Convenient constructor for a iSNSP DevAttrReg packet.
"""
return cls(
1,
'DevAttrReg',
0,
flags,
txnid,
seqid,
payload)
@classmethod
def DevDereg(
cls,
flags: iSNSPFlags,
txnid: int,
seqid: int,
payload: list[iSNSPAttribute],
):
"""
Convenient constructor for a iSNSP DevDereg packet.
"""
return cls(
1,
'DevDereg',
0,
flags,
txnid,
seqid,
payload)
| 15,911 | Python | .py | 481 | 23.746362 | 79 | 0.49477 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,379 | exceptions.py | truenas_middleware/tests/protocols/iSNSP/exceptions.py | class iSNSPException(Exception):
"""
Base exception for our iSNSP functions
"""
class MalformedPacketError(iSNSPException):
"""
The iSNSP packet has some sort of issue
"""
| 198 | Python | .py | 8 | 20.5 | 43 | 0.702128 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,380 | libpython.py | truenas_middleware/src/freenas/usr/local/share/python-gdb/libpython.py | #!/usr/bin/python
'''
From gdb 7 onwards, gdb's build can be configured --with-python, allowing gdb
to be extended with Python code e.g. for library-specific data visualizations,
such as for the C++ STL types. Documentation on this API can be seen at:
http://sourceware.org/gdb/current/onlinedocs/gdb/Python-API.html
This python module deals with the case when the process being debugged (the
"inferior process" in gdb parlance) is itself python, or more specifically,
linked against libpython. In this situation, almost every item of data is a
(PyObject*), and having the debugger merely print their addresses is not very
enlightening.
This module embeds knowledge about the implementation details of libpython so
that we can emit useful visualizations e.g. a string, a list, a dict, a frame
giving file/line information and the state of local variables
In particular, given a gdb.Value corresponding to a PyObject* in the inferior
process, we can generate a "proxy value" within the gdb process. For example,
given a PyObject* in the inferior process that is in fact a PyListObject*
holding three PyObject* that turn out to be PyBytesObject* instances, we can
generate a proxy value within the gdb process that is a list of bytes
instances:
[b"foo", b"bar", b"baz"]
Doing so can be expensive for complicated graphs of objects, and could take
some time, so we also have a "write_repr" method that writes a representation
of the data to a file-like object. This allows us to stop the traversal by
having the file-like object raise an exception if it gets too much data.
With both "proxyval" and "write_repr" we keep track of the set of all addresses
visited so far in the traversal, to avoid infinite recursion due to cycles in
the graph of object references.
We try to defer gdb.lookup_type() invocations for python types until as late as
possible: for a dynamically linked python binary, when the process starts in
the debugger, the libpython.so hasn't been dynamically loaded yet, so none of
the type names are known to the debugger
The module also extends gdb with some python-specific commands.
'''
# NOTE: some gdbs are linked with Python 3, so this file should be dual-syntax
# compatible (2.6+ and 3.0+). See #19308.
from __future__ import print_function
import gdb
import os
import locale
import sys
if sys.version_info[0] >= 3:
unichr = chr
xrange = range
long = int
# Look up the gdb.Type for some standard types:
# Those need to be refreshed as types (pointer sizes) may change when
# gdb loads different executables
def _type_char_ptr():
return gdb.lookup_type('char').pointer() # char*
def _type_unsigned_char_ptr():
return gdb.lookup_type('unsigned char').pointer() # unsigned char*
def _type_unsigned_short_ptr():
return gdb.lookup_type('unsigned short').pointer()
def _type_unsigned_int_ptr():
return gdb.lookup_type('unsigned int').pointer()
def _sizeof_void_p():
return gdb.lookup_type('void').pointer().sizeof
# value computed later, see PyUnicodeObjectPtr.proxy()
_is_pep393 = None
Py_TPFLAGS_HEAPTYPE = (1 << 9)
Py_TPFLAGS_LONG_SUBCLASS = (1 << 24)
Py_TPFLAGS_LIST_SUBCLASS = (1 << 25)
Py_TPFLAGS_TUPLE_SUBCLASS = (1 << 26)
Py_TPFLAGS_BYTES_SUBCLASS = (1 << 27)
Py_TPFLAGS_UNICODE_SUBCLASS = (1 << 28)
Py_TPFLAGS_DICT_SUBCLASS = (1 << 29)
Py_TPFLAGS_BASE_EXC_SUBCLASS = (1 << 30)
Py_TPFLAGS_TYPE_SUBCLASS = (1 << 31)
MAX_OUTPUT_LEN=1024
hexdigits = "0123456789abcdef"
ENCODING = locale.getpreferredencoding()
class NullPyObjectPtr(RuntimeError):
pass
def safety_limit(val):
# Given an integer value from the process being debugged, limit it to some
# safety threshold so that arbitrary breakage within said process doesn't
# break the gdb process too much (e.g. sizes of iterations, sizes of lists)
return min(val, 1000)
def safe_range(val):
# As per range, but don't trust the value too much: cap it to a safety
# threshold in case the data was corrupted
return xrange(safety_limit(int(val)))
if sys.version_info[0] >= 3:
def write_unicode(file, text):
file.write(text)
else:
def write_unicode(file, text):
# Write a byte or unicode string to file. Unicode strings are encoded to
# ENCODING encoding with 'backslashreplace' error handler to avoid
# UnicodeEncodeError.
if isinstance(text, unicode):
text = text.encode(ENCODING, 'backslashreplace')
file.write(text)
try:
os_fsencode = os.fsencode
except AttributeError:
def os_fsencode(filename):
if not isinstance(filename, unicode):
return filename
encoding = sys.getfilesystemencoding()
if encoding == 'mbcs':
# mbcs doesn't support surrogateescape
return filename.encode(encoding)
encoded = []
for char in filename:
# surrogateescape error handler
if 0xDC80 <= ord(char) <= 0xDCFF:
byte = chr(ord(char) - 0xDC00)
else:
byte = char.encode(encoding)
encoded.append(byte)
return ''.join(encoded)
class StringTruncated(RuntimeError):
pass
class TruncatedStringIO(object):
'''Similar to io.StringIO, but can truncate the output by raising a
StringTruncated exception'''
def __init__(self, maxlen=None):
self._val = ''
self.maxlen = maxlen
def write(self, data):
if self.maxlen:
if len(data) + len(self._val) > self.maxlen:
# Truncation:
self._val += data[0:self.maxlen - len(self._val)]
raise StringTruncated()
self._val += data
def getvalue(self):
return self._val
class PyObjectPtr(object):
"""
Class wrapping a gdb.Value that's either a (PyObject*) within the
inferior process, or some subclass pointer e.g. (PyBytesObject*)
There will be a subclass for every refined PyObject type that we care
about.
Note that at every stage the underlying pointer could be NULL, point
to corrupt data, etc; this is the debugger, after all.
"""
_typename = 'PyObject'
def __init__(self, gdbval, cast_to=None):
if cast_to:
self._gdbval = gdbval.cast(cast_to)
else:
self._gdbval = gdbval
def field(self, name):
'''
Get the gdb.Value for the given field within the PyObject, coping with
some python 2 versus python 3 differences.
Various libpython types are defined using the "PyObject_HEAD" and
"PyObject_VAR_HEAD" macros.
In Python 2, this these are defined so that "ob_type" and (for a var
object) "ob_size" are fields of the type in question.
In Python 3, this is defined as an embedded PyVarObject type thus:
PyVarObject ob_base;
so that the "ob_size" field is located insize the "ob_base" field, and
the "ob_type" is most easily accessed by casting back to a (PyObject*).
'''
if self.is_null():
raise NullPyObjectPtr(self)
if name == 'ob_type':
pyo_ptr = self._gdbval.cast(PyObjectPtr.get_gdb_type())
return pyo_ptr.dereference()[name]
if name == 'ob_size':
pyo_ptr = self._gdbval.cast(PyVarObjectPtr.get_gdb_type())
return pyo_ptr.dereference()[name]
# General case: look it up inside the object:
return self._gdbval.dereference()[name]
def pyop_field(self, name):
'''
Get a PyObjectPtr for the given PyObject* field within this PyObject,
coping with some python 2 versus python 3 differences.
'''
return PyObjectPtr.from_pyobject_ptr(self.field(name))
def write_field_repr(self, name, out, visited):
'''
Extract the PyObject* field named "name", and write its representation
to file-like object "out"
'''
field_obj = self.pyop_field(name)
field_obj.write_repr(out, visited)
def get_truncated_repr(self, maxlen):
'''
Get a repr-like string for the data, but truncate it at "maxlen" bytes
(ending the object graph traversal as soon as you do)
'''
out = TruncatedStringIO(maxlen)
try:
self.write_repr(out, set())
except StringTruncated:
# Truncation occurred:
return out.getvalue() + '...(truncated)'
# No truncation occurred:
return out.getvalue()
def type(self):
return PyTypeObjectPtr(self.field('ob_type'))
def is_null(self):
return 0 == long(self._gdbval)
def is_optimized_out(self):
'''
Is the value of the underlying PyObject* visible to the debugger?
This can vary with the precise version of the compiler used to build
Python, and the precise version of gdb.
See e.g. https://bugzilla.redhat.com/show_bug.cgi?id=556975 with
PyEval_EvalFrameEx's "f"
'''
return self._gdbval.is_optimized_out
def safe_tp_name(self):
try:
return self.type().field('tp_name').string()
except NullPyObjectPtr:
# NULL tp_name?
return 'unknown'
except RuntimeError:
# Can't even read the object at all?
return 'unknown'
def proxyval(self, visited):
'''
Scrape a value from the inferior process, and try to represent it
within the gdb process, whilst (hopefully) avoiding crashes when
the remote data is corrupt.
Derived classes will override this.
For example, a PyIntObject* with ob_ival 42 in the inferior process
should result in an int(42) in this process.
visited: a set of all gdb.Value pyobject pointers already visited
whilst generating this value (to guard against infinite recursion when
visiting object graphs with loops). Analogous to Py_ReprEnter and
Py_ReprLeave
'''
class FakeRepr(object):
"""
Class representing a non-descript PyObject* value in the inferior
process for when we don't have a custom scraper, intended to have
a sane repr().
"""
def __init__(self, tp_name, address):
self.tp_name = tp_name
self.address = address
def __repr__(self):
# For the NULL pointer, we have no way of knowing a type, so
# special-case it as per
# http://bugs.python.org/issue8032#msg100882
if self.address == 0:
return '0x0'
return '<%s at remote 0x%x>' % (self.tp_name, self.address)
return FakeRepr(self.safe_tp_name(),
long(self._gdbval))
def write_repr(self, out, visited):
'''
Write a string representation of the value scraped from the inferior
process to "out", a file-like object.
'''
# Default implementation: generate a proxy value and write its repr
# However, this could involve a lot of work for complicated objects,
# so for derived classes we specialize this
return out.write(repr(self.proxyval(visited)))
@classmethod
def subclass_from_type(cls, t):
'''
Given a PyTypeObjectPtr instance wrapping a gdb.Value that's a
(PyTypeObject*), determine the corresponding subclass of PyObjectPtr
to use
Ideally, we would look up the symbols for the global types, but that
isn't working yet:
(gdb) python print gdb.lookup_symbol('PyList_Type')[0].value
Traceback (most recent call last):
File "<string>", line 1, in <module>
NotImplementedError: Symbol type not yet supported in Python scripts.
Error while executing Python code.
For now, we use tp_flags, after doing some string comparisons on the
tp_name for some special-cases that don't seem to be visible through
flags
'''
try:
tp_name = t.field('tp_name').string()
tp_flags = int(t.field('tp_flags'))
except RuntimeError:
# Handle any kind of error e.g. NULL ptrs by simply using the base
# class
return cls
#print('tp_flags = 0x%08x' % tp_flags)
#print('tp_name = %r' % tp_name)
name_map = {'bool': PyBoolObjectPtr,
'classobj': PyClassObjectPtr,
'NoneType': PyNoneStructPtr,
'frame': PyFrameObjectPtr,
'set' : PySetObjectPtr,
'frozenset' : PySetObjectPtr,
'builtin_function_or_method' : PyCFunctionObjectPtr,
'method-wrapper': wrapperobject,
}
if tp_name in name_map:
return name_map[tp_name]
if tp_flags & Py_TPFLAGS_HEAPTYPE:
return HeapTypeObjectPtr
if tp_flags & Py_TPFLAGS_LONG_SUBCLASS:
return PyLongObjectPtr
if tp_flags & Py_TPFLAGS_LIST_SUBCLASS:
return PyListObjectPtr
if tp_flags & Py_TPFLAGS_TUPLE_SUBCLASS:
return PyTupleObjectPtr
if tp_flags & Py_TPFLAGS_BYTES_SUBCLASS:
return PyBytesObjectPtr
if tp_flags & Py_TPFLAGS_UNICODE_SUBCLASS:
return PyUnicodeObjectPtr
if tp_flags & Py_TPFLAGS_DICT_SUBCLASS:
return PyDictObjectPtr
if tp_flags & Py_TPFLAGS_BASE_EXC_SUBCLASS:
return PyBaseExceptionObjectPtr
#if tp_flags & Py_TPFLAGS_TYPE_SUBCLASS:
# return PyTypeObjectPtr
# Use the base class:
return cls
@classmethod
def from_pyobject_ptr(cls, gdbval):
'''
Try to locate the appropriate derived class dynamically, and cast
the pointer accordingly.
'''
try:
p = PyObjectPtr(gdbval)
cls = cls.subclass_from_type(p.type())
return cls(gdbval, cast_to=cls.get_gdb_type())
except RuntimeError:
# Handle any kind of error e.g. NULL ptrs by simply using the base
# class
pass
return cls(gdbval)
@classmethod
def get_gdb_type(cls):
return gdb.lookup_type(cls._typename).pointer()
def as_address(self):
return long(self._gdbval)
class PyVarObjectPtr(PyObjectPtr):
_typename = 'PyVarObject'
class ProxyAlreadyVisited(object):
'''
Placeholder proxy to use when protecting against infinite recursion due to
loops in the object graph.
Analogous to the values emitted by the users of Py_ReprEnter and Py_ReprLeave
'''
def __init__(self, rep):
self._rep = rep
def __repr__(self):
return self._rep
def _write_instance_repr(out, visited, name, pyop_attrdict, address):
'''Shared code for use by all classes:
write a representation to file-like object "out"'''
out.write('<')
out.write(name)
# Write dictionary of instance attributes:
if isinstance(pyop_attrdict, PyDictObjectPtr):
out.write('(')
first = True
for pyop_arg, pyop_val in pyop_attrdict.iteritems():
if not first:
out.write(', ')
first = False
out.write(pyop_arg.proxyval(visited))
out.write('=')
pyop_val.write_repr(out, visited)
out.write(')')
out.write(' at remote 0x%x>' % address)
class InstanceProxy(object):
def __init__(self, cl_name, attrdict, address):
self.cl_name = cl_name
self.attrdict = attrdict
self.address = address
def __repr__(self):
if isinstance(self.attrdict, dict):
kwargs = ', '.join(["%s=%r" % (arg, val)
for arg, val in self.attrdict.iteritems()])
return '<%s(%s) at remote 0x%x>' % (self.cl_name,
kwargs, self.address)
else:
return '<%s at remote 0x%x>' % (self.cl_name,
self.address)
def _PyObject_VAR_SIZE(typeobj, nitems):
if _PyObject_VAR_SIZE._type_size_t is None:
_PyObject_VAR_SIZE._type_size_t = gdb.lookup_type('size_t')
return ( ( typeobj.field('tp_basicsize') +
nitems * typeobj.field('tp_itemsize') +
(_sizeof_void_p() - 1)
) & ~(_sizeof_void_p() - 1)
).cast(_PyObject_VAR_SIZE._type_size_t)
_PyObject_VAR_SIZE._type_size_t = None
class HeapTypeObjectPtr(PyObjectPtr):
_typename = 'PyObject'
def get_attr_dict(self):
'''
Get the PyDictObject ptr representing the attribute dictionary
(or None if there's a problem)
'''
try:
typeobj = self.type()
dictoffset = int_from_int(typeobj.field('tp_dictoffset'))
if dictoffset != 0:
if dictoffset < 0:
type_PyVarObject_ptr = gdb.lookup_type('PyVarObject').pointer()
tsize = int_from_int(self._gdbval.cast(type_PyVarObject_ptr)['ob_size'])
if tsize < 0:
tsize = -tsize
size = _PyObject_VAR_SIZE(typeobj, tsize)
dictoffset += size
assert dictoffset > 0
assert dictoffset % _sizeof_void_p() == 0
dictptr = self._gdbval.cast(_type_char_ptr()) + dictoffset
PyObjectPtrPtr = PyObjectPtr.get_gdb_type().pointer()
dictptr = dictptr.cast(PyObjectPtrPtr)
return PyObjectPtr.from_pyobject_ptr(dictptr.dereference())
except RuntimeError:
# Corrupt data somewhere; fail safe
pass
# Not found, or some kind of error:
return None
def proxyval(self, visited):
'''
Support for classes.
Currently we just locate the dictionary using a transliteration to
python of _PyObject_GetDictPtr, ignoring descriptors
'''
# Guard against infinite loops:
if self.as_address() in visited:
return ProxyAlreadyVisited('<...>')
visited.add(self.as_address())
pyop_attr_dict = self.get_attr_dict()
if pyop_attr_dict:
attr_dict = pyop_attr_dict.proxyval(visited)
else:
attr_dict = {}
tp_name = self.safe_tp_name()
# Class:
return InstanceProxy(tp_name, attr_dict, long(self._gdbval))
def write_repr(self, out, visited):
# Guard against infinite loops:
if self.as_address() in visited:
out.write('<...>')
return
visited.add(self.as_address())
pyop_attrdict = self.get_attr_dict()
_write_instance_repr(out, visited,
self.safe_tp_name(), pyop_attrdict, self.as_address())
class ProxyException(Exception):
def __init__(self, tp_name, args):
self.tp_name = tp_name
self.args = args
def __repr__(self):
return '%s%r' % (self.tp_name, self.args)
class PyBaseExceptionObjectPtr(PyObjectPtr):
"""
Class wrapping a gdb.Value that's a PyBaseExceptionObject* i.e. an exception
within the process being debugged.
"""
_typename = 'PyBaseExceptionObject'
def proxyval(self, visited):
# Guard against infinite loops:
if self.as_address() in visited:
return ProxyAlreadyVisited('(...)')
visited.add(self.as_address())
arg_proxy = self.pyop_field('args').proxyval(visited)
return ProxyException(self.safe_tp_name(),
arg_proxy)
def write_repr(self, out, visited):
# Guard against infinite loops:
if self.as_address() in visited:
out.write('(...)')
return
visited.add(self.as_address())
out.write(self.safe_tp_name())
self.write_field_repr('args', out, visited)
class PyClassObjectPtr(PyObjectPtr):
"""
Class wrapping a gdb.Value that's a PyClassObject* i.e. a <classobj>
instance within the process being debugged.
"""
_typename = 'PyClassObject'
class BuiltInFunctionProxy(object):
def __init__(self, ml_name):
self.ml_name = ml_name
def __repr__(self):
return "<built-in function %s>" % self.ml_name
class BuiltInMethodProxy(object):
def __init__(self, ml_name, pyop_m_self):
self.ml_name = ml_name
self.pyop_m_self = pyop_m_self
def __repr__(self):
return ('<built-in method %s of %s object at remote 0x%x>'
% (self.ml_name,
self.pyop_m_self.safe_tp_name(),
self.pyop_m_self.as_address())
)
class PyCFunctionObjectPtr(PyObjectPtr):
"""
Class wrapping a gdb.Value that's a PyCFunctionObject*
(see Include/methodobject.h and Objects/methodobject.c)
"""
_typename = 'PyCFunctionObject'
def proxyval(self, visited):
m_ml = self.field('m_ml') # m_ml is a (PyMethodDef*)
ml_name = m_ml['ml_name'].string()
pyop_m_self = self.pyop_field('m_self')
if pyop_m_self.is_null():
return BuiltInFunctionProxy(ml_name)
else:
return BuiltInMethodProxy(ml_name, pyop_m_self)
class PyCodeObjectPtr(PyObjectPtr):
"""
Class wrapping a gdb.Value that's a PyCodeObject* i.e. a <code> instance
within the process being debugged.
"""
_typename = 'PyCodeObject'
def addr2line(self, addrq):
'''
Get the line number for a given bytecode offset
Analogous to PyCode_Addr2Line; translated from pseudocode in
Objects/lnotab_notes.txt
'''
co_lnotab = self.pyop_field('co_lnotab').proxyval(set())
# Initialize lineno to co_firstlineno as per PyCode_Addr2Line
# not 0, as lnotab_notes.txt has it:
lineno = int_from_int(self.field('co_firstlineno'))
addr = 0
for addr_incr, line_incr in zip(co_lnotab[::2], co_lnotab[1::2]):
addr += ord(addr_incr)
if addr > addrq:
return lineno
lineno += ord(line_incr)
return lineno
class PyDictObjectPtr(PyObjectPtr):
"""
Class wrapping a gdb.Value that's a PyDictObject* i.e. a dict instance
within the process being debugged.
"""
_typename = 'PyDictObject'
def iteritems(self):
'''
Yields a sequence of (PyObjectPtr key, PyObjectPtr value) pairs,
analogous to dict.iteritems()
'''
keys = self.field('ma_keys')
values = self.field('ma_values')
entries, nentries = self._get_entries(keys)
for i in safe_range(nentries):
ep = entries[i]
if long(values):
pyop_value = PyObjectPtr.from_pyobject_ptr(values[i])
else:
pyop_value = PyObjectPtr.from_pyobject_ptr(ep['me_value'])
if not pyop_value.is_null():
pyop_key = PyObjectPtr.from_pyobject_ptr(ep['me_key'])
yield (pyop_key, pyop_value)
def proxyval(self, visited):
# Guard against infinite loops:
if self.as_address() in visited:
return ProxyAlreadyVisited('{...}')
visited.add(self.as_address())
result = {}
for pyop_key, pyop_value in self.iteritems():
proxy_key = pyop_key.proxyval(visited)
proxy_value = pyop_value.proxyval(visited)
result[proxy_key] = proxy_value
return result
def write_repr(self, out, visited):
# Guard against infinite loops:
if self.as_address() in visited:
out.write('{...}')
return
visited.add(self.as_address())
out.write('{')
first = True
for pyop_key, pyop_value in self.iteritems():
if not first:
out.write(', ')
first = False
pyop_key.write_repr(out, visited)
out.write(': ')
pyop_value.write_repr(out, visited)
out.write('}')
def _get_entries(self, keys):
dk_nentries = int(keys['dk_nentries'])
dk_size = int(keys['dk_size'])
try:
# <= Python 3.5
return keys['dk_entries'], dk_size
except gdb.error:
# >= Python 3.6
pass
if dk_size <= 0xFF:
offset = dk_size
elif dk_size <= 0xFFFF:
offset = 2 * dk_size
elif dk_size <= 0xFFFFFFFF:
offset = 4 * dk_size
else:
offset = 8 * dk_size
ent_addr = keys['dk_indices']['as_1'].address
ent_addr = ent_addr.cast(_type_unsigned_char_ptr()) + offset
ent_ptr_t = gdb.lookup_type('PyDictKeyEntry').pointer()
ent_addr = ent_addr.cast(ent_ptr_t)
return ent_addr, dk_nentries
class PyListObjectPtr(PyObjectPtr):
_typename = 'PyListObject'
def __getitem__(self, i):
# Get the gdb.Value for the (PyObject*) with the given index:
field_ob_item = self.field('ob_item')
return field_ob_item[i]
def proxyval(self, visited):
# Guard against infinite loops:
if self.as_address() in visited:
return ProxyAlreadyVisited('[...]')
visited.add(self.as_address())
result = [PyObjectPtr.from_pyobject_ptr(self[i]).proxyval(visited)
for i in safe_range(int_from_int(self.field('ob_size')))]
return result
def write_repr(self, out, visited):
# Guard against infinite loops:
if self.as_address() in visited:
out.write('[...]')
return
visited.add(self.as_address())
out.write('[')
for i in safe_range(int_from_int(self.field('ob_size'))):
if i > 0:
out.write(', ')
element = PyObjectPtr.from_pyobject_ptr(self[i])
element.write_repr(out, visited)
out.write(']')
class PyLongObjectPtr(PyObjectPtr):
_typename = 'PyLongObject'
def proxyval(self, visited):
'''
Python's Include/longobjrep.h has this declaration:
struct _longobject {
PyObject_VAR_HEAD
digit ob_digit[1];
};
with this description:
The absolute value of a number is equal to
SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
Negative numbers are represented with ob_size < 0;
zero is represented by ob_size == 0.
where SHIFT can be either:
#define PyLong_SHIFT 30
#define PyLong_SHIFT 15
'''
ob_size = long(self.field('ob_size'))
if ob_size == 0:
return 0
ob_digit = self.field('ob_digit')
if gdb.lookup_type('digit').sizeof == 2:
SHIFT = 15
else:
SHIFT = 30
digits = [long(ob_digit[i]) * 2**(SHIFT*i)
for i in safe_range(abs(ob_size))]
result = sum(digits)
if ob_size < 0:
result = -result
return result
def write_repr(self, out, visited):
# Write this out as a Python 3 int literal, i.e. without the "L" suffix
proxy = self.proxyval(visited)
out.write("%s" % proxy)
class PyBoolObjectPtr(PyLongObjectPtr):
"""
Class wrapping a gdb.Value that's a PyBoolObject* i.e. one of the two
<bool> instances (Py_True/Py_False) within the process being debugged.
"""
def proxyval(self, visited):
if PyLongObjectPtr.proxyval(self, visited):
return True
else:
return False
class PyNoneStructPtr(PyObjectPtr):
"""
Class wrapping a gdb.Value that's a PyObject* pointing to the
singleton (we hope) _Py_NoneStruct with ob_type PyNone_Type
"""
_typename = 'PyObject'
def proxyval(self, visited):
return None
class PyFrameObjectPtr(PyObjectPtr):
_typename = 'PyFrameObject'
def __init__(self, gdbval, cast_to=None):
PyObjectPtr.__init__(self, gdbval, cast_to)
if not self.is_optimized_out():
self.co = PyCodeObjectPtr.from_pyobject_ptr(self.field('f_code'))
self.co_name = self.co.pyop_field('co_name')
self.co_filename = self.co.pyop_field('co_filename')
self.f_lineno = int_from_int(self.field('f_lineno'))
self.f_lasti = int_from_int(self.field('f_lasti'))
self.co_nlocals = int_from_int(self.co.field('co_nlocals'))
self.co_varnames = PyTupleObjectPtr.from_pyobject_ptr(self.co.field('co_varnames'))
def iter_locals(self):
'''
Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
the local variables of this frame
'''
if self.is_optimized_out():
return
f_localsplus = self.field('f_localsplus')
for i in safe_range(self.co_nlocals):
pyop_value = PyObjectPtr.from_pyobject_ptr(f_localsplus[i])
if not pyop_value.is_null():
pyop_name = PyObjectPtr.from_pyobject_ptr(self.co_varnames[i])
yield (pyop_name, pyop_value)
def iter_globals(self):
'''
Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
the global variables of this frame
'''
if self.is_optimized_out():
return ()
pyop_globals = self.pyop_field('f_globals')
return pyop_globals.iteritems()
def iter_builtins(self):
'''
Yield a sequence of (name,value) pairs of PyObjectPtr instances, for
the builtin variables
'''
if self.is_optimized_out():
return ()
pyop_builtins = self.pyop_field('f_builtins')
return pyop_builtins.iteritems()
def get_var_by_name(self, name):
'''
Look for the named local variable, returning a (PyObjectPtr, scope) pair
where scope is a string 'local', 'global', 'builtin'
If not found, return (None, None)
'''
for pyop_name, pyop_value in self.iter_locals():
if name == pyop_name.proxyval(set()):
return pyop_value, 'local'
for pyop_name, pyop_value in self.iter_globals():
if name == pyop_name.proxyval(set()):
return pyop_value, 'global'
for pyop_name, pyop_value in self.iter_builtins():
if name == pyop_name.proxyval(set()):
return pyop_value, 'builtin'
return None, None
def filename(self):
'''Get the path of the current Python source file, as a string'''
if self.is_optimized_out():
return '(frame information optimized out)'
return self.co_filename.proxyval(set())
def current_line_num(self):
'''Get current line number as an integer (1-based)
Translated from PyFrame_GetLineNumber and PyCode_Addr2Line
See Objects/lnotab_notes.txt
'''
if self.is_optimized_out():
return None
f_trace = self.field('f_trace')
if long(f_trace) != 0:
# we have a non-NULL f_trace:
return self.f_lineno
else:
#try:
return self.co.addr2line(self.f_lasti)
#except ValueError:
# return self.f_lineno
def current_line(self):
'''Get the text of the current source line as a string, with a trailing
newline character'''
if self.is_optimized_out():
return '(frame information optimized out)'
filename = self.filename()
try:
f = open(os_fsencode(filename), 'r')
except IOError:
return None
with f:
all_lines = f.readlines()
# Convert from 1-based current_line_num to 0-based list offset:
return all_lines[self.current_line_num()-1]
def write_repr(self, out, visited):
if self.is_optimized_out():
out.write('(frame information optimized out)')
return
out.write('Frame 0x%x, for file %s, line %i, in %s ('
% (self.as_address(),
self.co_filename.proxyval(visited),
self.current_line_num(),
self.co_name.proxyval(visited)))
first = True
for pyop_name, pyop_value in self.iter_locals():
if not first:
out.write(', ')
first = False
out.write(pyop_name.proxyval(visited))
out.write('=')
pyop_value.write_repr(out, visited)
out.write(')')
def print_traceback(self):
if self.is_optimized_out():
sys.stdout.write(' (frame information optimized out)\n')
return
visited = set()
sys.stdout.write(' File "%s", line %i, in %s\n'
% (self.co_filename.proxyval(visited),
self.current_line_num(),
self.co_name.proxyval(visited)))
class PySetObjectPtr(PyObjectPtr):
_typename = 'PySetObject'
@classmethod
def _dummy_key(self):
return gdb.lookup_global_symbol('_PySet_Dummy').value()
def __iter__(self):
dummy_ptr = self._dummy_key()
table = self.field('table')
for i in safe_range(self.field('mask') + 1):
setentry = table[i]
key = setentry['key']
if key != 0 and key != dummy_ptr:
yield PyObjectPtr.from_pyobject_ptr(key)
def proxyval(self, visited):
# Guard against infinite loops:
if self.as_address() in visited:
return ProxyAlreadyVisited('%s(...)' % self.safe_tp_name())
visited.add(self.as_address())
members = (key.proxyval(visited) for key in self)
if self.safe_tp_name() == 'frozenset':
return frozenset(members)
else:
return set(members)
def write_repr(self, out, visited):
# Emulate Python 3's set_repr
tp_name = self.safe_tp_name()
# Guard against infinite loops:
if self.as_address() in visited:
out.write('(...)')
return
visited.add(self.as_address())
# Python 3's set_repr special-cases the empty set:
if not self.field('used'):
out.write(tp_name)
out.write('()')
return
# Python 3 uses {} for set literals:
if tp_name != 'set':
out.write(tp_name)
out.write('(')
out.write('{')
first = True
for key in self:
if not first:
out.write(', ')
first = False
key.write_repr(out, visited)
out.write('}')
if tp_name != 'set':
out.write(')')
class PyBytesObjectPtr(PyObjectPtr):
_typename = 'PyBytesObject'
def __str__(self):
field_ob_size = self.field('ob_size')
field_ob_sval = self.field('ob_sval')
char_ptr = field_ob_sval.address.cast(_type_unsigned_char_ptr())
return ''.join([chr(char_ptr[i]) for i in safe_range(field_ob_size)])
def proxyval(self, visited):
return str(self)
def write_repr(self, out, visited):
# Write this out as a Python 3 bytes literal, i.e. with a "b" prefix
# Get a PyStringObject* within the Python 2 gdb process:
proxy = self.proxyval(visited)
# Transliteration of Python 3's Objects/bytesobject.c:PyBytes_Repr
# to Python 2 code:
quote = "'"
if "'" in proxy and not '"' in proxy:
quote = '"'
out.write('b')
out.write(quote)
for byte in proxy:
if byte == quote or byte == '\\':
out.write('\\')
out.write(byte)
elif byte == '\t':
out.write('\\t')
elif byte == '\n':
out.write('\\n')
elif byte == '\r':
out.write('\\r')
elif byte < ' ' or ord(byte) >= 0x7f:
out.write('\\x')
out.write(hexdigits[(ord(byte) & 0xf0) >> 4])
out.write(hexdigits[ord(byte) & 0xf])
else:
out.write(byte)
out.write(quote)
class PyTupleObjectPtr(PyObjectPtr):
_typename = 'PyTupleObject'
def __getitem__(self, i):
# Get the gdb.Value for the (PyObject*) with the given index:
field_ob_item = self.field('ob_item')
return field_ob_item[i]
def proxyval(self, visited):
# Guard against infinite loops:
if self.as_address() in visited:
return ProxyAlreadyVisited('(...)')
visited.add(self.as_address())
result = tuple([PyObjectPtr.from_pyobject_ptr(self[i]).proxyval(visited)
for i in safe_range(int_from_int(self.field('ob_size')))])
return result
def write_repr(self, out, visited):
# Guard against infinite loops:
if self.as_address() in visited:
out.write('(...)')
return
visited.add(self.as_address())
out.write('(')
for i in safe_range(int_from_int(self.field('ob_size'))):
if i > 0:
out.write(', ')
element = PyObjectPtr.from_pyobject_ptr(self[i])
element.write_repr(out, visited)
if self.field('ob_size') == 1:
out.write(',)')
else:
out.write(')')
class PyTypeObjectPtr(PyObjectPtr):
_typename = 'PyTypeObject'
def _unichr_is_printable(char):
# Logic adapted from Python 3's Tools/unicode/makeunicodedata.py
if char == u" ":
return True
import unicodedata
return unicodedata.category(char) not in ("C", "Z")
if sys.maxunicode >= 0x10000:
_unichr = unichr
else:
# Needed for proper surrogate support if sizeof(Py_UNICODE) is 2 in gdb
def _unichr(x):
if x < 0x10000:
return unichr(x)
x -= 0x10000
ch1 = 0xD800 | (x >> 10)
ch2 = 0xDC00 | (x & 0x3FF)
return unichr(ch1) + unichr(ch2)
class PyUnicodeObjectPtr(PyObjectPtr):
_typename = 'PyUnicodeObject'
def char_width(self):
_type_Py_UNICODE = gdb.lookup_type('Py_UNICODE')
return _type_Py_UNICODE.sizeof
def proxyval(self, visited):
global _is_pep393
if _is_pep393 is None:
fields = gdb.lookup_type('PyUnicodeObject').target().fields()
_is_pep393 = 'data' in [f.name for f in fields]
if _is_pep393:
# Python 3.3 and newer
may_have_surrogates = False
compact = self.field('_base')
ascii = compact['_base']
state = ascii['state']
is_compact_ascii = (int(state['ascii']) and int(state['compact']))
if not int(state['ready']):
# string is not ready
field_length = long(compact['wstr_length'])
may_have_surrogates = True
field_str = ascii['wstr']
else:
field_length = long(ascii['length'])
if is_compact_ascii:
field_str = ascii.address + 1
elif int(state['compact']):
field_str = compact.address + 1
else:
field_str = self.field('data')['any']
repr_kind = int(state['kind'])
if repr_kind == 1:
field_str = field_str.cast(_type_unsigned_char_ptr())
elif repr_kind == 2:
field_str = field_str.cast(_type_unsigned_short_ptr())
elif repr_kind == 4:
field_str = field_str.cast(_type_unsigned_int_ptr())
else:
# Python 3.2 and earlier
field_length = long(self.field('length'))
field_str = self.field('str')
may_have_surrogates = self.char_width() == 2
# Gather a list of ints from the Py_UNICODE array; these are either
# UCS-1, UCS-2 or UCS-4 code points:
if not may_have_surrogates:
Py_UNICODEs = [int(field_str[i]) for i in safe_range(field_length)]
else:
# A more elaborate routine if sizeof(Py_UNICODE) is 2 in the
# inferior process: we must join surrogate pairs.
Py_UNICODEs = []
i = 0
limit = safety_limit(field_length)
while i < limit:
ucs = int(field_str[i])
i += 1
if ucs < 0xD800 or ucs >= 0xDC00 or i == field_length:
Py_UNICODEs.append(ucs)
continue
# This could be a surrogate pair.
ucs2 = int(field_str[i])
if ucs2 < 0xDC00 or ucs2 > 0xDFFF:
continue
code = (ucs & 0x03FF) << 10
code |= ucs2 & 0x03FF
code += 0x00010000
Py_UNICODEs.append(code)
i += 1
# Convert the int code points to unicode characters, and generate a
# local unicode instance.
# This splits surrogate pairs if sizeof(Py_UNICODE) is 2 here (in gdb).
result = u''.join([
(_unichr(ucs) if ucs <= 0x10ffff else '\ufffd')
for ucs in Py_UNICODEs])
return result
def write_repr(self, out, visited):
# Write this out as a Python 3 str literal, i.e. without a "u" prefix
# Get a PyUnicodeObject* within the Python 2 gdb process:
proxy = self.proxyval(visited)
# Transliteration of Python 3's Object/unicodeobject.c:unicode_repr
# to Python 2:
if "'" in proxy and '"' not in proxy:
quote = '"'
else:
quote = "'"
out.write(quote)
i = 0
while i < len(proxy):
ch = proxy[i]
i += 1
# Escape quotes and backslashes
if ch == quote or ch == '\\':
out.write('\\')
out.write(ch)
# Map special whitespace to '\t', \n', '\r'
elif ch == '\t':
out.write('\\t')
elif ch == '\n':
out.write('\\n')
elif ch == '\r':
out.write('\\r')
# Map non-printable US ASCII to '\xhh' */
elif ch < ' ' or ch == 0x7F:
out.write('\\x')
out.write(hexdigits[(ord(ch) >> 4) & 0x000F])
out.write(hexdigits[ord(ch) & 0x000F])
# Copy ASCII characters as-is
elif ord(ch) < 0x7F:
out.write(ch)
# Non-ASCII characters
else:
ucs = ch
ch2 = None
if sys.maxunicode < 0x10000:
# If sizeof(Py_UNICODE) is 2 here (in gdb), join
# surrogate pairs before calling _unichr_is_printable.
if (i < len(proxy)
and 0xD800 <= ord(ch) < 0xDC00 \
and 0xDC00 <= ord(proxy[i]) <= 0xDFFF):
ch2 = proxy[i]
ucs = ch + ch2
i += 1
# Unfortuately, Python 2's unicode type doesn't seem
# to expose the "isprintable" method
printable = _unichr_is_printable(ucs)
if printable:
try:
ucs.encode(ENCODING)
except UnicodeEncodeError:
printable = False
# Map Unicode whitespace and control characters
# (categories Z* and C* except ASCII space)
if not printable:
if ch2 is not None:
# Match Python 3's representation of non-printable
# wide characters.
code = (ord(ch) & 0x03FF) << 10
code |= ord(ch2) & 0x03FF
code += 0x00010000
else:
code = ord(ucs)
# Map 8-bit characters to '\\xhh'
if code <= 0xff:
out.write('\\x')
out.write(hexdigits[(code >> 4) & 0x000F])
out.write(hexdigits[code & 0x000F])
# Map 21-bit characters to '\U00xxxxxx'
elif code >= 0x10000:
out.write('\\U')
out.write(hexdigits[(code >> 28) & 0x0000000F])
out.write(hexdigits[(code >> 24) & 0x0000000F])
out.write(hexdigits[(code >> 20) & 0x0000000F])
out.write(hexdigits[(code >> 16) & 0x0000000F])
out.write(hexdigits[(code >> 12) & 0x0000000F])
out.write(hexdigits[(code >> 8) & 0x0000000F])
out.write(hexdigits[(code >> 4) & 0x0000000F])
out.write(hexdigits[code & 0x0000000F])
# Map 16-bit characters to '\uxxxx'
else:
out.write('\\u')
out.write(hexdigits[(code >> 12) & 0x000F])
out.write(hexdigits[(code >> 8) & 0x000F])
out.write(hexdigits[(code >> 4) & 0x000F])
out.write(hexdigits[code & 0x000F])
else:
# Copy characters as-is
out.write(ch)
if ch2 is not None:
out.write(ch2)
out.write(quote)
class wrapperobject(PyObjectPtr):
_typename = 'wrapperobject'
def safe_name(self):
try:
name = self.field('descr')['d_base']['name'].string()
return repr(name)
except (NullPyObjectPtr, RuntimeError):
return '<unknown name>'
def safe_tp_name(self):
try:
return self.field('self')['ob_type']['tp_name'].string()
except (NullPyObjectPtr, RuntimeError):
return '<unknown tp_name>'
def safe_self_addresss(self):
try:
address = long(self.field('self'))
return '%#x' % address
except (NullPyObjectPtr, RuntimeError):
return '<failed to get self address>'
def proxyval(self, visited):
name = self.safe_name()
tp_name = self.safe_tp_name()
self_address = self.safe_self_addresss()
return ("<method-wrapper %s of %s object at %s>"
% (name, tp_name, self_address))
def write_repr(self, out, visited):
proxy = self.proxyval(visited)
out.write(proxy)
def int_from_int(gdbval):
return int(str(gdbval))
def stringify(val):
# TODO: repr() puts everything on one line; pformat can be nicer, but
# can lead to v.long results; this function isolates the choice
if True:
return repr(val)
else:
from pprint import pformat
return pformat(val)
class PyObjectPtrPrinter:
"Prints a (PyObject*)"
def __init__ (self, gdbval):
self.gdbval = gdbval
def to_string (self):
pyop = PyObjectPtr.from_pyobject_ptr(self.gdbval)
if True:
return pyop.get_truncated_repr(MAX_OUTPUT_LEN)
else:
# Generate full proxy value then stringify it.
# Doing so could be expensive
proxyval = pyop.proxyval(set())
return stringify(proxyval)
def pretty_printer_lookup(gdbval):
type = gdbval.type.unqualified()
if type.code != gdb.TYPE_CODE_PTR:
return None
type = type.target().unqualified()
t = str(type)
if t in ("PyObject", "PyFrameObject", "PyUnicodeObject", "wrapperobject"):
return PyObjectPtrPrinter(gdbval)
"""
During development, I've been manually invoking the code in this way:
(gdb) python
import sys
sys.path.append('/home/david/coding/python-gdb')
import libpython
end
then reloading it after each edit like this:
(gdb) python reload(libpython)
The following code should ensure that the prettyprinter is registered
if the code is autoloaded by gdb when visiting libpython.so, provided
that this python file is installed to the same path as the library (or its
.debug file) plus a "-gdb.py" suffix, e.g:
/usr/lib/libpython2.6.so.1.0-gdb.py
/usr/lib/debug/usr/lib/libpython2.6.so.1.0.debug-gdb.py
"""
def register (obj):
if obj is None:
obj = gdb
# Wire up the pretty-printer
obj.pretty_printers.append(pretty_printer_lookup)
register (gdb.current_objfile ())
# Unfortunately, the exact API exposed by the gdb module varies somewhat
# from build to build
# See http://bugs.python.org/issue8279?#msg102276
class Frame(object):
'''
Wrapper for gdb.Frame, adding various methods
'''
def __init__(self, gdbframe):
self._gdbframe = gdbframe
def older(self):
older = self._gdbframe.older()
if older:
return Frame(older)
else:
return None
def newer(self):
newer = self._gdbframe.newer()
if newer:
return Frame(newer)
else:
return None
def select(self):
'''If supported, select this frame and return True; return False if unsupported
Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
onwards, but absent on Ubuntu buildbot'''
if not hasattr(self._gdbframe, 'select'):
print ('Unable to select frame: '
'this build of gdb does not expose a gdb.Frame.select method')
return False
self._gdbframe.select()
return True
def get_index(self):
'''Calculate index of frame, starting at 0 for the newest frame within
this thread'''
index = 0
# Go down until you reach the newest frame:
iter_frame = self
while iter_frame.newer():
index += 1
iter_frame = iter_frame.newer()
return index
# We divide frames into:
# - "python frames":
# - "bytecode frames" i.e. PyEval_EvalFrameEx
# - "other python frames": things that are of interest from a python
# POV, but aren't bytecode (e.g. GC, GIL)
# - everything else
def is_python_frame(self):
'''Is this a PyEval_EvalFrameEx frame, or some other important
frame? (see is_other_python_frame for what "important" means in this
context)'''
if self.is_evalframeex():
return True
if self.is_other_python_frame():
return True
return False
def is_evalframeex(self):
'''Is this a PyEval_EvalFrameEx frame?'''
if self._gdbframe.name() == 'PyEval_EvalFrameEx':
'''
I believe we also need to filter on the inline
struct frame_id.inline_depth, only regarding frames with
an inline depth of 0 as actually being this function
So we reject those with type gdb.INLINE_FRAME
'''
if self._gdbframe.type() == gdb.NORMAL_FRAME:
# We have a PyEval_EvalFrameEx frame:
return True
return False
def is_other_python_frame(self):
'''Is this frame worth displaying in python backtraces?
Examples:
- waiting on the GIL
- garbage-collecting
- within a CFunction
If it is, return a descriptive string
For other frames, return False
'''
if self.is_waiting_for_gil():
return 'Waiting for the GIL'
if self.is_gc_collect():
return 'Garbage-collecting'
# Detect invocations of PyCFunction instances:
frame = self._gdbframe
caller = frame.name()
if not caller:
return False
if caller in ('_PyCFunction_FastCallDict',
'_PyCFunction_FastCallKeywords'):
arg_name = 'func'
# Within that frame:
# "func" is the local containing the PyObject* of the
# PyCFunctionObject instance
# "f" is the same value, but cast to (PyCFunctionObject*)
# "self" is the (PyObject*) of the 'self'
try:
# Use the prettyprinter for the func:
func = frame.read_var(arg_name)
return str(func)
except RuntimeError:
return 'PyCFunction invocation (unable to read %s)' % arg_name
if caller == 'wrapper_call':
try:
func = frame.read_var('wp')
return str(func)
except RuntimeError:
return '<wrapper_call invocation>'
# This frame isn't worth reporting:
return False
def is_waiting_for_gil(self):
'''Is this frame waiting on the GIL?'''
# This assumes the _POSIX_THREADS version of Python/ceval_gil.h:
name = self._gdbframe.name()
if name:
return 'pthread_cond_timedwait' in name
def is_gc_collect(self):
'''Is this frame "collect" within the garbage-collector?'''
return self._gdbframe.name() == 'collect'
def get_pyop(self):
try:
f = self._gdbframe.read_var('f')
frame = PyFrameObjectPtr.from_pyobject_ptr(f)
if not frame.is_optimized_out():
return frame
# gdb is unable to get the "f" argument of PyEval_EvalFrameEx()
# because it was "optimized out". Try to get "f" from the frame
# of the caller, PyEval_EvalCodeEx().
orig_frame = frame
caller = self._gdbframe.older()
if caller:
f = caller.read_var('f')
frame = PyFrameObjectPtr.from_pyobject_ptr(f)
if not frame.is_optimized_out():
return frame
return orig_frame
except ValueError:
return None
@classmethod
def get_selected_frame(cls):
_gdbframe = gdb.selected_frame()
if _gdbframe:
return Frame(_gdbframe)
return None
@classmethod
def get_selected_python_frame(cls):
'''Try to obtain the Frame for the python-related code in the selected
frame, or None'''
try:
frame = cls.get_selected_frame()
except gdb.error:
# No frame: Python didn't start yet
return None
while frame:
if frame.is_python_frame():
return frame
frame = frame.older()
# Not found:
return None
@classmethod
def get_selected_bytecode_frame(cls):
'''Try to obtain the Frame for the python bytecode interpreter in the
selected GDB frame, or None'''
frame = cls.get_selected_frame()
while frame:
if frame.is_evalframeex():
return frame
frame = frame.older()
# Not found:
return None
def print_summary(self):
if self.is_evalframeex():
pyop = self.get_pyop()
if pyop:
line = pyop.get_truncated_repr(MAX_OUTPUT_LEN)
write_unicode(sys.stdout, '#%i %s\n' % (self.get_index(), line))
if not pyop.is_optimized_out():
line = pyop.current_line()
if line is not None:
sys.stdout.write(' %s\n' % line.strip())
else:
sys.stdout.write('#%i (unable to read python frame information)\n' % self.get_index())
else:
info = self.is_other_python_frame()
if info:
sys.stdout.write('#%i %s\n' % (self.get_index(), info))
else:
sys.stdout.write('#%i\n' % self.get_index())
def print_traceback(self):
if self.is_evalframeex():
pyop = self.get_pyop()
if pyop:
pyop.print_traceback()
if not pyop.is_optimized_out():
line = pyop.current_line()
if line is not None:
sys.stdout.write(' %s\n' % line.strip())
else:
sys.stdout.write(' (unable to read python frame information)\n')
else:
info = self.is_other_python_frame()
if info:
sys.stdout.write(' %s\n' % info)
else:
sys.stdout.write(' (not a python frame)\n')
class PyList(gdb.Command):
'''List the current Python source code, if any
Use
py-list START
to list at a different line number within the python source.
Use
py-list START, END
to list a specific range of lines within the python source.
'''
def __init__(self):
gdb.Command.__init__ (self,
"py-list",
gdb.COMMAND_FILES,
gdb.COMPLETE_NONE)
def invoke(self, args, from_tty):
import re
start = None
end = None
m = re.match(r'\s*(\d+)\s*', args)
if m:
start = int(m.group(0))
end = start + 10
m = re.match(r'\s*(\d+)\s*,\s*(\d+)\s*', args)
if m:
start, end = map(int, m.groups())
# py-list requires an actual PyEval_EvalFrameEx frame:
frame = Frame.get_selected_bytecode_frame()
if not frame:
print('Unable to locate gdb frame for python bytecode interpreter')
return
pyop = frame.get_pyop()
if not pyop or pyop.is_optimized_out():
print('Unable to read information on python frame')
return
filename = pyop.filename()
lineno = pyop.current_line_num()
if start is None:
start = lineno - 5
end = lineno + 5
if start<1:
start = 1
try:
f = open(os_fsencode(filename), 'r')
except IOError as err:
sys.stdout.write('Unable to open %s: %s\n'
% (filename, err))
return
with f:
all_lines = f.readlines()
# start and end are 1-based, all_lines is 0-based;
# so [start-1:end] as a python slice gives us [start, end] as a
# closed interval
for i, line in enumerate(all_lines[start-1:end]):
linestr = str(i+start)
# Highlight current line:
if i + start == lineno:
linestr = '>' + linestr
sys.stdout.write('%4s %s' % (linestr, line))
# ...and register the command:
PyList()
def move_in_stack(move_up):
'''Move up or down the stack (for the py-up/py-down command)'''
frame = Frame.get_selected_python_frame()
if not frame:
print('Unable to locate python frame')
return
while frame:
if move_up:
iter_frame = frame.older()
else:
iter_frame = frame.newer()
if not iter_frame:
break
if iter_frame.is_python_frame():
# Result:
if iter_frame.select():
iter_frame.print_summary()
return
frame = iter_frame
if move_up:
print('Unable to find an older python frame')
else:
print('Unable to find a newer python frame')
class PyUp(gdb.Command):
'Select and print the python stack frame that called this one (if any)'
def __init__(self):
gdb.Command.__init__ (self,
"py-up",
gdb.COMMAND_STACK,
gdb.COMPLETE_NONE)
def invoke(self, args, from_tty):
move_in_stack(move_up=True)
class PyDown(gdb.Command):
'Select and print the python stack frame called by this one (if any)'
def __init__(self):
gdb.Command.__init__ (self,
"py-down",
gdb.COMMAND_STACK,
gdb.COMPLETE_NONE)
def invoke(self, args, from_tty):
move_in_stack(move_up=False)
# Not all builds of gdb have gdb.Frame.select
if hasattr(gdb.Frame, 'select'):
PyUp()
PyDown()
class PyBacktraceFull(gdb.Command):
'Display the current python frame and all the frames within its call stack (if any)'
def __init__(self):
gdb.Command.__init__ (self,
"py-bt-full",
gdb.COMMAND_STACK,
gdb.COMPLETE_NONE)
def invoke(self, args, from_tty):
frame = Frame.get_selected_python_frame()
if not frame:
print('Unable to locate python frame')
return
while frame:
if frame.is_python_frame():
frame.print_summary()
frame = frame.older()
PyBacktraceFull()
class PyBacktrace(gdb.Command):
'Display the current python frame and all the frames within its call stack (if any)'
def __init__(self):
gdb.Command.__init__ (self,
"py-bt",
gdb.COMMAND_STACK,
gdb.COMPLETE_NONE)
def invoke(self, args, from_tty):
frame = Frame.get_selected_python_frame()
if not frame:
print('Unable to locate python frame')
return
sys.stdout.write('Traceback (most recent call first):\n')
while frame:
if frame.is_python_frame():
frame.print_traceback()
frame = frame.older()
PyBacktrace()
class PyPrint(gdb.Command):
'Look up the given python variable name, and print it'
def __init__(self):
gdb.Command.__init__ (self,
"py-print",
gdb.COMMAND_DATA,
gdb.COMPLETE_NONE)
def invoke(self, args, from_tty):
name = str(args)
frame = Frame.get_selected_python_frame()
if not frame:
print('Unable to locate python frame')
return
pyop_frame = frame.get_pyop()
if not pyop_frame:
print('Unable to read information on python frame')
return
pyop_var, scope = pyop_frame.get_var_by_name(name)
if pyop_var:
print('%s %r = %s'
% (scope,
name,
pyop_var.get_truncated_repr(MAX_OUTPUT_LEN)))
else:
print('%r not found' % name)
PyPrint()
class PyLocals(gdb.Command):
'Look up the given python variable name, and print it'
def __init__(self):
gdb.Command.__init__ (self,
"py-locals",
gdb.COMMAND_DATA,
gdb.COMPLETE_NONE)
def invoke(self, args, from_tty):
name = str(args)
frame = Frame.get_selected_python_frame()
if not frame:
print('Unable to locate python frame')
return
pyop_frame = frame.get_pyop()
if not pyop_frame:
print('Unable to read information on python frame')
return
for pyop_name, pyop_value in pyop_frame.iter_locals():
print('%s = %s'
% (pyop_name.proxyval(set()),
pyop_value.get_truncated_repr(MAX_OUTPUT_LEN)))
PyLocals()
| 63,797 | Python | .pyt | 1,580 | 29.753165 | 102 | 0.571886 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,381 | test_copytree.py | truenas_middleware/tests/unit/test_copytree.py | import errno
import gc
import os
import pytest
import random
import stat
from middlewared.utils.filesystem import copy
from operator import eq, ne
from unittest.mock import Mock, patch
TEST_FILE_DATASZ = 128 * 1024
TEST_XATTR_DATASZ = 1024
TEST_FILES = [
('testfile1', random.randbytes(TEST_FILE_DATASZ)),
('testfile2', random.randbytes(TEST_FILE_DATASZ)),
('canary', random.randbytes(TEST_FILE_DATASZ)),
('1234_bob', random.randbytes(TEST_FILE_DATASZ))
]
TEST_FILE_XATTRS = [
('user.filexat1', random.randbytes(TEST_XATTR_DATASZ)),
('user.filexat2', random.randbytes(TEST_XATTR_DATASZ)),
('user.filexat3', random.randbytes(TEST_XATTR_DATASZ)),
]
TEST_DIRS = [
'testdir1',
'testdir2',
'1234_larry'
]
TEST_DIR_XATTRS = [
('user.dirxat1', random.randbytes(TEST_XATTR_DATASZ)),
('user.dirxat2', random.randbytes(TEST_XATTR_DATASZ)),
('user.dirxat3', random.randbytes(TEST_XATTR_DATASZ)),
]
JENNY = 8675309
class Job:
log = []
progress = 0
def set_progress(self, progress: int, msg: str):
self.progress = progress
self.log.append(msg)
def create_test_files(target: str, symlink_target_path: str) -> None:
for filename, data in TEST_FILES:
path = os.path.join(target, filename)
with open(path, 'wb') as f:
f.write(data)
os.fchmod(f.fileno(), 0o666)
os.fchown(f.fileno(), JENNY, JENNY + 1)
f.flush()
for xat_name, xat_data in TEST_FILE_XATTRS:
os.setxattr(path, xat_name, xat_data)
# symlink target outside of dirs to be copied around
sl = f'{filename}_sl'
os.symlink(symlink_target_path, os.path.join(target, sl))
# this needs to be last op on file to avoid having other
# changes affect atime / mtime
os.utime(path, ns=(JENNY + 1, JENNY + 2))
def create_test_data(target: str, symlink_target_path) -> None:
""" generate test data in randomized temporary directory
Basic tree of files and directories including some symlinks
"""
source = os.path.join(target, 'SOURCE')
os.mkdir(source)
for xat_name, xat_data in TEST_DIR_XATTRS:
os.setxattr(source, xat_name, xat_data)
os.chown(source, JENNY + 10, JENNY + 11)
os.chmod(source, 0o777)
create_test_files(source, symlink_target_path)
for dirname in TEST_DIRS:
path = os.path.join(source, dirname)
os.mkdir(path)
os.chmod(path, 0o777)
os.chown(path, JENNY, JENNY)
for xat_name, xat_data in TEST_DIR_XATTRS:
os.setxattr(path, xat_name, xat_data)
# force atime and mtime to some value other than
# current timestamp
os.utime(path, ns=(JENNY + 3, JENNY + 4))
# symlink target outside of dirs to be copied around
sl = f'{dirname}_sl'
os.symlink(symlink_target_path, os.path.join(path, sl))
# create separate symlink dir for our test files
# _outside_ SOURCE
os.mkdir(os.path.join(target, dirname))
create_test_files(path, os.path.join(target, dirname))
os.utime(path, ns=(JENNY + 3, JENNY + 4))
os.utime(source, ns=(JENNY + 5, JENNY + 6))
@pytest.fixture(scope="function")
def directory_for_test(tmpdir):
""" generate test data in randomized temporary directory
Basic tree of files and directories including some symlinks
"""
create_test_data(tmpdir, tmpdir)
return tmpdir
def get_fd_count() -> int:
# Make sure we free up any dangling files waiting for garbage
# collection before we get authoritative count for this module
gc.collect()
return len(os.listdir('/proc/self/fd'))
@pytest.fixture(scope="module")
def fd_count() -> int:
return get_fd_count()
def validate_attributes(
src: str,
dst: str,
flags: copy.CopyFlags
) -> None:
st_src = os.lstat(src)
st_dst = os.lstat(dst)
assert st_src.st_size == st_dst.st_size
match (file_type := stat.S_IFMT(st_src.st_mode)):
case stat.S_IFREG | stat.S_IFDIR:
pass
# validate we set owner / group when requested
op = eq if flags & copy.CopyFlags.OWNER else ne
assert op(st_src.st_uid, st_dst.st_uid)
assert op(st_src.st_gid, st_dst.st_gid)
# validate we preserve file mode when requested
op = eq if flags & copy.CopyFlags.PERMISSIONS else ne
assert op(st_src.st_mode, st_dst.st_mode)
# validate we preserve timestamps when requested
op = eq if flags & copy.CopyFlags.TIMESTAMPS else ne
# checking mtime is sufficient. Atime in test runner
# is enabled and so it will get reset on source when
# we're copying data around.
assert op(st_src.st_mtime_ns, st_dst.st_mtime_ns)
case stat.S_IFLNK:
src_tgt = os.readlink(src)
dst_tgt = os.readlink(dst)
assert eq(src_tgt, dst_tgt)
return
case _:
raise ValueError(f'{src}: unexpected file type: {file_type}')
# validate we set owner / group when requested
op = eq if flags & copy.CopyFlags.OWNER else ne
assert op(st_src.st_uid, st_dst.st_uid)
assert op(st_src.st_gid, st_dst.st_gid)
# validate we preserve file mode when requested
op = eq if flags & copy.CopyFlags.PERMISSIONS else ne
assert op(st_src.st_mode, st_dst.st_mode)
# validate we preserve timestamps when requested
# NOTE: futimens on linux only allows setting atime + mtime
op = eq if flags & copy.CopyFlags.TIMESTAMPS else ne
assert op(st_src.st_mtime_ns, st_dst.st_mtime_ns)
def validate_xattrs(
src: str,
dst: str,
flags: copy.CopyFlags
) -> None:
if stat.S_ISLNK(os.lstat(src).st_mode):
# Nothing to do since we don't follow symlinks
return
xat_src = os.listxattr(src)
xat_dst = os.listxattr(dst)
if flags & copy.CopyFlags.XATTRS:
assert len(xat_src) > 0
assert len(xat_dst) > 0
assert xat_src == xat_dst
for xat_name in xat_src:
xat_data_src = os.getxattr(src, xat_name)
xat_data_dst = os.getxattr(dst, xat_name)
assert len(xat_data_src) > 0
assert xat_data_src == xat_data_dst
else:
assert len(xat_src) > 0
assert len(xat_dst) == 0
def validate_data(
src: str,
dst: str,
flags: copy.CopyFlags
) -> None:
match (file_type := stat.S_IFMT(os.lstat(src).st_mode)):
case stat.S_IFLNK:
# readlink performed in validate_attributes
return
case stat.S_IFDIR:
assert os.listdir(src) == os.listdir(dst)
return
case stat.S_IFREG:
# validation performed below
pass
case _:
raise ValueError(f'{src}: unexpected file type: {file_type}')
with open(src, 'rb') as f:
src_data = f.read()
with open(dst, 'rb') as f:
dst_data = f.read()
assert src_data == dst_data
def validate_the_things(
src: str,
dst: str,
flags: copy.CopyFlags
) -> None:
for fn in (validate_data, validate_xattrs, validate_attributes):
fn(src, dst, flags)
def validate_copy_tree(
src: str,
dst: str,
flags: copy.CopyFlags
):
with os.scandir(src) as it:
for f in it:
if f.name == 'CHILD':
# skip validation of bind mountpoint
continue
new_src = os.path.join(src, f.name)
new_dst = os.path.join(dst, f.name)
validate_the_things(new_src, new_dst, flags)
if f.is_dir() and not f.is_symlink():
validate_copy_tree(new_src, new_dst, flags)
validate_the_things(src, dst, flags)
def test__copytree_default(directory_for_test, fd_count):
""" test basic behavior of copytree """
src = os.path.join(directory_for_test, 'SOURCE')
dst = os.path.join(directory_for_test, 'DEST')
config = copy.CopyTreeConfig()
assert config.flags == copy.DEF_CP_FLAGS
stats = copy.copytree(src, dst, config)
validate_copy_tree(src, dst, config.flags)
assert stats.files != 0
assert stats.dirs != 0
assert stats.symlinks != 0
assert get_fd_count() == fd_count
@pytest.mark.parametrize('is_ctldir', [True, False])
def test__copytree_exclude_ctldir(directory_for_test, fd_count, is_ctldir):
""" test that we do not recurse into ZFS ctldir """
src = os.path.join(directory_for_test, 'SOURCE')
dst = os.path.join(directory_for_test, 'DEST')
snapdir = os.path.join(src, '.zfs', 'snapshot', 'now')
os.makedirs(snapdir)
with open(os.path.join(snapdir, 'canary'), 'w'):
pass
if is_ctldir:
# Mock over method to determine whether path is in actual .zfs
with patch(
'middlewared.utils.filesystem.copy.path_in_ctldir', Mock(
return_value=True
)
):
copy.copytree(src, dst, copy.CopyTreeConfig())
# We should automatically exclude a real .zfs directory
assert not os.path.exists(os.path.join(dst, '.zfs'))
else:
# This .zfs directory does not have special inode number
# and so we know we can copy it.
copy.copytree(src, dst, copy.CopyTreeConfig())
assert os.path.exists(os.path.join(dst, '.zfs'))
@pytest.mark.parametrize('existok', [True, False])
def test__copytree_existok(directory_for_test, fd_count, existok):
""" test behavior of `exist_ok` configuration option """
src = os.path.join(directory_for_test, 'SOURCE')
dst = os.path.join(directory_for_test, 'DEST')
config = copy.CopyTreeConfig(exist_ok=existok)
os.mkdir(dst)
if existok:
copy.copytree(src, dst, config)
validate_copy_tree(src, dst, config.flags)
else:
with pytest.raises(FileExistsError):
copy.copytree(src, dst, config)
assert get_fd_count() == fd_count
@pytest.mark.parametrize('flag', [
copy.CopyFlags.XATTRS,
copy.CopyFlags.PERMISSIONS,
copy.CopyFlags.TIMESTAMPS,
copy.CopyFlags.OWNER
])
def test__copytree_flags(directory_for_test, fd_count, flag):
"""
copytree allows user to specify what types of metadata to
preserve on copy similar to robocopy on Windows. This tests
that setting individual flags results in copy of _only_
the specified metadata.
"""
src = os.path.join(directory_for_test, 'SOURCE')
dst = os.path.join(directory_for_test, 'DEST')
copy.copytree(src, dst, copy.CopyTreeConfig(flags=flag))
validate_copy_tree(src, dst, flag)
assert get_fd_count() == fd_count
def test__force_userspace_copy(directory_for_test, fd_count):
""" force use of shutil.copyfileobj wrapper instead of copy_file_range """
src = os.path.join(directory_for_test, 'SOURCE')
dst = os.path.join(directory_for_test, 'DEST')
flags = copy.DEF_CP_FLAGS
copy.copytree(src, dst, copy.CopyTreeConfig(flags=flags, op=copy.CopyTreeOp.USERSPACE))
validate_copy_tree(src, dst, flags)
assert get_fd_count() == fd_count
def test__copytree_into_itself_simple(directory_for_test, fd_count):
""" perform a basic copy of a tree into a subdirectory of itself.
This simulates case where user has mistakenly set homedir to FOO
and performs an update of homedir to switch it to FOO/username.
If logic breaks then we'll end up with this test failing due to
infinite recursion.
"""
src = os.path.join(directory_for_test, 'SOURCE')
dst = os.path.join(directory_for_test, 'SOURCE', 'DEST')
copy.copytree(src, dst, copy.CopyTreeConfig())
assert not os.path.exists(os.path.join(directory_for_test, 'SOURCE', 'DEST', 'DEST'))
assert get_fd_count() == fd_count
def test__copytree_into_itself_complex(directory_for_test, fd_count):
""" check recursion guard against deeper nested target """
src = os.path.join(directory_for_test, 'SOURCE')
dst = os.path.join(directory_for_test, 'SOURCE', 'FOO', 'BAR', 'DEST')
os.makedirs(os.path.join(directory_for_test, 'SOURCE', 'FOO', 'BAR'))
copy.copytree(src, dst, copy.CopyTreeConfig())
# we expect to copy everything up to the point where we'd start infinite
# recursion
assert os.path.exists(os.path.join(dst, 'FOO', 'BAR'))
# but not quite get there
assert not os.path.exists(os.path.join(dst, 'FOO', 'BAR', 'DEST'))
assert get_fd_count() == fd_count
def test__copytree_job_log(directory_for_test, fd_count):
""" check that providing job object causes progress to be written properly """
src = os.path.join(directory_for_test, 'SOURCE')
dst = os.path.join(directory_for_test, 'DEST')
job = Job()
config = copy.CopyTreeConfig(job=job, job_msg_inc=1)
copy.copytree(src, dst, config)
assert job.progress == 100
assert len(job.log) > 0
last = job.log[-1]
assert last.startswith('Successfully copied')
def test__copytree_job_log_prefix(directory_for_test, fd_count):
""" check that log message prefix gets written as expected """
src = os.path.join(directory_for_test, 'SOURCE')
dst = os.path.join(directory_for_test, 'DEST')
job = Job()
config = copy.CopyTreeConfig(job=job, job_msg_inc=1, job_msg_prefix='Canary: ')
copy.copytree(src, dst, config)
assert job.progress == 100
assert len(job.log) > 0
last = job.log[-1]
assert last.startswith('Canary: Successfully copied')
def test__clone_file_somewhat_large(tmpdir):
src_fd = os.open(os.path.join(tmpdir, 'test_large_clone_src'), os.O_CREAT | os.O_RDWR)
dst_fd = os.open(os.path.join(tmpdir, 'test_large_clone_dst'), os.O_CREAT | os.O_RDWR)
chunk_sz = 1024 ** 2
try:
for i in range(0, 128):
payload = random.randbytes(chunk_sz)
os.pwrite(src_fd, payload, i * chunk_sz)
copy.clone_file(src_fd, dst_fd)
for i in range(0, 128):
src = os.pread(src_fd, chunk_sz, i * chunk_sz)
dst = os.pread(dst_fd, chunk_sz, i * chunk_sz)
assert src == dst
finally:
os.close(src_fd)
os.close(dst_fd)
os.unlink(os.path.join(tmpdir, 'test_large_clone_src'))
os.unlink(os.path.join(tmpdir, 'test_large_clone_dst'))
def test__copy_default_fallthrough(tmpdir):
""" verify we can fallthrough from CLONE to USERSPACE """
src_fd = os.open(os.path.join(tmpdir, 'test_default_fallthrough_src'), os.O_CREAT | os.O_RDWR)
dst_fd = os.open(os.path.join(tmpdir, 'test_default_fallthrough_dst'), os.O_CREAT | os.O_RDWR)
chunk_sz = 1024 ** 2
try:
for i in range(0, 128):
payload = random.randbytes(chunk_sz)
os.pwrite(src_fd, payload, i * chunk_sz)
# return value of 0 triggers fallthrough code
with patch('os.sendfile', Mock(return_value=0)):
# raising EXDEV triggers clone fallthrough
with patch('middlewared.utils.filesystem.copy.clone_file', Mock(side_effect=OSError(errno.EXDEV, 'MOCK'))):
copy.clone_or_copy_file(src_fd, dst_fd)
for i in range(0, 128):
src = os.pread(src_fd, chunk_sz, i * chunk_sz)
dst = os.pread(dst_fd, chunk_sz, i * chunk_sz)
assert src == dst
finally:
os.close(src_fd)
os.close(dst_fd)
os.unlink(os.path.join(tmpdir, 'test_default_fallthrough_src'))
os.unlink(os.path.join(tmpdir, 'test_default_fallthrough_dst'))
def test__copy_sendfile_fallthrough(tmpdir):
""" verify that fallthrough to userspace copy from copy_sendfile works """
src_fd = os.open(os.path.join(tmpdir, 'test_sendfile_fallthrough_src'), os.O_CREAT | os.O_RDWR)
dst_fd = os.open(os.path.join(tmpdir, 'test_sendfile_fallthrough_dst'), os.O_CREAT | os.O_RDWR)
chunk_sz = 1024 ** 2
try:
for i in range(0, 128):
payload = random.randbytes(chunk_sz)
os.pwrite(src_fd, payload, i * chunk_sz)
# return value of 0 triggers fallthrough code
with patch('os.sendfile', Mock(return_value=0)):
copy.copy_sendfile(src_fd, dst_fd)
for i in range(0, 128):
src = os.pread(src_fd, chunk_sz, i * chunk_sz)
dst = os.pread(dst_fd, chunk_sz, i * chunk_sz)
assert src == dst
finally:
os.close(src_fd)
os.close(dst_fd)
os.unlink(os.path.join(tmpdir, 'test_sendfile_fallthrough_src'))
os.unlink(os.path.join(tmpdir, 'test_sendfile_fallthrough_dst'))
def test__copy_sendfile(tmpdir):
""" verify that copy.sendfile preserves file data and does not by default fallthrogh to userspace """
src_fd = os.open(os.path.join(tmpdir, 'test_large_sendfile_src'), os.O_CREAT | os.O_RDWR)
dst_fd = os.open(os.path.join(tmpdir, 'test_large_sendfile_dst'), os.O_CREAT | os.O_RDWR)
chunk_sz = 1024 ** 2
try:
for i in range(0, 128):
payload = random.randbytes(chunk_sz)
os.pwrite(src_fd, payload, i * chunk_sz)
with patch(
'middlewared.utils.filesystem.copy.copy_file_userspace', Mock(
side_effect=Exception('Unexpected fallthrough to copy_userspace')
)
):
copy.copy_sendfile(src_fd, dst_fd)
for i in range(0, 128):
src = os.pread(src_fd, chunk_sz, i * chunk_sz)
dst = os.pread(dst_fd, chunk_sz, i * chunk_sz)
assert src == dst
finally:
os.close(src_fd)
os.close(dst_fd)
os.unlink(os.path.join(tmpdir, 'test_large_sendfile_src'))
os.unlink(os.path.join(tmpdir, 'test_large_sendfile_dst'))
| 17,721 | Python | .pyt | 417 | 35.266187 | 119 | 0.642791 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,382 | test_port_attachments.py | truenas_middleware/src/middlewared/middlewared/pytest/unit/plugins/test_port_attachments.py | import contextlib
import pytest
from unittest.mock import patch
from middlewared.plugins.ports.ports import PortService, ValidationErrors
from middlewared.pytest.unit.middleware import Middleware
PORTS_IN_USE = [
{
'namespace': 'snmp',
'title': 'SNMP Service',
'ports': [
[
'0.0.0.0',
160
],
[
'0.0.0.0',
161
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
160
],
[
'0.0.0.0',
161
]
]
}
]
},
{
'namespace': 'ssh',
'title': 'SSH Service',
'ports': [
[
'0.0.0.0',
22
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
22
]
]
}
]
},
{
'namespace': 'tftp',
'title': 'TFTP Service',
'ports': [
[
'0.0.0.0',
69
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
69
]
]
}
]
},
{
'namespace': 'kmip',
'title': 'KMIP Service',
'ports': [
[
'0.0.0.0',
5696
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
5696
]
]
}
]
},
{
'namespace': 'rsyncd',
'title': 'Rsyncd Service',
'ports': [
[
'0.0.0.0',
11000
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
11000
]
]
}
]
},
{
'namespace': 'webdav',
'title': 'Webdav Service',
'ports': [
[
'0.0.0.0',
10258
],
[
'0.0.0.0',
14658
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
10258
],
[
'0.0.0.0',
14658
]
]
}
]
},
{
'namespace': 'smb',
'title': 'SMB Service',
'ports': [
[
'0.0.0.0',
137
],
[
'0.0.0.0',
138
],
[
'0.0.0.0',
139
],
[
'0.0.0.0',
445
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
137
],
[
'0.0.0.0',
138
],
[
'0.0.0.0',
139
],
[
'0.0.0.0',
445
]
]
}
]
},
{
'namespace': 's3',
'title': 'S3 Service',
'ports': [
[
'192.168.0.70',
8703
],
[
'192.168.0.70',
9010
],
[
'2001:db8:3333:4444:5555:6666:7777:8888',
8704
]
],
'port_details': [
{
'description': None,
'ports': [
[
'192.168.0.70',
8703
],
[
'192.168.0.70',
9010
],
[
'2001:db8:3333:4444:5555:6666:7777:8888',
8704
]
]
}
]
},
{
'namespace': 'ftp',
'title': 'FTP Service',
'ports': [
[
'0.0.0.0',
3730
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
3730
]
]
}
]
},
{
'namespace': 'openvpn.server',
'title': 'Openvpn Server Service',
'ports': [
[
'0.0.0.0',
1194
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
1194
]
]
}
]
},
{
'namespace': 'system.general',
'title': 'WebUI Service',
'ports': [
[
'0.0.0.0',
80
],
[
'0.0.0.0',
443
],
[
'::',
8080
],
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
80
],
[
'0.0.0.0',
443
],
[
'::',
8080
],
]
}
]
},
{
'namespace': 'reporting',
'title': 'Reporting Service',
'ports': [
[
'0.0.0.0',
2003
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
2003
]
]
}
]
},
{
'namespace': 'iscsi.global',
'title': 'iSCSI Service',
'ports': [
[
'0.0.0.0',
3260
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
3260
]
]
}
]
},
{
'namespace': 'nfs',
'title': 'NFS Service',
'ports': [
[
'0.0.0.0',
2049
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
2049
]
]
}
]
},
{
'namespace': 'gluster.fuse',
'title': 'Gluster Service',
'ports': [
[
'0.0.0.0',
24007
],
[
'0.0.0.0',
24008
],
[
'::',
24008
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
24007
],
[
'0.0.0.0',
24008
],
[
'::',
24008
]
]
}
]
},
{
'title': 'System',
'ports': [
[
'0.0.0.0',
67
],
[
'0.0.0.0',
123
],
[
'0.0.0.0',
3702
],
[
'0.0.0.0',
5353
],
[
'0.0.0.0',
6000
],
[
'::',
68
]
],
'port_details': [
{
'description': None,
'ports': [
[
'0.0.0.0',
67
],
[
'::',
68
],
[
'0.0.0.0',
123
],
[
'0.0.0.0',
3702
],
[
'0.0.0.0',
5353
],
[
'0.0.0.0',
6000
]
]
}
],
'namespace': 'system'
}
]
@contextlib.contextmanager
def get_port_service():
with patch('middlewared.plugins.ports.ports.PortService.get_in_use') as get_in_use_port:
get_in_use_port.return_value = PORTS_IN_USE
yield PortService(Middleware())
@pytest.mark.parametrize('port,bindip,whitelist_namespace', [
(67, '0.0.0.0', 'system'),
(67, '192.168.0.12', 'system'),
(24007, '0.0.0.0', 'gluster.fuse'),
(24007, '192.168.0.12', 'gluster.fuse'),
(68, '::', 'system'),
(68, '2001:db8:3333:4444:5555:6666:7777:8888', 'system'),
(24008, '::', 'gluster.fuse'),
(24008, '2001:db8:3333:4444:5555:6666:7777:8888', 'gluster.fuse'),
])
@pytest.mark.asyncio
async def test_port_validate_whitelist_namespace_logic(port, bindip, whitelist_namespace):
with get_port_service() as port_service:
with pytest.raises(ValidationErrors):
await port_service.validate_port('test', port, bindip, raise_error=True)
assert (await port_service.validate_port('test', port, bindip, whitelist_namespace)).errors == []
@pytest.mark.parametrize('port,bindip,should_work', [
(80, '0.0.0.0', False),
(81, '0.0.0.0', True),
(8703, '0.0.0.0', False),
(8703, '192.168.0.70', False),
(8703, '192.168.0.71', True),
(9010, '0.0.0.0', False),
(9010, '192.168.0.70', False),
(9010, '192.168.0.71', True),
(80, '::', True),
(8080, '::', False),
(8081, '::', True),
(8703, '::', True),
(8704, '::', False),
(8704, '2001:db8:3333:4444:5555:6666:7777:8888', False),
(8704, '2001:db8:3333:4444:5555:6666:7777:8889', True),
])
@pytest.mark.asyncio
async def test_port_validation_logic(port, bindip, should_work):
with get_port_service() as port_service:
if should_work:
assert (await port_service.validate_port('test', port, bindip, raise_error=False)).errors == []
else:
with pytest.raises(ValidationErrors):
await port_service.validate_port('test', port, bindip, raise_error=True)
| 12,252 | Python | .tac | 517 | 9.408124 | 107 | 0.259553 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,383 | test_attachment_delegate_is_child_path.py | truenas_middleware/src/middlewared/middlewared/pytest/unit/plugins/test_attachment_delegate_is_child_path.py | import pytest
from middlewared.plugins.smb import SMBFSAttachmentDelegate
from middlewared.pytest.unit.middleware import Middleware
@pytest.mark.parametrize('resource, path, check_parent, exact_match, is_child, expected_output', (
({'path_local': '/mnt/tank/test'}, '/mnt/tank', False, False, True, True),
({'path_local': '/mnt/tank/test'}, '/mnt/tank', False, True, True, False),
({'path_local': '/mnt/tank'}, '/mnt/tank', False, False, True, True),
({'path_local': '/mnt/test'}, '/mnt/tank', True, False, False, False),
({'path_local': '/mnt/tank/test'}, '/mnt/tank', True, False, True, True),
))
@pytest.mark.asyncio
async def test_attachment_is_child(resource, path, check_parent, exact_match, is_child, expected_output):
m = Middleware()
m['filesystem.is_child'] = lambda *arg: is_child
smb_attachment = SMBFSAttachmentDelegate(m)
assert (await smb_attachment.is_child_of_path(resource, path, check_parent, exact_match)) == expected_output
| 984 | Python | .tac | 16 | 58.0625 | 112 | 0.699482 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,384 | test_attachments.py | truenas_middleware/src/middlewared/middlewared/pytest/unit/plugins/vm/test_attachments.py | import pytest
from middlewared.plugins.vm.attachments import determine_recursive_search
@pytest.mark.parametrize('recursive,device,child_datasets,result', [
(True, {'attributes': {'path': '/mnt/tank/somefile'}, 'dtype': 'CDROM'}, ['tank/child'], True),
(False, {'attributes': {'path': '/dev/zvol/tank/somezvol'}, 'dtype': 'DISK'}, ['tank/child'], False),
(False, {'attributes': {'path': '/mnt/tank/child/file'}, 'dtype': 'RAW'}, ['tank/child'], False),
(False, {'attributes': {'path': '/mnt/tank/file'}, 'dtype': 'RAW'}, ['tank/child'], True),
])
@pytest.mark.asyncio
async def test_determining_recursive_search(recursive, device, child_datasets, result):
assert await determine_recursive_search(recursive, device, child_datasets) is result
| 764 | Python | .tac | 11 | 66.363636 | 105 | 0.689333 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,385 | fs_attachment_delegate.py | truenas_middleware/src/middlewared/middlewared/plugins/nfs_/fs_attachment_delegate.py | from middlewared.common.attachment import LockableFSAttachmentDelegate
from middlewared.plugins.nfs import SharingNFSService
class NFSFSAttachmentDelegate(LockableFSAttachmentDelegate):
name = 'nfs'
title = 'NFS Share'
service = 'nfs'
service_class = SharingNFSService
resource_name = 'path'
async def restart_reload_services(self, attachments):
await self._service_change('nfs', 'reload')
async def setup(middleware):
await middleware.call('pool.dataset.register_attachment_delegate', NFSFSAttachmentDelegate(middleware))
| 565 | Python | .tac | 12 | 42.583333 | 107 | 0.787934 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,386 | port_attachments.py | truenas_middleware/src/middlewared/middlewared/plugins/nfs_/port_attachments.py | from middlewared.common.ports import ServicePortDelegate
class NFSServicePortDelegate(ServicePortDelegate):
bind_address_field = 'bindip'
name = 'nfs'
namespace = 'nfs'
port_fields = ['mountd_port', 'rpcstatd_port', 'rpclockd_port']
title = 'NFS Service'
def bind_address(self, config):
if config[self.bind_address_field] and '0.0.0.0' not in config[self.bind_address_field]:
return config[self.bind_address_field]
else:
return ['0.0.0.0']
async def get_ports_internal(self):
await self.basic_checks()
config = await self.config()
ports = [('0.0.0.0', 2049)]
bind_addresses = self.bind_address(config)
for k in filter(lambda k: config.get(k), self.port_fields):
for bindip in bind_addresses:
ports.append((bindip, config[k]))
return ports
async def setup(middleware):
await middleware.call('port.register_attachment_delegate', NFSServicePortDelegate(middleware))
| 1,019 | Python | .tac | 23 | 36.521739 | 98 | 0.662955 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,387 | attachments.py | truenas_middleware/src/middlewared/middlewared/plugins/ftp_/attachments.py | from middlewared.common.ports import ServicePortDelegate
class FTPServicePortDelegate(ServicePortDelegate):
name = 'FTP'
namespace = 'ftp'
port_fields = ['port']
title = 'FTP Service'
async def setup(middleware):
await middleware.call('port.register_attachment_delegate', FTPServicePortDelegate(middleware))
| 333 | Python | .tac | 8 | 37.5 | 98 | 0.778125 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,388 | cert_attachment.py | truenas_middleware/src/middlewared/middlewared/plugins/ftp_/cert_attachment.py | from middlewared.common.attachment.certificate import CertificateServiceAttachmentDelegate
class FTPCertificateAttachment(CertificateServiceAttachmentDelegate):
CERT_FIELD = 'ssltls_certificate'
HUMAN_NAME = 'FTP Service'
SERVICE = 'ftp'
async def setup(middleware):
await middleware.call('certificate.register_attachment_delegate', FTPCertificateAttachment(middleware))
| 392 | Python | .tac | 7 | 52 | 107 | 0.834211 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,389 | fs_attachment_delegate.py | truenas_middleware/src/middlewared/middlewared/plugins/iscsi_/fs_attachment_delegate.py | from middlewared.common.attachment import LockableFSAttachmentDelegate
from .extents import iSCSITargetExtentService
class ISCSIFSAttachmentDelegate(LockableFSAttachmentDelegate):
name = 'iscsi'
title = 'iSCSI Extent'
service = 'iscsitarget'
service_class = iSCSITargetExtentService
async def get_query_filters(self, enabled, options=None):
return [['type', '=', 'DISK']] + (await super().get_query_filters(enabled, options))
async def delete(self, attachments):
orphan_targets_ids = set()
for attachment in attachments:
for te in await self.middleware.call('iscsi.targetextent.query', [['extent', '=', attachment['id']]]):
orphan_targets_ids.add(te['target'])
await self.middleware.call('datastore.delete', 'services.iscsitargettoextent', te['id'])
await self.middleware.call('datastore.delete', 'services.iscsitargetextent', attachment['id'])
await self.remove_alert(attachment)
for te in await self.middleware.call('iscsi.targetextent.query', [['target', 'in', orphan_targets_ids]]):
orphan_targets_ids.discard(te['target'])
for target_id in orphan_targets_ids:
await self.middleware.call('iscsi.target.delete', target_id, True)
await self._service_change('iscsitarget', 'reload')
async def restart_reload_services(self, attachments):
await self._service_change('iscsitarget', 'reload')
async def stop(self, attachments):
await self.restart_reload_services(attachments)
async def setup(middleware):
await middleware.call('pool.dataset.register_attachment_delegate', ISCSIFSAttachmentDelegate(middleware))
| 1,712 | Python | .tac | 28 | 52.857143 | 114 | 0.704545 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,390 | port_attachments.py | truenas_middleware/src/middlewared/middlewared/plugins/iscsi_/port_attachments.py | from middlewared.common.ports import ServicePortDelegate
class ISCSIGlobalServicePortDelegate(ServicePortDelegate):
name = 'iSCSI'
namespace = 'iscsi.global'
port_fields = ['listen_port']
title = 'iSCSI Service'
async def setup(middleware):
await middleware.call('port.register_attachment_delegate', ISCSIGlobalServicePortDelegate(middleware))
| 369 | Python | .tac | 8 | 42 | 106 | 0.794944 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,391 | attachments.py | truenas_middleware/src/middlewared/middlewared/plugins/reporting/attachments.py | from middlewared.common.ports import ServicePortDelegate
from .netdata.utils import NETDATA_PORT
class ReportingServicePortDelegate(ServicePortDelegate):
name = 'reporting'
namespace = 'reporting'
title = 'Reporting Service'
async def get_ports_bound_on_wildcards(self):
return [NETDATA_PORT]
async def setup(middleware):
await middleware.call('port.register_attachment_delegate', ReportingServicePortDelegate(middleware))
| 458 | Python | .tac | 10 | 41.3 | 104 | 0.795918 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,392 | attachments.py | truenas_middleware/src/middlewared/middlewared/plugins/system_general/attachments.py | from middlewared.common.ports import ServicePortDelegate
class SystemGeneralServicePortDelegate(ServicePortDelegate):
bind_address_field = 'ui_address'
name = 'webui'
namespace = 'system.general'
port_fields = ['ui_port', 'ui_httpsport']
title = 'WebUI Service'
def bind_address(self, config):
addresses = []
for wildcard_ip, address_field in (
('0.0.0.0', 'ui_address'),
('::', 'ui_v6address'),
):
if config[address_field] and wildcard_ip not in config[address_field]:
addresses.extend(config[address_field])
else:
addresses.append(wildcard_ip)
return addresses
async def get_ports_internal(self):
await self.basic_checks()
config = await self.config()
ports = []
bind_addresses = self.bind_address(config)
for k in filter(lambda k: config.get(k), self.port_fields):
for bindip in bind_addresses:
ports.append((bindip, config[k]))
return ports
async def setup(middleware):
await middleware.call('port.register_attachment_delegate', SystemGeneralServicePortDelegate(middleware))
| 1,208 | Python | .tac | 29 | 32.758621 | 108 | 0.639316 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,393 | attachments.py | truenas_middleware/src/middlewared/middlewared/plugins/smb_/attachments.py | from middlewared.common.ports import ServicePortDelegate
class SMBServicePortDelegate(ServicePortDelegate):
name = 'smb'
namespace = 'smb'
title = 'SMB Service'
async def get_ports_bound_on_wildcards(self):
return [137, 138, 139, 445]
async def setup(middleware):
await middleware.call('port.register_attachment_delegate', SMBServicePortDelegate(middleware))
| 393 | Python | .tac | 9 | 38.888889 | 98 | 0.76455 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,394 | attachments.py | truenas_middleware/src/middlewared/middlewared/plugins/docker/attachments.py | import os
from middlewared.common.attachment import FSAttachmentDelegate
class DockerFSAttachmentDelegate(FSAttachmentDelegate):
name = 'docker'
title = 'Docker'
service = 'docker'
async def query(self, path, enabled, options=None):
results = []
k8s_config = await self.middleware.call('docker.config')
if not k8s_config['pool']:
return results
query_dataset = os.path.relpath(path, '/mnt')
if query_dataset in (k8s_config['dataset'], k8s_config['pool']) or query_dataset.startswith(
f'{k8s_config["dataset"]}/'
):
results.append({'id': k8s_config['pool']})
return results
async def get_attachment_name(self, attachment):
return attachment['id']
async def delete(self, attachments):
if attachments:
await (await self.middleware.call('docker.update', {'pool': None})).wait(raise_error=True)
async def toggle(self, attachments, enabled):
await getattr(self, 'start' if enabled else 'stop')(attachments)
async def stop(self, attachments):
if not attachments:
return
try:
await self.middleware.call('service.stop', self.service)
except Exception as e:
self.middleware.logger.error('Failed to stop docker: %s', e)
async def start(self, attachments):
if not attachments:
return
try:
await self.middleware.call('docker.state.start_service', True)
except Exception:
self.middleware.logger.error('Failed to start docker')
async def setup(middleware):
await middleware.call('pool.dataset.register_attachment_delegate', DockerFSAttachmentDelegate(middleware))
| 1,751 | Python | .tac | 40 | 35.225 | 110 | 0.65822 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,395 | cert_attachments.py | truenas_middleware/src/middlewared/middlewared/plugins/apps/cert_attachments.py | from middlewared.common.attachment.certificate import CertificateCRUDServiceAttachmentDelegate
from middlewared.service import Service
from .ix_apps.metadata import get_collective_config
class AppCertificateAttachmentDelegate(CertificateCRUDServiceAttachmentDelegate):
HUMAN_NAME = 'Applications'
NAMESPACE = 'app'
async def consuming_cert_human_output(self, cert_id):
attachments = await self.attachments(cert_id)
return f'{", ".join(app["id"] for app in attachments)!r} {self.HUMAN_NAME}' if attachments else None
async def attachments(self, cert_id):
config = await self.middleware.run_in_thread(get_collective_config)
apps_consuming_cert = [
app_name for app_name, app_config in config.items() if cert_id in app_config.get('ix_certificates', {})
]
return await self.middleware.call(f'{self.NAMESPACE}.query', [['id', 'in', apps_consuming_cert]])
async def redeploy(self, cert_id):
apps = [r['name'] for r in await self.attachments(cert_id)]
bulk_job = await self.middleware.call('core.bulk', 'app.redeploy', [[app] for app in apps])
for index, status in enumerate(await bulk_job.wait()):
if status['error']:
self.middleware.logger.error(
'Failed to redeploy %r app: %s', apps[index], status['error']
)
class AppCertificateService(Service):
class Config:
namespace = 'app.certificate'
private = True
async def get_apps_consuming_outdated_certs(self, filters=None):
apps_having_outdated_certs = []
filters = filters or []
certs = {c['id']: c for c in await self.middleware.call('certificate.query')}
config = await self.middleware.run_in_thread(get_collective_config)
apps = {app['name']: app for app in await self.middleware.call('app.query', filters)}
for app_name, app_config in config.items():
if app_name not in apps or not app_config.get('ix_certificates'):
continue
if any(
cert['certificate'] != certs[cert_id]['certificate']
for cert_id, cert in app_config['ix_certificates'].items()
if cert_id in certs
):
apps_having_outdated_certs.append(app_name)
return apps_having_outdated_certs
async def redeploy_apps_consuming_outdated_certs(self):
return await self.middleware.call(
'core.bulk', 'app.redeploy', [[r] for r in await self.get_apps_consuming_outdated_certs()]
)
async def setup(middleware):
await middleware.call(
'certificate.register_attachment_delegate', AppCertificateAttachmentDelegate(middleware)
)
| 2,751 | Python | .tac | 51 | 44.54902 | 115 | 0.660581 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,396 | fs_attachments.py | truenas_middleware/src/middlewared/middlewared/plugins/apps/fs_attachments.py | from middlewared.common.attachment import FSAttachmentDelegate
class AppFSAttachmentDelegate(FSAttachmentDelegate):
name = 'apps'
title = 'Apps'
async def query(self, path, enabled, options=None):
apps_attached = []
for app in await self.middleware.call('app.query'):
# We don't want to consider those apps which fit in the following criteria:
# - app has no volumes
# - app is stopped and we are looking for enabled apps
# - app is not stopped and we are looking for disabled apps
if not (skip_app := not app['active_workloads']['volumes']):
if enabled:
skip_app |= app['state'] == 'STOPPED'
else:
skip_app |= app['state'] != 'STOPPED'
if skip_app:
continue
if await self.middleware.call(
'filesystem.is_child', [volume['source'] for volume in app['active_workloads']['volumes']], path
):
apps_attached.append({
'id': app['name'],
'name': app['name'],
})
return apps_attached
async def delete(self, attachments):
for attachment in attachments:
try:
await (await self.middleware.call('app.stop', attachment['id'])).wait(raise_error=True)
except Exception:
self.middleware.logger.error('Unable to stop %r app', attachment['id'], exc_info=True)
async def toggle(self, attachments, enabled):
# if enabled is true - we are going to ignore that as we don't want to scale up releases
# automatically when a path becomes available
for attachment in ([] if enabled else attachments):
action = 'start' if enabled else 'stop'
try:
await (await self.middleware.call(f'app.{action}', attachment['id'])).wait(raise_error=True)
except Exception:
self.middleware.logger.error('Unable to %s %r app', action, attachment['id'], exc_info=True)
async def stop(self, attachments):
await self.toggle(attachments, False)
async def start(self, attachments):
await self.toggle(attachments, True)
async def setup(middleware):
middleware.create_task(
middleware.call('pool.dataset.register_attachment_delegate', AppFSAttachmentDelegate(middleware))
)
| 2,448 | Python | .tac | 49 | 38.265306 | 112 | 0.603687 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,397 | port_attachments.py | truenas_middleware/src/middlewared/middlewared/plugins/apps/port_attachments.py | from middlewared.common.ports import PortDelegate
class AppPortDelegate(PortDelegate):
name = 'applications'
namespace = 'app'
title = 'Applications'
async def get_ports(self):
ports = []
for app in filter(
lambda a: a['active_workloads']['used_ports'],
await self.middleware.call('app.query')
):
app_ports = []
for port_entry in app['active_workloads']['used_ports']:
for host_port in port_entry['host_ports']:
app_ports.append(('0.0.0.0', host_port['host_port']))
ports.append({
'description': f'{app["id"]!r} application',
'ports': app_ports,
})
return ports
async def setup(middleware):
await middleware.call('port.register_attachment_delegate', AppPortDelegate(middleware))
| 879 | Python | .tac | 22 | 29.863636 | 91 | 0.586572 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,398 | cert_attachments.py | truenas_middleware/src/middlewared/middlewared/plugins/system/cert_attachments.py | from middlewared.common.attachment.certificate import CertificateServiceAttachmentDelegate
class SystemGeneralCertificateAttachmentDelegate(CertificateServiceAttachmentDelegate):
CERT_FIELD = 'ui_certificate'
HUMAN_NAME = 'UI Service'
NAMESPACE = 'system.general'
SERVICE = 'http'
class SystemAdvancedCertificateAttachmentDelegate(CertificateServiceAttachmentDelegate):
CERT_FIELD = 'syslog_tls_certificate'
HUMAN_NAME = 'Syslog Service'
NAMESPACE = 'system.advanced'
SERVICE = 'syslogd'
async def setup(middleware):
await middleware.call(
'certificate.register_attachment_delegate', SystemGeneralCertificateAttachmentDelegate(middleware)
)
await middleware.call(
'certificate.register_attachment_delegate', SystemAdvancedCertificateAttachmentDelegate(middleware)
)
| 838 | Python | .tac | 18 | 41.555556 | 107 | 0.802956 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |
25,399 | attach_disk.py | truenas_middleware/src/middlewared/middlewared/plugins/pool_/attach_disk.py | import asyncio
from middlewared.schema import accepts, Bool, Dict, Int, returns, Str
from middlewared.service import job, Service, ValidationErrors
class PoolService(Service):
@accepts(
Int('oid'),
Dict(
'pool_attach',
Str('target_vdev', required=True),
Str('new_disk', required=True),
Bool('allow_duplicate_serials', default=False),
)
)
@returns()
@job(lock=lambda args: f'pool_attach_{args[0]}')
async def attach(self, job, oid, options):
"""
`target_vdev` is the GUID of the vdev where the disk needs to be attached. In case of STRIPED vdev, this
is the STRIPED disk GUID which will be converted to mirror. If `target_vdev` is mirror, it will be converted
into a n-way mirror.
"""
pool = await self.middleware.call('pool.get_instance', oid)
verrors = ValidationErrors()
topology = pool['topology']
topology_type = vdev = None
for i in topology:
for v in topology[i]:
if v['guid'] == options['target_vdev']:
topology_type = i
vdev = v
break
if topology_type:
break
else:
verrors.add('pool_attach.target_vdev', 'Unable to locate VDEV')
verrors.check()
if topology_type in ('cache', 'spares'):
verrors.add('pool_attach.target_vdev', f'Attaching disks to {topology_type} not allowed.')
elif topology_type == 'data':
# We would like to make sure here that we don't have inconsistent vdev types across data
if vdev['type'] not in ('DISK', 'MIRROR', 'RAIDZ1', 'RAIDZ2', 'RAIDZ3'):
verrors.add('pool_attach.target_vdev', f'Attaching disk to {vdev["type"]} vdev is not allowed.')
# Let's validate new disk now
verrors.add_child(
'pool_attach',
await self.middleware.call('disk.check_disks_availability', [options['new_disk']],
options['allow_duplicate_serials']),
)
verrors.check()
job.set_progress(3, 'Completed validation')
guid = vdev['guid'] if vdev['type'] in ['DISK', 'RAIDZ1', 'RAIDZ2', 'RAIDZ3'] else vdev['children'][0]['guid']
disks = {options['new_disk']: {'vdev': []}}
job.set_progress(5, 'Formatting disks')
await self.middleware.call('pool.format_disks', job, disks, 5, 20)
job.set_progress(22, 'Extending pool')
devname = disks[options['new_disk']]['vdev'][0]
extend_job = await self.middleware.call('zfs.pool.extend', pool['name'], None, [
{'target': guid, 'type': 'DISK', 'path': devname}
])
await extend_job.wait(raise_error=True)
if vdev['type'] in ('RAIDZ1', 'RAIDZ2', 'RAIDZ3'):
while True:
expand = await self.middleware.call('zfs.pool.expand_state', pool['name'])
if expand['state'] is None:
job.set_progress(25, 'Waiting for expansion to start')
await asyncio.sleep(1)
continue
if expand['state'] == 'FINISHED':
job.set_progress(100, '')
break
if expand['waiting_for_resilver']:
message = 'Paused for resilver or clear'
else:
message = 'Expanding'
job.set_progress(max(min(expand['percentage'], 95), 25), message)
await asyncio.sleep(10 if expand['total_secs_left'] > 60 else 1)
| 3,657 | Python | .tac | 76 | 35.802632 | 118 | 0.560258 | truenas/middleware | 2,277 | 481 | 13 | LGPL-3.0 | 9/5/2024, 5:13:34 PM (Europe/Amsterdam) |