Debian Codegraph @

dirsrvtests/tests/suites/acl/proxy_authz_test.py

raw
1 # --- BEGIN COPYRIGHT BLOCK ---
2 # Copyright (C) 2016 Red Hat, Inc.
3 # Copyright (C) 2025 Red Hat, Inc.
4 # All rights reserved.
5 #
6 # License: GPL (version 3 or any later version).
7 # See LICENSE for details.
8 # --- END COPYRIGHT BLOCK ---
9
10 # Proxy authorization with subtree ACIs and the same uid values under two subtrees.
11 import ldap
12 import pytest
13 import logging
14 from ldap.controls.simple import ProxyAuthzControl
15 from lib389._constants import DEFAULT_SUFFIX, DN_DM, PW_DM
16 from lib389.idm.domain import Domain
17 from lib389.idm.organizationalunit import OrganizationalUnits
18 from lib389.idm.user import UserAccounts
19 from lib389.utils import ds_is_older, ensure_bytes
20 from lib389.idm.directorymanager import DirectoryManager
21
22 logging.getLogger(__name__).setLevel(logging.DEBUG)
23 log = logging.getLogger(__name__)
24
25 pytestmark = [
26 pytest.mark.tier1,
27 pytest.mark.skipif(
28 ds_is_older("1.3.5"),
29 reason="Proxy ACI with authorization identity (not on older 389)",
30 ),
31 ]
32
33
34 @pytest.fixture(scope="module")
35 def testuser(topo, request):
36 """Create a test user for the tests."""
37 users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
38 testuser = users.create(properties={
39 'uid': 'test',
40 'cn': 'test',
41 'sn': 'test',
42 'uidNumber': '1001',
43 'gidNumber': '2001',
44 'homeDirectory': '/home/test',
45 'userPassword': PW_DM
46 })
47 log.info(f"Created test user: {testuser.dn}")
48
49 def _cleanup():
50 testuser.delete()
51 log.info(f"Cleanup: removed {testuser.dn}")
52
53 request.addfinalizer(_cleanup)
54 return testuser
55
56
57 @pytest.fixture(scope="module")
58 def proxyuser(topo, request):
59 """Create a proxy user for the tests."""
60 users = UserAccounts(topo.standalone, DEFAULT_SUFFIX)
61 proxyuser = users.create(properties={
62 'uid': 'proxy',
63 'cn': 'proxy',
64 'sn': 'proxy',
65 'uidNumber': '1000',
66 'gidNumber': '2000',
67 'homeDirectory': '/home/proxy',
68 'userPassword': PW_DM
69 })
70 log.info(f"Created proxy user: {proxyuser.dn}")
71
72 def _cleanup():
73 proxyuser.delete()
74 log.info(f"Cleanup: removed {proxyuser.dn}")
75
76 request.addfinalizer(_cleanup)
77 return proxyuser
78
79
80 @pytest.fixture(scope="module")
81 def setup(request, topo, testuser, proxyuser):
82 """Setup the test environment."""
83 inst = topo.standalone
84
85 # Create OUs
86 ous = OrganizationalUnits(inst, DEFAULT_SUFFIX)
87 ou_objects = {}
88 for ou in ('green', 'red'):
89 if ous.exists(dn=f'ou={ou},{DEFAULT_SUFFIX}'):
90 ou_objects[ou] = ous.get(dn=f'ou={ou},{DEFAULT_SUFFIX}')
91 else:
92 orgunit = ous.create(properties={'ou': ou})
93 ou_objects[ou] = orgunit
94
95 # Backup and remove default acis
96 dm = DirectoryManager(inst)
97 dm.rebind()
98 domain = Domain(inst, DEFAULT_SUFFIX)
99 saved_acis = list(domain.get_attr_vals("aci"))
100 domain.remove_all("aci")
101 log.info(f"Removed {len(saved_acis)} default acis")
102
103 # Create acis
104 aci_target = f'(target = "ldap:///{ou_objects["green"].dn}")'
105 aci_targetattr = (
106 '(targetattr = "objectclass || cn || sn || uid || givenname ")'
107 )
108
109 # aci for search-read to green subtree for test user
110 aci_body = (
111 aci_target + aci_targetattr + f'(version 3.0; acl "Allow search-read to green subtree"; allow (read, search, compare) userdn = "ldap:///{testuser.dn.lower()}";)'
112 )
113 domain.add("aci", aci_body)
114 log.info(f"Created aci: {aci_body}")
115
116 # aci for use of proxy auth to green subtree for proxy user
117 aci_body = (
118 aci_target + aci_targetattr + f'(version 3.0; acl "Allow use of proxy auth to green subtree"; allow (proxy) userdn = "ldap:///{proxyuser.dn}";)'
119 )
120 domain.add("aci", aci_body)
121 log.info(f"Created aci: {aci_body}")
122
123 # Create test users in the subtrees
124 test_users = []
125 for idx in range(2):
126 for subtree in ou_objects.values():
127 users = UserAccounts(inst, DEFAULT_SUFFIX, rdn=f'ou={subtree.rdn}')
128 user = users.create(properties={
129 'uid': f'test{idx}',
130 'cn': f'test{idx}',
131 'sn': f'test{idx}',
132 'uidNumber': f'{2000 + idx}',
133 'gidNumber': '100',
134 'homeDirectory': f'/home/test{idx}',
135 'userPassword': PW_DM,
136 'givenName': 'test',
137 'mail': f'test{idx}@example.com',
138 'description': 'description',
139 'employeeNumber': f'{idx}',
140 'telephoneNumber': f'{idx}{idx}{idx}',
141 'mobile': f'{idx}{idx}{idx}',
142 'l': 'MV',
143 'title': 'Engineer'
144 })
145 test_users.append(user)
146 log.info(f"Created test user: {user.dn}")
147
148 def _cleanup():
149 dm.rebind()
150 domain.remove_all("aci")
151 for aci in saved_acis:
152 domain.add("aci", aci)
153 log.info(f"Cleanup: restored {len(saved_acis)} acis")
154
155 for user in test_users:
156 user.delete()
157 log.info(f"Cleanup: removed {user.dn}")
158
159 for orgunit in ou_objects.values():
160 orgunit.delete()
161 log.info(f"Cleanup: removed {orgunit.dn}")
162
163 request.addfinalizer(_cleanup)
164
165
166 @pytest.mark.parametrize("user_name,expect", [
167 ('test', True),
168 ('proxy', False),
169 ])
170 def test_proxy_authz_search_user(topo, setup, user_name, expect):
171 """Verify direct search visibility for regular and proxy users.
172
173 :id: c1c04f2e-e3ab-4204-a738-cdba8b5311e0
174 :parametrized: yes
175 :setup: Standalone instance with green/red OUs, test/proxy users, and proxy-related ACIs
176 :steps:
177 1. Bind as the selected user.
178 2. Search the suffix subtree for uid=test1.
179 :expectedresults:
180 1. Bind operation succeeds.
181 2. The entry is found if the user is allowed to search, otherwise error is raised.
182 """
183 user = UserAccounts(topo.standalone, DEFAULT_SUFFIX).get(user_name)
184 user.rebind(password=PW_DM)
185
186 if expect:
187 UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn='ou=green').get('test1')
188 else:
189 with pytest.raises(ldap.NO_SUCH_OBJECT):
190 UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn='ou=green').get('test1')
191
192
193 @pytest.mark.parametrize("subtree, expect", [('green', True), ('red', False)])
194 def test_proxy_authz_search_with_proxy_auth_as_test_user(topo, setup, testuser, proxyuser, subtree, expect):
195 """Verify proxy user can search as test user with proxy auth control.
196
197 :id: 31d22f3e-14ab-454f-9530-c75fe6e0f5ff
198 :setup: Standalone instance with green/red OUs, test/proxy users, and proxy-related ACIs
199 :steps:
200 1. Create a ProxyAuthz control authorizing as the test user DN.
201 2. Bind as the proxy user.
202 3. Search the suffix subtree for uid=test1 using the proxy auth control.
203 :expectedresults:
204 1. Proxy authorization control is accepted.
205 2. Bind as proxy user succeeds.
206 3. Exactly one entry is returned, matching test-user access to the green subtree.
207 """
208 proxy_ctrl = ProxyAuthzControl(
209 criticality=True, authzId=ensure_bytes(f"dn: {testuser.dn}")
210 )
211
212 users = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn=f'ou={subtree}')
213 backup_controls = users._server_controls
214 try:
215 users._server_controls = [proxy_ctrl]
216
217 proxyuser.bind(password=PW_DM)
218 if expect:
219 users.get('test1')
220 else:
221 with pytest.raises(ldap.NO_SUCH_OBJECT):
222 users.get('test1')
223 finally:
224 users._server_controls = backup_controls
225
226
227 @pytest.mark.parametrize("subtree", ['green', 'red'])
228 def test_proxy_authz_search_dm(topo, setup, subtree):
229 """Verify Directory Manager search returns all matching entries.
230
231 :id: b705f745-d378-4891-8890-5f3e9ef24f17
232 :setup: Standalone instance with green/red OUs, test/proxy users, and proxy-related ACIs
233 :steps:
234 1. Bind as Directory Manager.
235 2. Search the suffix subtree for uid=test1.
236 :expectedresults:
237 1. Bind as Directory Manager succeeds.
238 2. Two matching entries are returned from both test subtrees.
239 """
240 dm = DirectoryManager(topo.standalone, DN_DM)
241 dm.rebind(password=PW_DM)
242
243 UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn=f'ou={subtree}').get('test1')
244
245
246 @pytest.mark.parametrize("user_name,subtree,expect", [
247 ('test', 'green', True),
248 ('proxy', 'green', False),
249 ('test', 'red', False),
250 ('proxy', 'red', False),
251 ])
252 def test_proxy_authz_search_dm_auth_as_user(topo, setup, user_name, subtree, expect):
253 """Verify Directory Manager proxy auth search as selected user identity.
254
255 :id: c9493f75-c740-46f9-bfd8-d267fd85fdcd
256 :parametrized: yes
257 :setup: Standalone instance with green/red OUs, test/proxy users, and proxy-related ACIs
258 :steps:
259 1. Resolve the selected user DN.
260 2. Create a ProxyAuthz control using that user DN.
261 3. Bind as Directory Manager.
262 4. Search the suffix subtree for uid=test1 with the proxy auth control.
263 :expectedresults:
264 1. User DN is resolved successfully.
265 2. Proxy authorization control is accepted.
266 3. Bind as Directory Manager succeeds.
267 4. Returned entry count matches the expected result for the proxied identity.
268 """
269 user = UserAccounts(topo.standalone, DEFAULT_SUFFIX).get(user_name)
270
271 proxy_ctrl = ProxyAuthzControl(
272 criticality=True, authzId=ensure_bytes(f"dn: {user.dn}")
273 )
274
275 users = UserAccounts(topo.standalone, DEFAULT_SUFFIX, rdn=f'ou={subtree}')
276 backup_controls = users._server_controls
277 try:
278 users._server_controls = [proxy_ctrl]
279
280 dm = DirectoryManager(topo.standalone, DN_DM)
281 dm.rebind(password=PW_DM)
282
283 if expect:
284 users.get('test1')
285 else:
286 with pytest.raises(ldap.NO_SUCH_OBJECT):
287 users.get('test1')
288 finally:
289 users._server_controls = backup_controls