s4:ldap.py - add a test for the "systemOnly" classes
[ira/wip.git] / source4 / lib / ldb / tests / python / ldap.py
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 # This is a port of the original in testprogs/ejs/ldap.js
4
5 import getopt
6 import optparse
7 import sys
8 import time
9 import random
10 import base64
11
12 sys.path.append("bin/python")
13 sys.path.append("../lib/subunit/python")
14
15 import samba.getopt as options
16
17 from samba.auth import system_session
18 from ldb import SCOPE_SUBTREE, SCOPE_ONELEVEL, SCOPE_BASE, LdbError
19 from ldb import ERR_NO_SUCH_OBJECT, ERR_ATTRIBUTE_OR_VALUE_EXISTS
20 from ldb import ERR_ENTRY_ALREADY_EXISTS, ERR_UNWILLING_TO_PERFORM
21 from ldb import ERR_NOT_ALLOWED_ON_NON_LEAF, ERR_OTHER, ERR_INVALID_DN_SYNTAX
22 from ldb import ERR_NO_SUCH_ATTRIBUTE, ERR_INSUFFICIENT_ACCESS_RIGHTS
23 from ldb import ERR_OBJECT_CLASS_VIOLATION, ERR_NOT_ALLOWED_ON_RDN
24 from ldb import Message, MessageElement, Dn, FLAG_MOD_ADD, FLAG_MOD_REPLACE
25 from samba import Ldb, param, dom_sid_to_rid
26 from samba import UF_NORMAL_ACCOUNT, UF_TEMP_DUPLICATE_ACCOUNT
27 from samba import UF_SERVER_TRUST_ACCOUNT, UF_WORKSTATION_TRUST_ACCOUNT
28 from samba import UF_INTERDOMAIN_TRUST_ACCOUNT
29 from samba import UF_PASSWD_NOTREQD, UF_ACCOUNTDISABLE
30 from samba import GTYPE_SECURITY_BUILTIN_LOCAL_GROUP
31 from samba import GTYPE_SECURITY_GLOBAL_GROUP, GTYPE_SECURITY_DOMAIN_LOCAL_GROUP
32 from samba import GTYPE_SECURITY_UNIVERSAL_GROUP
33 from samba import GTYPE_DISTRIBUTION_GLOBAL_GROUP
34 from samba import GTYPE_DISTRIBUTION_DOMAIN_LOCAL_GROUP
35 from samba import GTYPE_DISTRIBUTION_UNIVERSAL_GROUP
36 from samba import ATYPE_NORMAL_ACCOUNT, ATYPE_WORKSTATION_TRUST
37 from samba import ATYPE_SECURITY_GLOBAL_GROUP, ATYPE_SECURITY_LOCAL_GROUP
38 from samba import ATYPE_SECURITY_UNIVERSAL_GROUP
39 from samba import ATYPE_DISTRIBUTION_GLOBAL_GROUP
40 from samba import ATYPE_DISTRIBUTION_LOCAL_GROUP
41 from samba import ATYPE_DISTRIBUTION_UNIVERSAL_GROUP
42
43 from subunit import SubunitTestRunner
44 import unittest
45
46 from samba.ndr import ndr_pack, ndr_unpack
47 from samba.dcerpc import security
48
49 parser = optparse.OptionParser("ldap [options] <host>")
50 sambaopts = options.SambaOptions(parser)
51 parser.add_option_group(sambaopts)
52 parser.add_option_group(options.VersionOptions(parser))
53 # use command line creds if available
54 credopts = options.CredentialsOptions(parser)
55 parser.add_option_group(credopts)
56 opts, args = parser.parse_args()
57
58 if len(args) < 1:
59     parser.print_usage()
60     sys.exit(1)
61
62 host = args[0]
63
64 lp = sambaopts.get_loadparm()
65 creds = credopts.get_credentials(lp)
66
67 class BasicTests(unittest.TestCase):
68     def delete_force(self, ldb, dn):
69         try:
70             ldb.delete(dn)
71         except LdbError, (num, _):
72             self.assertEquals(num, ERR_NO_SUCH_OBJECT)
73
74     def find_basedn(self, ldb):
75         res = ldb.search(base="", expression="", scope=SCOPE_BASE,
76                          attrs=["defaultNamingContext"])
77         self.assertEquals(len(res), 1)
78         return res[0]["defaultNamingContext"][0]
79
80     def find_configurationdn(self, ldb):
81         res = ldb.search(base="", expression="", scope=SCOPE_BASE, attrs=["configurationNamingContext"])
82         self.assertEquals(len(res), 1)
83         return res[0]["configurationNamingContext"][0]
84
85     def find_schemadn(self, ldb):
86         res = ldb.search(base="", expression="", scope=SCOPE_BASE, attrs=["schemaNamingContext"])
87         self.assertEquals(len(res), 1)
88         return res[0]["schemaNamingContext"][0]
89
90     def find_domain_sid(self):
91         res = self.ldb.search(base=self.base_dn, expression="(objectClass=*)", scope=SCOPE_BASE)
92         return ndr_unpack( security.dom_sid,res[0]["objectSid"][0])
93
94     def setUp(self):
95         self.ldb = ldb
96         self.gc_ldb = gc_ldb
97         self.base_dn = self.find_basedn(ldb)
98         self.configuration_dn = self.find_configurationdn(ldb)
99         self.schema_dn = self.find_schemadn(ldb)
100         self.domain_sid = self.find_domain_sid()
101
102         print "baseDN: %s\n" % self.base_dn
103
104         self.delete_force(self.ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
105         self.delete_force(self.ldb, "cn=ldaptestuser2,cn=users," + self.base_dn)
106         self.delete_force(self.ldb, "cn=ldaptestuser3,cn=users," + self.base_dn)
107         self.delete_force(self.ldb, "cn=ldaptestuser4,cn=users," + self.base_dn)
108         self.delete_force(self.ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
109         self.delete_force(self.ldb, "cn=ldaptestgroup2,cn=users," + self.base_dn)
110         self.delete_force(self.ldb, "cn=ldaptestcomputer,cn=computers," + self.base_dn)
111         self.delete_force(self.ldb, "cn=ldaptest2computer,cn=computers," + self.base_dn)
112         self.delete_force(self.ldb, "cn=ldaptestcomputer3,cn=computers," + self.base_dn)
113         self.delete_force(self.ldb, "cn=ldaptestutf8user èùéìòà ,cn=users," + self.base_dn)
114         self.delete_force(self.ldb, "cn=ldaptestutf8user2  èùéìòà ,cn=users," + self.base_dn)
115         self.delete_force(self.ldb, "cn=ldaptestcontainer," + self.base_dn)
116         self.delete_force(self.ldb, "cn=ldaptestcontainer2," + self.base_dn)
117         self.delete_force(self.ldb, "cn=parentguidtest,cn=users," + self.base_dn)
118         self.delete_force(self.ldb, "cn=parentguidtest,cn=testotherusers," + self.base_dn)
119         self.delete_force(self.ldb, "cn=testotherusers," + self.base_dn)
120         self.delete_force(self.ldb, "cn=ldaptestobject," + self.base_dn)
121
122     def test_system_only(self):
123         """Test systemOnly objects"""
124         print "Test systemOnly objects"""
125
126         try:
127             self.ldb.add({
128                 "dn": "cn=ldaptestobject," + self.base_dn,
129                 "objectclass": "configuration"})
130             self.fail()
131         except LdbError, (num, _):
132             self.assertEquals(num, ERR_UNWILLING_TO_PERFORM)
133
134         self.delete_force(self.ldb, "cn=ldaptestobject," + self.base_dn)
135
136     def test_invalid_attribute(self):
137         """Test adding invalid attributes (not in schema)"""
138         print "Test adding invalid attributes (not in schema)"""
139
140         try:
141             self.ldb.add({
142                 "dn": "cn=ldaptestgroup,cn=users," + self.base_dn,
143                 "objectclass": "group",
144                 "thisdoesnotexist": "x"})
145             self.fail()
146         except LdbError, (num, _):
147             self.assertEquals(num, ERR_NO_SUCH_ATTRIBUTE)
148
149         self.ldb.add({
150              "dn": "cn=ldaptestgroup,cn=users," + self.base_dn,
151              "objectclass": "group"})
152
153         m = Message()
154         m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
155         m["thisdoesnotexist"] = MessageElement("x", FLAG_MOD_REPLACE,
156           "thisdoesnotexist")
157         try:
158             ldb.modify(m)
159             self.fail()
160         except LdbError, (num, _):
161             self.assertEquals(num, ERR_NO_SUCH_ATTRIBUTE)
162
163         self.delete_force(self.ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
164
165     def test_distinguished_name(self):
166         """Tests the 'distinguishedName' attribute"""
167         print "Tests the 'distinguishedName' attribute"""
168
169         self.ldb.add({
170              "dn": "cn=ldaptestgroup,cn=users," + self.base_dn,
171              "objectclass": "group"})
172
173         m = Message()
174         m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
175         m["distinguishedName"] = MessageElement(
176           "cn=ldaptestuser,cn=users," + self.base_dn, FLAG_MOD_REPLACE,
177           "distinguishedName")
178
179         try:
180             ldb.modify(m)
181             self.fail()
182         except LdbError, (num, _):
183             self.assertEquals(num, ERR_UNWILLING_TO_PERFORM)
184
185         self.delete_force(self.ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
186
187     def test_rdn_name(self):
188         """Tests the RDN"""
189         print "Tests the RDN"""
190
191         self.ldb.add({
192              "dn": "cn=ldaptestgroup,cn=users," + self.base_dn,
193              "objectclass": "group"})
194
195         m = Message()
196         m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
197         m["name"] = MessageElement("cn=ldaptestuser", FLAG_MOD_REPLACE,
198           "name")
199
200         try:
201             ldb.modify(m)
202             self.fail()
203         except LdbError, (num, _):
204             self.assertEquals(num, ERR_NOT_ALLOWED_ON_RDN)
205
206         m = Message()
207         m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
208         m["cn"] = MessageElement("ldaptestuser",
209           FLAG_MOD_REPLACE, "cn")
210
211         try:
212             ldb.modify(m)
213             self.fail()
214         except LdbError, (num, _):
215             self.assertEquals(num, ERR_NOT_ALLOWED_ON_RDN)
216
217         self.delete_force(self.ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
218
219     def test_rename(self):
220         """Tests the rename operation"""
221         print "Tests the rename operations"""
222
223         self.ldb.add({
224              "dn": "cn=ldaptestuser2,cn=users," + self.base_dn,
225              "objectclass": ["user", "person"] })
226
227         ldb.rename("cn=ldaptestuser2,cn=users," + self.base_dn, "cn=ldaptestuser2,cn=users," + self.base_dn)
228         ldb.rename("cn=ldaptestuser2,cn=users," + self.base_dn, "cn=ldaptestuser3,cn=users," + self.base_dn)
229         ldb.rename("cn=ldaptestuser3,cn=users," + self.base_dn, "cn=ldaptestUSER3,cn=users," + self.base_dn)
230         try:
231             ldb.rename("cn=ldaptestuser3,cn=users," + self.base_dn, ",cn=users," + self.base_dn)
232             self.fail()
233         except LdbError, (num, _):
234             self.assertEquals(num, ERR_INVALID_DN_SYNTAX)
235
236         self.delete_force(self.ldb, "cn=ldaptestuser3,cn=users," + self.base_dn)
237
238     def test_parentGUID(self):
239         """Test parentGUID behaviour"""
240         print "Testing parentGUID behaviour\n"
241
242         # TODO: This seems to fail on Windows Server. Hidden attribute?
243
244         self.ldb.add({
245             "dn": "cn=parentguidtest,cn=users," + self.base_dn,
246             "objectclass":"user",
247             "samaccountname":"parentguidtest"});
248         res1 = ldb.search(base="cn=parentguidtest,cn=users," + self.base_dn, scope=SCOPE_BASE,
249                           attrs=["parentGUID"]);
250         res2 = ldb.search(base="cn=users," + self.base_dn,scope=SCOPE_BASE,
251                           attrs=["objectGUID"]);
252         self.assertEquals(res1[0]["parentGUID"], res2[0]["objectGUID"]);
253
254         print "Testing parentGUID behaviour on rename\n"
255
256         self.ldb.add({
257             "dn": "cn=testotherusers," + self.base_dn,
258             "objectclass":"container"});
259         res1 = ldb.search(base="cn=testotherusers," + self.base_dn,scope=SCOPE_BASE,
260                           attrs=["objectGUID"]);
261         ldb.rename("cn=parentguidtest,cn=users," + self.base_dn,
262                    "cn=parentguidtest,cn=testotherusers," + self.base_dn);
263         res2 = ldb.search(base="cn=parentguidtest,cn=testotherusers," + self.base_dn,
264                           scope=SCOPE_BASE,
265                           attrs=["parentGUID"]);
266         self.assertEquals(res1[0]["objectGUID"], res2[0]["parentGUID"]);
267
268         self.delete_force(self.ldb, "cn=parentguidtest,cn=testotherusers," + self.base_dn)
269         self.delete_force(self.ldb, "cn=testotherusers," + self.base_dn)
270
271     def test_groupType_int32(self):
272         """Test groupType (int32) behaviour (should appear to be casted to a 32 bit signed integer before comparsion)"""
273         print "Testing groupType (int32) behaviour\n"
274
275         res1 = ldb.search(base=self.base_dn, scope=SCOPE_SUBTREE,
276                           attrs=["groupType"], expression="groupType=2147483653");
277
278         res2 = ldb.search(base=self.base_dn, scope=SCOPE_SUBTREE,
279                           attrs=["groupType"], expression="groupType=-2147483643");
280
281         self.assertEquals(len(res1), len(res2))
282
283         self.assertTrue(res1.count > 0)
284
285         self.assertEquals(res1[0]["groupType"][0], "-2147483643")
286
287     def test_groups(self):
288         """This tests the group behaviour (setting, changing) of a user account"""
289         print "Testing group behaviour\n"
290
291         ldb.add({
292             "dn": "cn=ldaptestgroup,cn=users," + self.base_dn,
293             "objectclass": "group"})
294
295         ldb.add({
296             "dn": "cn=ldaptestgroup2,cn=users," + self.base_dn,
297             "objectclass": "group"})
298
299         res1 = ldb.search("cn=ldaptestgroup,cn=users," + self.base_dn,
300                           scope=SCOPE_BASE, attrs=["objectSID"])
301         self.assertTrue(len(res1) == 1)
302         group_rid_1 = dom_sid_to_rid(ldb.schema_format_value("objectSID",
303           res1[0]["objectSID"][0]))
304
305         res1 = ldb.search("cn=ldaptestgroup2,cn=users," + self.base_dn,
306                           scope=SCOPE_BASE, attrs=["objectSID"])
307         self.assertTrue(len(res1) == 1)
308         group_rid_2 = dom_sid_to_rid(ldb.schema_format_value("objectSID",
309           res1[0]["objectSID"][0]))
310
311         # Try to create a user with an invalid primary group
312         try:
313             ldb.add({
314                 "dn": "cn=ldaptestuser,cn=users," + self.base_dn,
315                 "objectclass": ["user", "person"],
316                 "primaryGroupID": "0"})
317             self.fail()
318         except LdbError, (num, _):
319             self.assertEquals(num, ERR_UNWILLING_TO_PERFORM)
320         self.delete_force(self.ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
321
322         # Try to Create a user with a valid primary group
323 # TODO Some more investigation needed here
324 #        try:
325 #            ldb.add({
326 #                "dn": "cn=ldaptestuser,cn=users," + self.base_dn,
327 #                "objectclass": ["user", "person"],
328 #                "primaryGroupID": str(group_rid_1)})
329 #            self.fail()
330 #        except LdbError, (num, _):
331 #            self.assertEquasl(num, ERR_UNWILLING_TO_PERFORM)
332 #        self.delete_force(self.ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
333
334         ldb.add({
335             "dn": "cn=ldaptestuser,cn=users," + self.base_dn,
336             "objectclass": ["user", "person"]})
337
338         # Try to add invalid primary group
339         m = Message()
340         m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
341         m["primaryGroupID"] = MessageElement("0", FLAG_MOD_REPLACE,
342           "primaryGroupID")
343         try:
344             ldb.modify(m)
345             self.fail()
346         except LdbError, (num, _):
347             self.assertEquals(num, ERR_UNWILLING_TO_PERFORM)
348
349         # Try to make group 1 primary - should be denied since it is not yet
350         # secondary
351         m = Message()
352         m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
353         m["primaryGroupID"] = MessageElement(str(group_rid_1),
354           FLAG_MOD_REPLACE, "primaryGroupID")
355         try:
356             ldb.modify(m)
357             self.fail()
358         except LdbError, (num, _):
359             self.assertEquals(num, ERR_UNWILLING_TO_PERFORM)
360
361         # Make group 1 secondary
362         m = Message()
363         m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
364         m["member"] = "cn=ldaptestuser,cn=users," + self.base_dn
365         ldb.modify(m)
366
367         # Make group 1 primary
368         m = Message()
369         m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
370         m["primaryGroupID"] = MessageElement(str(group_rid_1),
371           FLAG_MOD_REPLACE, "primaryGroupID")
372         ldb.modify(m)
373
374         # Try to delete group 1 - should be denied
375         try:
376             ldb.delete("cn=ldaptestgroup,cn=users," + self.base_dn)
377             self.fail()
378         except LdbError, (num, _):
379             self.assertEquals(num, ERR_ENTRY_ALREADY_EXISTS)
380
381         # Try to add group 1 also as secondary - should be denied
382         m = Message()
383         m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
384         m["member"] = "cn=ldaptestuser,cn=users," + self.base_dn
385         try:
386             ldb.modify(m)
387             self.fail()
388         except LdbError, (num, _):
389             self.assertEquals(num, ERR_ENTRY_ALREADY_EXISTS)
390
391         # Try to add invalid member to group 1 - should be denied
392         m = Message()
393         m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
394         m["member"] = MessageElement(
395           "cn=ldaptestuser3,cn=users," + self.base_dn,
396           FLAG_MOD_ADD, "member")
397         try:
398             ldb.modify(m)
399             self.fail()
400         except LdbError, (num, _):
401             self.assertEquals(num, ERR_NO_SUCH_OBJECT)
402
403         # Make group 2 secondary
404         m = Message()
405         m.dn = Dn(ldb, "cn=ldaptestgroup2,cn=users," + self.base_dn)
406         m["member"] = "cn=ldaptestuser,cn=users," + self.base_dn
407         ldb.modify(m)
408
409         # Swap the groups
410         m = Message()
411         m.dn = Dn(ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
412         m["primaryGroupID"] = MessageElement(str(group_rid_2),
413           FLAG_MOD_REPLACE, "primaryGroupID")
414         ldb.modify(m)
415
416         # Old primary group should contain a "member" attribute for the user,
417         # the new shouldn't contain anymore one
418         res1 = ldb.search("cn=ldaptestgroup, cn=users," + self.base_dn,
419                           scope=SCOPE_BASE, attrs=["member"])
420         self.assertTrue(len(res1) == 1)
421         self.assertTrue(len(res1[0]["member"]) == 1)
422         self.assertEquals(res1[0]["member"][0].lower(),
423           ("cn=ldaptestuser,cn=users," + self.base_dn).lower())
424
425         res1 = ldb.search("cn=ldaptestgroup2, cn=users," + self.base_dn,
426                           scope=SCOPE_BASE, attrs=["member"])
427         self.assertTrue(len(res1) == 1)
428         self.assertFalse("member" in res1[0])
429
430         # Also this should be denied
431         try:
432             ldb.add({
433               "dn": "cn=ldaptestuser1,cn=users," + self.base_dn,
434               "objectclass": ["user", "person"],
435               "primaryGroupID": "0"})
436             self.fail()
437         except LdbError, (num, _):
438             self.assertEquals(num, ERR_UNWILLING_TO_PERFORM)
439
440         self.delete_force(self.ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
441         self.delete_force(self.ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
442         self.delete_force(self.ldb, "cn=ldaptestgroup2,cn=users," + self.base_dn)
443
444     def test_primary_group_token(self):
445         """Test the primary group token behaviour (hidden-generated-readonly attribute on groups)"""
446         print "Testing primary group token behaviour\n"
447
448         ldb.add({
449             "dn": "cn=ldaptestuser,cn=users," + self.base_dn,
450             "objectclass": ["user", "person"]})
451
452         ldb.add({
453             "dn": "cn=ldaptestgroup,cn=users," + self.base_dn,
454             "objectclass": "group"})
455
456         res1 = ldb.search("cn=ldaptestuser, cn=users," + self.base_dn,
457                           scope=SCOPE_BASE, attrs=["primaryGroupToken"])
458         self.assertTrue(len(res1) == 1)
459         self.assertFalse("primaryGroupToken" in res1[0])
460
461         res1 = ldb.search("cn=ldaptestgroup,cn=users," + self.base_dn,
462                           scope=SCOPE_BASE)
463         self.assertTrue(len(res1) == 1)
464         self.assertFalse("primaryGroupToken" in res1[0])
465
466         res1 = ldb.search("cn=ldaptestgroup,cn=users," + self.base_dn,
467                           scope=SCOPE_BASE, attrs=["primaryGroupToken", "objectSID"])
468         self.assertTrue(len(res1) == 1)
469         primary_group_token = int(res1[0]["primaryGroupToken"][0])
470
471         rid = dom_sid_to_rid(ldb.schema_format_value("objectSID", res1[0]["objectSID"][0]))
472         self.assertEquals(primary_group_token, rid)
473
474 # TODO Has to wait until we support read-only generated attributes correctly
475 #        m = Message()
476 #        m.dn = Dn(ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
477 #        m["primaryGroupToken"] = "100"
478 #        try:
479 #                ldb.modify(m)
480 #                self.fail()
481 #        except LdbError, (num, msg):
482
483         self.delete_force(self.ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
484         self.delete_force(self.ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
485
486     def test_all(self):
487         """Basic tests"""
488
489         print "Testing user add"
490
491         ldb.add({
492             "dn": "cn=ldaptestuser,cn=uSers," + self.base_dn,
493             "objectclass": ["user", "person"],
494             "cN": "LDAPtestUSER",
495             "givenname": "ldap",
496             "sn": "testy"})
497
498         ldb.add({
499             "dn": "cn=ldaptestgroup,cn=uSers," + self.base_dn,
500             "objectclass": "group",
501             "member": "cn=ldaptestuser,cn=useRs," + self.base_dn})
502
503         ldb.add({
504             "dn": "cn=ldaptestcomputer,cn=computers," + self.base_dn,
505             "objectclass": "computer",
506             "cN": "LDAPtestCOMPUTER"})
507
508         ldb.add({"dn": "cn=ldaptest2computer,cn=computers," + self.base_dn,
509             "objectClass": "computer",
510             "cn": "LDAPtest2COMPUTER",
511             "userAccountControl": str(UF_WORKSTATION_TRUST_ACCOUNT),
512             "displayname": "ldap testy"})
513
514         try:
515             ldb.add({"dn": "cn=ldaptestcomputer3,cn=computers," + self.base_dn,
516                      "objectClass": "computer",
517                      "cn": "LDAPtest2COMPUTER"
518                      })
519             self.fail()
520         except LdbError, (num, _):
521             self.assertEquals(num, ERR_INVALID_DN_SYNTAX)
522
523         try:
524             ldb.add({"dn": "cn=ldaptestcomputer3,cn=computers," + self.base_dn,
525                      "objectClass": "computer",
526                      "cn": "ldaptestcomputer3",
527                      "sAMAccountType": str(ATYPE_NORMAL_ACCOUNT)
528                 })
529             self.fail()
530         except LdbError, (num, _):
531             self.assertEquals(num, ERR_UNWILLING_TO_PERFORM)
532
533         ldb.add({"dn": "cn=ldaptestcomputer3,cn=computers," + self.base_dn,
534                  "objectClass": "computer",
535                  "cn": "LDAPtestCOMPUTER3"
536                  })
537
538         print "Testing ldb.search for (&(cn=ldaptestcomputer3)(objectClass=user))";
539         res = ldb.search(self.base_dn, expression="(&(cn=ldaptestcomputer3)(objectClass=user))");
540         self.assertEquals(len(res), 1, "Found only %d for (&(cn=ldaptestcomputer3)(objectClass=user))" % len(res))
541
542         self.assertEquals(str(res[0].dn), ("CN=ldaptestcomputer3,CN=Computers," + self.base_dn));
543         self.assertEquals(res[0]["cn"][0], "ldaptestcomputer3");
544         self.assertEquals(res[0]["name"][0], "ldaptestcomputer3");
545         self.assertEquals(res[0]["objectClass"][0], "top");
546         self.assertEquals(res[0]["objectClass"][1], "person");
547         self.assertEquals(res[0]["objectClass"][2], "organizationalPerson");
548         self.assertEquals(res[0]["objectClass"][3], "user");
549         self.assertEquals(res[0]["objectClass"][4], "computer");
550         self.assertTrue("objectGUID" in res[0])
551         self.assertTrue("whenCreated" in res[0])
552         self.assertEquals(res[0]["objectCategory"][0], ("CN=Computer,CN=Schema,CN=Configuration," + self.base_dn));
553         self.assertEquals(int(res[0]["primaryGroupID"][0]), 513);
554         self.assertEquals(int(res[0]["sAMAccountType"][0]), ATYPE_NORMAL_ACCOUNT);
555         self.assertEquals(int(res[0]["userAccountControl"][0]), UF_NORMAL_ACCOUNT | UF_PASSWD_NOTREQD | UF_ACCOUNTDISABLE);
556
557         self.delete_force(self.ldb, "cn=ldaptestcomputer3,cn=computers," + self.base_dn)
558
559         print "Testing attribute or value exists behaviour"
560         try:
561             ldb.modify_ldif("""
562 dn: cn=ldaptest2computer,cn=computers,""" + self.base_dn + """
563 changetype: modify
564 replace: servicePrincipalName
565 servicePrincipalName: host/ldaptest2computer
566 servicePrincipalName: host/ldaptest2computer
567 servicePrincipalName: cifs/ldaptest2computer
568 """)
569             self.fail()
570         except LdbError, (num, msg):
571             self.assertEquals(num, ERR_ATTRIBUTE_OR_VALUE_EXISTS)
572
573         ldb.modify_ldif("""
574 dn: cn=ldaptest2computer,cn=computers,""" + self.base_dn + """
575 changetype: modify
576 replace: servicePrincipalName
577 servicePrincipalName: host/ldaptest2computer
578 servicePrincipalName: cifs/ldaptest2computer
579 """)
580         try:
581             ldb.modify_ldif("""
582 dn: cn=ldaptest2computer,cn=computers,""" + self.base_dn + """
583 changetype: modify
584 add: servicePrincipalName
585 servicePrincipalName: host/ldaptest2computer
586 """)
587             self.fail()
588         except LdbError, (num, msg):
589             self.assertEquals(num, ERR_ATTRIBUTE_OR_VALUE_EXISTS)
590
591         print "Testing ranged results"
592         ldb.modify_ldif("""
593 dn: cn=ldaptest2computer,cn=computers,""" + self.base_dn + """
594 changetype: modify
595 replace: servicePrincipalName
596 """)
597
598         ldb.modify_ldif("""
599 dn: cn=ldaptest2computer,cn=computers,""" + self.base_dn + """
600 changetype: modify
601 add: servicePrincipalName
602 servicePrincipalName: host/ldaptest2computer0
603 servicePrincipalName: host/ldaptest2computer1
604 servicePrincipalName: host/ldaptest2computer2
605 servicePrincipalName: host/ldaptest2computer3
606 servicePrincipalName: host/ldaptest2computer4
607 servicePrincipalName: host/ldaptest2computer5
608 servicePrincipalName: host/ldaptest2computer6
609 servicePrincipalName: host/ldaptest2computer7
610 servicePrincipalName: host/ldaptest2computer8
611 servicePrincipalName: host/ldaptest2computer9
612 servicePrincipalName: host/ldaptest2computer10
613 servicePrincipalName: host/ldaptest2computer11
614 servicePrincipalName: host/ldaptest2computer12
615 servicePrincipalName: host/ldaptest2computer13
616 servicePrincipalName: host/ldaptest2computer14
617 servicePrincipalName: host/ldaptest2computer15
618 servicePrincipalName: host/ldaptest2computer16
619 servicePrincipalName: host/ldaptest2computer17
620 servicePrincipalName: host/ldaptest2computer18
621 servicePrincipalName: host/ldaptest2computer19
622 servicePrincipalName: host/ldaptest2computer20
623 servicePrincipalName: host/ldaptest2computer21
624 servicePrincipalName: host/ldaptest2computer22
625 servicePrincipalName: host/ldaptest2computer23
626 servicePrincipalName: host/ldaptest2computer24
627 servicePrincipalName: host/ldaptest2computer25
628 servicePrincipalName: host/ldaptest2computer26
629 servicePrincipalName: host/ldaptest2computer27
630 servicePrincipalName: host/ldaptest2computer28
631 servicePrincipalName: host/ldaptest2computer29
632 """)
633
634         res = ldb.search(self.base_dn, expression="(cn=ldaptest2computer))", scope=SCOPE_SUBTREE,
635                          attrs=["servicePrincipalName;range=0-*"])
636         self.assertEquals(len(res), 1, "Could not find (cn=ldaptest2computer)")
637         #print len(res[0]["servicePrincipalName;range=0-*"])
638         self.assertEquals(len(res[0]["servicePrincipalName;range=0-*"]), 30)
639
640         res = ldb.search(self.base_dn, expression="(cn=ldaptest2computer))", scope=SCOPE_SUBTREE, attrs=["servicePrincipalName;range=0-19"])
641         self.assertEquals(len(res), 1, "Could not find (cn=ldaptest2computer)")
642             # print res[0]["servicePrincipalName;range=0-19"].length
643         self.assertEquals(len(res[0]["servicePrincipalName;range=0-19"]), 20)
644
645
646         res = ldb.search(self.base_dn, expression="(cn=ldaptest2computer))", scope=SCOPE_SUBTREE, attrs=["servicePrincipalName;range=0-30"])
647         self.assertEquals(len(res), 1, "Could not find (cn=ldaptest2computer)")
648         self.assertEquals(len(res[0]["servicePrincipalName;range=0-*"]), 30)
649
650         res = ldb.search(self.base_dn, expression="(cn=ldaptest2computer))", scope=SCOPE_SUBTREE, attrs=["servicePrincipalName;range=0-40"])
651         self.assertEquals(len(res), 1, "Could not find (cn=ldaptest2computer)")
652         self.assertEquals(len(res[0]["servicePrincipalName;range=0-*"]), 30)
653
654         res = ldb.search(self.base_dn, expression="(cn=ldaptest2computer))", scope=SCOPE_SUBTREE, attrs=["servicePrincipalName;range=30-40"])
655         self.assertEquals(len(res), 1, "Could not find (cn=ldaptest2computer)")
656         self.assertEquals(len(res[0]["servicePrincipalName;range=30-*"]), 0)
657
658
659         res = ldb.search(self.base_dn, expression="(cn=ldaptest2computer))", scope=SCOPE_SUBTREE, attrs=["servicePrincipalName;range=10-40"])
660         self.assertEquals(len(res), 1, "Could not find (cn=ldaptest2computer)")
661         self.assertEquals(len(res[0]["servicePrincipalName;range=10-*"]), 20)
662         # pos_11 = res[0]["servicePrincipalName;range=10-*"][18]
663
664         res = ldb.search(self.base_dn, expression="(cn=ldaptest2computer))", scope=SCOPE_SUBTREE, attrs=["servicePrincipalName;range=11-40"])
665         self.assertEquals(len(res), 1, "Could not find (cn=ldaptest2computer)")
666         self.assertEquals(len(res[0]["servicePrincipalName;range=11-*"]), 19)
667             # print res[0]["servicePrincipalName;range=11-*"][18]
668             # print pos_11
669             # self.assertEquals((res[0]["servicePrincipalName;range=11-*"][18]), pos_11)
670
671         res = ldb.search(self.base_dn, expression="(cn=ldaptest2computer))", scope=SCOPE_SUBTREE, attrs=["servicePrincipalName;range=11-15"])
672         self.assertEquals(len(res), 1, "Could not find (cn=ldaptest2computer)")
673         self.assertEquals(len(res[0]["servicePrincipalName;range=11-15"]), 5)
674             # self.assertEquals(res[0]["servicePrincipalName;range=11-15"][4], pos_11)
675
676         res = ldb.search(self.base_dn, expression="(cn=ldaptest2computer))", scope=SCOPE_SUBTREE, attrs=["servicePrincipalName"])
677         self.assertEquals(len(res), 1, "Could not find (cn=ldaptest2computer)")
678             # print res[0]["servicePrincipalName"][18]
679             # print pos_11
680         self.assertEquals(len(res[0]["servicePrincipalName"]), 30)
681             # self.assertEquals(res[0]["servicePrincipalName"][18], pos_11)
682
683         self.delete_force(self.ldb, "cn=ldaptestuser2,cn=users," + self.base_dn)
684         ldb.add({
685             "dn": "cn=ldaptestuser2,cn=useRs," + self.base_dn,
686             "objectClass": ["person", "user"],
687             "cn": "LDAPtestUSER2",
688             "givenname": "testy",
689             "sn": "ldap user2"})
690
691         print "Testing Ambigious Name Resolution"
692         # Testing ldb.search for (&(anr=ldap testy)(objectClass=user))
693         res = ldb.search(expression="(&(anr=ldap testy)(objectClass=user))")
694         self.assertEquals(len(res), 3, "Found only %d of 3 for (&(anr=ldap testy)(objectClass=user))" % len(res))
695
696         # Testing ldb.search for (&(anr=testy ldap)(objectClass=user))
697         res = ldb.search(expression="(&(anr=testy ldap)(objectClass=user))")
698         self.assertEquals(len(res), 2, "Found only %d of 2 for (&(anr=testy ldap)(objectClass=user))" % len(res))
699
700         # Testing ldb.search for (&(anr=ldap)(objectClass=user))
701         res = ldb.search(expression="(&(anr=ldap)(objectClass=user))")
702         self.assertEquals(len(res), 4, "Found only %d of 4 for (&(anr=ldap)(objectClass=user))" % len(res))
703
704         # Testing ldb.search for (&(anr==ldap)(objectClass=user))
705         res = ldb.search(expression="(&(anr==ldap)(objectClass=user))")
706         self.assertEquals(len(res), 1, "Could not find (&(anr==ldap)(objectClass=user)). Found only %d for (&(anr=ldap)(objectClass=user))" % len(res))
707
708         self.assertEquals(str(res[0].dn), ("CN=ldaptestuser,CN=Users," + self.base_dn))
709         self.assertEquals(res[0]["cn"][0], "ldaptestuser")
710         self.assertEquals(str(res[0]["name"]), "ldaptestuser")
711
712         # Testing ldb.search for (&(anr=testy)(objectClass=user))
713         res = ldb.search(expression="(&(anr=testy)(objectClass=user))")
714         self.assertEquals(len(res), 2, "Found only %d for (&(anr=testy)(objectClass=user))" % len(res))
715
716         # Testing ldb.search for (&(anr=testy ldap)(objectClass=user))
717         res = ldb.search(expression="(&(anr=testy ldap)(objectClass=user))")
718         self.assertEquals(len(res), 2, "Found only %d for (&(anr=testy ldap)(objectClass=user))" % len(res))
719
720         # Testing ldb.search for (&(anr==testy ldap)(objectClass=user))
721 # this test disabled for the moment, as anr with == tests are not understood
722 #        res = ldb.search(expression="(&(anr==testy ldap)(objectClass=user))")
723 #        self.assertEquals(len(res), 1, "Found only %d for (&(anr==testy ldap)(objectClass=user))" % len(res))
724
725         self.assertEquals(str(res[0].dn), ("CN=ldaptestuser,CN=Users," + self.base_dn))
726         self.assertEquals(res[0]["cn"][0], "ldaptestuser")
727         self.assertEquals(res[0]["name"][0], "ldaptestuser")
728
729         # Testing ldb.search for (&(anr==testy ldap)(objectClass=user))
730 #        res = ldb.search(expression="(&(anr==testy ldap)(objectClass=user))")
731 #        self.assertEquals(len(res), 1, "Could not find (&(anr==testy ldap)(objectClass=user))")
732
733         self.assertEquals(str(res[0].dn), ("CN=ldaptestuser,CN=Users," + self.base_dn))
734         self.assertEquals(res[0]["cn"][0], "ldaptestuser")
735         self.assertEquals(res[0]["name"][0], "ldaptestuser")
736
737         # Testing ldb.search for (&(anr=testy ldap user)(objectClass=user))
738         res = ldb.search(expression="(&(anr=testy ldap user)(objectClass=user))")
739         self.assertEquals(len(res), 1, "Could not find (&(anr=testy ldap user)(objectClass=user))")
740
741         self.assertEquals(str(res[0].dn), ("CN=ldaptestuser2,CN=Users," + self.base_dn))
742         self.assertEquals(str(res[0]["cn"]), "ldaptestuser2")
743         self.assertEquals(str(res[0]["name"]), "ldaptestuser2")
744
745         # Testing ldb.search for (&(anr==testy ldap user2)(objectClass=user))
746 #        res = ldb.search(expression="(&(anr==testy ldap user2)(objectClass=user))")
747 #        self.assertEquals(len(res), 1, "Could not find (&(anr==testy ldap user2)(objectClass=user))")
748
749         self.assertEquals(str(res[0].dn), ("CN=ldaptestuser2,CN=Users," + self.base_dn))
750         self.assertEquals(str(res[0]["cn"]), "ldaptestuser2")
751         self.assertEquals(str(res[0]["name"]), "ldaptestuser2")
752
753         # Testing ldb.search for (&(anr==ldap user2)(objectClass=user))
754 #        res = ldb.search(expression="(&(anr==ldap user2)(objectClass=user))")
755 #        self.assertEquals(len(res), 1, "Could not find (&(anr==ldap user2)(objectClass=user))")
756
757         self.assertEquals(str(res[0].dn), ("CN=ldaptestuser2,CN=Users," + self.base_dn))
758         self.assertEquals(str(res[0]["cn"]), "ldaptestuser2")
759         self.assertEquals(str(res[0]["name"]), "ldaptestuser2")
760
761         # Testing ldb.search for (&(anr==not ldap user2)(objectClass=user))
762 #        res = ldb.search(expression="(&(anr==not ldap user2)(objectClass=user))")
763 #        self.assertEquals(len(res), 0, "Must not find (&(anr==not ldap user2)(objectClass=user))")
764
765         # Testing ldb.search for (&(anr=not ldap user2)(objectClass=user))
766         res = ldb.search(expression="(&(anr=not ldap user2)(objectClass=user))")
767         self.assertEquals(len(res), 0, "Must not find (&(anr=not ldap user2)(objectClass=user))")
768
769         # Testing ldb.search for (&(anr="testy ldap")(objectClass=user)) (ie, with quotes)
770 #        res = ldb.search(expression="(&(anr==\"testy ldap\")(objectClass=user))")
771 #        self.assertEquals(len(res), 0, "Found (&(anr==\"testy ldap\")(objectClass=user))")
772
773         print "Testing Renames"
774
775         attrs = ["objectGUID", "objectSid"]
776         print "Testing ldb.search for (&(cn=ldaptestUSer2)(objectClass=user))"
777         res_user = ldb.search(self.base_dn, expression="(&(cn=ldaptestUSer2)(objectClass=user))", scope=SCOPE_SUBTREE, attrs=attrs)
778         self.assertEquals(len(res_user), 1, "Could not find (&(cn=ldaptestUSer2)(objectClass=user))")
779
780         # Check rename works with extended/alternate DN forms
781         ldb.rename("<SID=" + ldb.schema_format_value("objectSID", res_user[0]["objectSID"][0]) + ">" , "cn=ldaptestUSER3,cn=users," + self.base_dn)
782
783         print "Testing ldb.search for (&(cn=ldaptestuser3)(objectClass=user))"
784         res = ldb.search(expression="(&(cn=ldaptestuser3)(objectClass=user))")
785         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestuser3)(objectClass=user))")
786
787         self.assertEquals(str(res[0].dn), ("CN=ldaptestUSER3,CN=Users," + self.base_dn))
788         self.assertEquals(str(res[0]["cn"]), "ldaptestUSER3")
789         self.assertEquals(str(res[0]["name"]), "ldaptestUSER3")
790
791         #"Testing ldb.search for (&(&(cn=ldaptestuser3)(userAccountControl=*))(objectClass=user))"
792         res = ldb.search(expression="(&(&(cn=ldaptestuser3)(userAccountControl=*))(objectClass=user))")
793         self.assertEquals(len(res), 1, "(&(&(cn=ldaptestuser3)(userAccountControl=*))(objectClass=user))")
794
795         self.assertEquals(str(res[0].dn), ("CN=ldaptestUSER3,CN=Users," + self.base_dn))
796         self.assertEquals(str(res[0]["cn"]), "ldaptestUSER3")
797         self.assertEquals(str(res[0]["name"]), "ldaptestUSER3")
798
799         #"Testing ldb.search for (&(&(cn=ldaptestuser3)(userAccountControl=546))(objectClass=user))"
800         res = ldb.search(expression="(&(&(cn=ldaptestuser3)(userAccountControl=546))(objectClass=user))")
801         self.assertEquals(len(res), 1, "(&(&(cn=ldaptestuser3)(userAccountControl=546))(objectClass=user))")
802
803         self.assertEquals(str(res[0].dn), ("CN=ldaptestUSER3,CN=Users," + self.base_dn))
804         self.assertEquals(str(res[0]["cn"]), "ldaptestUSER3")
805         self.assertEquals(str(res[0]["name"]), "ldaptestUSER3")
806
807         #"Testing ldb.search for (&(&(cn=ldaptestuser3)(userAccountControl=547))(objectClass=user))"
808         res = ldb.search(expression="(&(&(cn=ldaptestuser3)(userAccountControl=547))(objectClass=user))")
809         self.assertEquals(len(res), 0, "(&(&(cn=ldaptestuser3)(userAccountControl=547))(objectClass=user))")
810
811         # This is a Samba special, and does not exist in real AD
812         #    print "Testing ldb.search for (dn=CN=ldaptestUSER3,CN=Users," + self.base_dn + ")"
813         #    res = ldb.search("(dn=CN=ldaptestUSER3,CN=Users," + self.base_dn + ")")
814         #    if (res.error != 0 || len(res) != 1) {
815         #        print "Could not find (dn=CN=ldaptestUSER3,CN=Users," + self.base_dn + ")"
816         #        self.assertEquals(len(res), 1)
817         #    }
818         #    self.assertEquals(res[0].dn, ("CN=ldaptestUSER3,CN=Users," + self.base_dn))
819         #    self.assertEquals(res[0].cn, "ldaptestUSER3")
820         #    self.assertEquals(res[0].name, "ldaptestUSER3")
821
822         print "Testing ldb.search for (distinguishedName=CN=ldaptestUSER3,CN=Users," + self.base_dn + ")"
823         res = ldb.search(expression="(distinguishedName=CN=ldaptestUSER3,CN=Users," + self.base_dn + ")")
824         self.assertEquals(len(res), 1, "Could not find (dn=CN=ldaptestUSER3,CN=Users," + self.base_dn + ")")
825         self.assertEquals(str(res[0].dn), ("CN=ldaptestUSER3,CN=Users," + self.base_dn))
826         self.assertEquals(str(res[0]["cn"]), "ldaptestUSER3")
827         self.assertEquals(str(res[0]["name"]), "ldaptestUSER3")
828
829         # ensure we cannot add it again
830         try:
831             ldb.add({"dn": "cn=ldaptestuser3,cn=userS," + self.base_dn,
832                       "objectClass": ["person", "user"],
833                       "cn": "LDAPtestUSER3"})
834             self.fail()
835         except LdbError, (num, _):
836             self.assertEquals(num, ERR_ENTRY_ALREADY_EXISTS)
837
838         # rename back
839         ldb.rename("cn=ldaptestuser3,cn=users," + self.base_dn, "cn=ldaptestuser2,cn=users," + self.base_dn)
840
841         # ensure we cannot rename it twice
842         try:
843             ldb.rename("cn=ldaptestuser3,cn=users," + self.base_dn,
844                        "cn=ldaptestuser2,cn=users," + self.base_dn)
845             self.fail()
846         except LdbError, (num, _):
847             self.assertEquals(num, ERR_NO_SUCH_OBJECT)
848
849         # ensure can now use that name
850         ldb.add({"dn": "cn=ldaptestuser3,cn=users," + self.base_dn,
851                       "objectClass": ["person", "user"],
852                       "cn": "LDAPtestUSER3"})
853
854         # ensure we now cannot rename
855         try:
856             ldb.rename("cn=ldaptestuser2,cn=users," + self.base_dn, "cn=ldaptestuser3,cn=users," + self.base_dn)
857             self.fail()
858         except LdbError, (num, _):
859             self.assertEquals(num, ERR_ENTRY_ALREADY_EXISTS)
860         try:
861             ldb.rename("cn=ldaptestuser3,cn=users," + self.base_dn, "cn=ldaptestuser3,cn=configuration," + self.base_dn)
862             self.fail()
863         except LdbError, (num, _):
864             self.assertTrue(num in (71, 64))
865
866         ldb.rename("cn=ldaptestuser3,cn=users," + self.base_dn, "cn=ldaptestuser5,cn=users," + self.base_dn)
867
868         ldb.delete("cn=ldaptestuser5,cn=users," + self.base_dn)
869
870         self.delete_force(ldb, "cn=ldaptestgroup2,cn=users," + self.base_dn)
871
872         ldb.rename("cn=ldaptestgroup,cn=users," + self.base_dn, "cn=ldaptestgroup2,cn=users," + self.base_dn)
873
874         print "Testing subtree renames"
875
876         ldb.add({"dn": "cn=ldaptestcontainer," + self.base_dn,
877                  "objectClass": "container"})
878
879         ldb.add({"dn": "CN=ldaptestuser4,CN=ldaptestcontainer," + self.base_dn,
880                  "objectClass": ["person", "user"],
881                  "cn": "LDAPtestUSER4"})
882
883         ldb.modify_ldif("""
884 dn: cn=ldaptestgroup2,cn=users,""" + self.base_dn + """
885 changetype: modify
886 add: member
887 member: cn=ldaptestuser4,cn=ldaptestcontainer,""" + self.base_dn + """
888 member: cn=ldaptestcomputer,cn=computers,""" + self.base_dn + """
889 member: cn=ldaptestuser2,cn=users,""" + self.base_dn + """
890 """)
891
892         print "Testing ldb.rename of cn=ldaptestcontainer," + self.base_dn + " to cn=ldaptestcontainer2," + self.base_dn
893         ldb.rename("CN=ldaptestcontainer," + self.base_dn, "CN=ldaptestcontainer2," + self.base_dn)
894
895         print "Testing ldb.search for (&(cn=ldaptestuser4)(objectClass=user))"
896         res = ldb.search(expression="(&(cn=ldaptestuser4)(objectClass=user))")
897         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestuser4)(objectClass=user))")
898
899         print "Testing subtree ldb.search for (&(cn=ldaptestuser4)(objectClass=user)) in (just renamed from) cn=ldaptestcontainer," + self.base_dn
900         try:
901             res = ldb.search("cn=ldaptestcontainer," + self.base_dn,
902                     expression="(&(cn=ldaptestuser4)(objectClass=user))",
903                     scope=SCOPE_SUBTREE)
904             self.fail(res)
905         except LdbError, (num, _):
906             self.assertEquals(num, ERR_NO_SUCH_OBJECT)
907
908         print "Testing one-level ldb.search for (&(cn=ldaptestuser4)(objectClass=user)) in (just renamed from) cn=ldaptestcontainer," + self.base_dn
909         try:
910             res = ldb.search("cn=ldaptestcontainer," + self.base_dn,
911                     expression="(&(cn=ldaptestuser4)(objectClass=user))", scope=SCOPE_ONELEVEL)
912             self.fail()
913         except LdbError, (num, _):
914             self.assertEquals(num, ERR_NO_SUCH_OBJECT)
915
916         print "Testing ldb.search for (&(cn=ldaptestuser4)(objectClass=user)) in renamed container"
917         res = ldb.search("cn=ldaptestcontainer2," + self.base_dn, expression="(&(cn=ldaptestuser4)(objectClass=user))", scope=SCOPE_SUBTREE)
918         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestuser4)(objectClass=user)) under cn=ldaptestcontainer2," + self.base_dn)
919
920         self.assertEquals(str(res[0].dn), ("CN=ldaptestuser4,CN=ldaptestcontainer2," + self.base_dn))
921         self.assertEquals(res[0]["memberOf"][0].upper(), ("CN=ldaptestgroup2,CN=Users," + self.base_dn).upper())
922
923         time.sleep(4)
924
925         print "Testing ldb.search for (&(member=CN=ldaptestuser4,CN=ldaptestcontainer2," + self.base_dn + ")(objectclass=group)) to check subtree renames and linked attributes"
926         res = ldb.search(self.base_dn, expression="(&(member=CN=ldaptestuser4,CN=ldaptestcontainer2," + self.base_dn + ")(objectclass=group))", scope=SCOPE_SUBTREE)
927         self.assertEquals(len(res), 1, "Could not find (&(member=CN=ldaptestuser4,CN=ldaptestcontainer2," + self.base_dn + ")(objectclass=group)), perhaps linked attributes are not consistant with subtree renames?")
928
929         print "Testing ldb.rename (into itself) of cn=ldaptestcontainer2," + self.base_dn + " to cn=ldaptestcontainer,cn=ldaptestcontainer2," + self.base_dn
930         try:
931             ldb.rename("cn=ldaptestcontainer2," + self.base_dn, "cn=ldaptestcontainer,cn=ldaptestcontainer2," + self.base_dn)
932             self.fail()
933         except LdbError, (num, _):
934             self.assertEquals(num, ERR_UNWILLING_TO_PERFORM)
935
936         print "Testing ldb.rename (into non-existent container) of cn=ldaptestcontainer2," + self.base_dn + " to cn=ldaptestcontainer,cn=ldaptestcontainer3," + self.base_dn
937         try:
938             ldb.rename("cn=ldaptestcontainer2," + self.base_dn, "cn=ldaptestcontainer,cn=ldaptestcontainer3," + self.base_dn)
939             self.fail()
940         except LdbError, (num, _):
941             self.assertTrue(num in (ERR_UNWILLING_TO_PERFORM, ERR_OTHER))
942
943         print "Testing delete (should fail, not a leaf node) of renamed cn=ldaptestcontainer2," + self.base_dn
944         try:
945             ldb.delete("cn=ldaptestcontainer2," + self.base_dn)
946             self.fail()
947         except LdbError, (num, _):
948             self.assertEquals(num, ERR_NOT_ALLOWED_ON_NON_LEAF)
949
950         print "Testing base ldb.search for CN=ldaptestuser4,CN=ldaptestcontainer2," + self.base_dn
951         res = ldb.search(expression="(objectclass=*)", base=("CN=ldaptestuser4,CN=ldaptestcontainer2," + self.base_dn), scope=SCOPE_BASE)
952         self.assertEquals(len(res), 1)
953         res = ldb.search(expression="(cn=ldaptestuser40)", base=("CN=ldaptestuser4,CN=ldaptestcontainer2," + self.base_dn), scope=SCOPE_BASE)
954         self.assertEquals(len(res), 0)
955
956         print "Testing one-level ldb.search for (&(cn=ldaptestuser4)(objectClass=user)) in cn=ldaptestcontainer2," + self.base_dn
957         res = ldb.search(expression="(&(cn=ldaptestuser4)(objectClass=user))", base=("cn=ldaptestcontainer2," + self.base_dn), scope=SCOPE_ONELEVEL)
958         # FIXME: self.assertEquals(len(res), 0)
959
960         print "Testing one-level ldb.search for (&(cn=ldaptestuser4)(objectClass=user)) in cn=ldaptestcontainer2," + self.base_dn
961         res = ldb.search(expression="(&(cn=ldaptestuser4)(objectClass=user))", base=("cn=ldaptestcontainer2," + self.base_dn), scope=SCOPE_SUBTREE)
962         # FIXME: self.assertEquals(len(res), 0)
963
964         print "Testing delete of subtree renamed "+("CN=ldaptestuser4,CN=ldaptestcontainer2," + self.base_dn)
965         ldb.delete(("CN=ldaptestuser4,CN=ldaptestcontainer2," + self.base_dn))
966         print "Testing delete of renamed cn=ldaptestcontainer2," + self.base_dn
967         ldb.delete("cn=ldaptestcontainer2," + self.base_dn)
968
969         ldb.add({"dn": "cn=ldaptestutf8user èùéìòà ,cn=users," + self.base_dn, "objectClass": "user"})
970
971         ldb.add({"dn": "cn=ldaptestutf8user2  èùéìòà ,cn=users," + self.base_dn, "objectClass": "user"})
972
973         print "Testing ldb.search for (&(cn=ldaptestuser)(objectClass=user))"
974         res = ldb.search(expression="(&(cn=ldaptestuser)(objectClass=user))")
975         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestuser)(objectClass=user))")
976
977         self.assertEquals(str(res[0].dn), ("CN=ldaptestuser,CN=Users," + self.base_dn))
978         self.assertEquals(str(res[0]["cn"]), "ldaptestuser")
979         self.assertEquals(str(res[0]["name"]), "ldaptestuser")
980         self.assertEquals(set(res[0]["objectClass"]), set(["top", "person", "organizationalPerson", "user"]))
981         self.assertTrue("objectGUID" in res[0])
982         self.assertTrue("whenCreated" in res[0])
983         self.assertEquals(str(res[0]["objectCategory"]), ("CN=Person,CN=Schema,CN=Configuration," + self.base_dn))
984         self.assertEquals(int(res[0]["sAMAccountType"][0]), ATYPE_NORMAL_ACCOUNT)
985         self.assertEquals(int(res[0]["userAccountControl"][0]), UF_NORMAL_ACCOUNT | UF_PASSWD_NOTREQD | UF_ACCOUNTDISABLE)
986         self.assertEquals(res[0]["memberOf"][0].upper(), ("CN=ldaptestgroup2,CN=Users," + self.base_dn).upper())
987         self.assertEquals(len(res[0]["memberOf"]), 1)
988
989         print "Testing ldb.search for (&(cn=ldaptestuser)(objectCategory=cn=person,cn=schema,cn=configuration," + self.base_dn + "))"
990         res2 = ldb.search(expression="(&(cn=ldaptestuser)(objectCategory=cn=person,cn=schema,cn=configuration," + self.base_dn + "))")
991         self.assertEquals(len(res2), 1, "Could not find (&(cn=ldaptestuser)(objectCategory=cn=person,cn=schema,cn=configuration," + self.base_dn + "))")
992
993         self.assertEquals(res[0].dn, res2[0].dn)
994
995         print "Testing ldb.search for (&(cn=ldaptestuser)(objectCategory=PerSon))"
996         res3 = ldb.search(expression="(&(cn=ldaptestuser)(objectCategory=PerSon))")
997         self.assertEquals(len(res3), 1, "Could not find (&(cn=ldaptestuser)(objectCategory=PerSon)): matched %d" % len(res3))
998
999         self.assertEquals(res[0].dn, res3[0].dn)
1000
1001         if gc_ldb is not None:
1002             print "Testing ldb.search for (&(cn=ldaptestuser)(objectCategory=PerSon)) in Global Catalog"
1003             res3gc = gc_ldb.search(expression="(&(cn=ldaptestuser)(objectCategory=PerSon))")
1004             self.assertEquals(len(res3gc), 1)
1005
1006             self.assertEquals(res[0].dn, res3gc[0].dn)
1007
1008         print "Testing ldb.search for (&(cn=ldaptestuser)(objectCategory=PerSon)) in with 'phantom root' control"
1009
1010         res3control = gc_ldb.search(self.base_dn, expression="(&(cn=ldaptestuser)(objectCategory=PerSon))", scope=SCOPE_SUBTREE, attrs=["cn"], controls=["search_options:1:2"])
1011         self.assertEquals(len(res3control), 1, "Could not find (&(cn=ldaptestuser)(objectCategory=PerSon)) in Global Catalog")
1012
1013         self.assertEquals(res[0].dn, res3control[0].dn)
1014
1015         ldb.delete(res[0].dn)
1016
1017         print "Testing ldb.search for (&(cn=ldaptestcomputer)(objectClass=user))"
1018         res = ldb.search(expression="(&(cn=ldaptestcomputer)(objectClass=user))")
1019         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestuser)(objectClass=user))")
1020
1021         self.assertEquals(str(res[0].dn), ("CN=ldaptestcomputer,CN=Computers," + self.base_dn))
1022         self.assertEquals(str(res[0]["cn"]), "ldaptestcomputer")
1023         self.assertEquals(str(res[0]["name"]), "ldaptestcomputer")
1024         self.assertEquals(set(res[0]["objectClass"]), set(["top", "person", "organizationalPerson", "user", "computer"]))
1025         self.assertTrue("objectGUID" in res[0])
1026         self.assertTrue("whenCreated" in res[0])
1027         self.assertEquals(str(res[0]["objectCategory"]), ("CN=Computer,CN=Schema,CN=Configuration," + self.base_dn))
1028         self.assertEquals(int(res[0]["primaryGroupID"][0]), 513)
1029         self.assertEquals(int(res[0]["sAMAccountType"][0]), ATYPE_NORMAL_ACCOUNT)
1030         self.assertEquals(int(res[0]["userAccountControl"][0]), UF_NORMAL_ACCOUNT | UF_PASSWD_NOTREQD | UF_ACCOUNTDISABLE)
1031         self.assertEquals(res[0]["memberOf"][0].upper(), ("CN=ldaptestgroup2,CN=Users," + self.base_dn).upper())
1032         self.assertEquals(len(res[0]["memberOf"]), 1)
1033
1034         print "Testing ldb.search for (&(cn=ldaptestcomputer)(objectCategory=cn=computer,cn=schema,cn=configuration," + self.base_dn + "))"
1035         res2 = ldb.search(expression="(&(cn=ldaptestcomputer)(objectCategory=cn=computer,cn=schema,cn=configuration," + self.base_dn + "))")
1036         self.assertEquals(len(res2), 1, "Could not find (&(cn=ldaptestcomputer)(objectCategory=cn=computer,cn=schema,cn=configuration," + self.base_dn + "))")
1037
1038         self.assertEquals(res[0].dn, res2[0].dn)
1039
1040         if gc_ldb is not None:
1041             print "Testing ldb.search for (&(cn=ldaptestcomputer)(objectCategory=cn=computer,cn=schema,cn=configuration," + self.base_dn + ")) in Global Catlog"
1042             res2gc = gc_ldb.search(expression="(&(cn=ldaptestcomputer)(objectCategory=cn=computer,cn=schema,cn=configuration," + self.base_dn + "))")
1043             self.assertEquals(len(res2gc), 1, "Could not find (&(cn=ldaptestcomputer)(objectCategory=cn=computer,cn=schema,cn=configuration," + self.base_dn + ")) in Global Catlog")
1044
1045             self.assertEquals(res[0].dn, res2gc[0].dn)
1046
1047         print "Testing ldb.search for (&(cn=ldaptestcomputer)(objectCategory=compuTER))"
1048         res3 = ldb.search(expression="(&(cn=ldaptestcomputer)(objectCategory=compuTER))")
1049         self.assertEquals(len(res3), 1, "Could not find (&(cn=ldaptestcomputer)(objectCategory=compuTER))")
1050
1051         self.assertEquals(res[0].dn, res3[0].dn)
1052
1053         if gc_ldb is not None:
1054             print "Testing ldb.search for (&(cn=ldaptestcomputer)(objectCategory=compuTER)) in Global Catalog"
1055             res3gc = gc_ldb.search(expression="(&(cn=ldaptestcomputer)(objectCategory=compuTER))")
1056             self.assertEquals(len(res3gc), 1, "Could not find (&(cn=ldaptestcomputer)(objectCategory=compuTER)) in Global Catalog")
1057
1058             self.assertEquals(res[0].dn, res3gc[0].dn)
1059
1060         print "Testing ldb.search for (&(cn=ldaptestcomp*r)(objectCategory=compuTER))"
1061         res4 = ldb.search(expression="(&(cn=ldaptestcomp*r)(objectCategory=compuTER))")
1062         self.assertEquals(len(res4), 1, "Could not find (&(cn=ldaptestcomp*r)(objectCategory=compuTER))")
1063
1064         self.assertEquals(res[0].dn, res4[0].dn)
1065
1066         print "Testing ldb.search for (&(cn=ldaptestcomput*)(objectCategory=compuTER))"
1067         res5 = ldb.search(expression="(&(cn=ldaptestcomput*)(objectCategory=compuTER))")
1068         self.assertEquals(len(res5), 1, "Could not find (&(cn=ldaptestcomput*)(objectCategory=compuTER))")
1069
1070         self.assertEquals(res[0].dn, res5[0].dn)
1071
1072         print "Testing ldb.search for (&(cn=*daptestcomputer)(objectCategory=compuTER))"
1073         res6 = ldb.search(expression="(&(cn=*daptestcomputer)(objectCategory=compuTER))")
1074         self.assertEquals(len(res6), 1, "Could not find (&(cn=*daptestcomputer)(objectCategory=compuTER))")
1075
1076         self.assertEquals(res[0].dn, res6[0].dn)
1077
1078         ldb.delete("<GUID=" + ldb.schema_format_value("objectGUID", res[0]["objectGUID"][0]) + ">")
1079
1080         print "Testing ldb.search for (&(cn=ldaptest2computer)(objectClass=user))"
1081         res = ldb.search(expression="(&(cn=ldaptest2computer)(objectClass=user))")
1082         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptest2computer)(objectClass=user))")
1083
1084         self.assertEquals(str(res[0].dn), "CN=ldaptest2computer,CN=Computers," + self.base_dn)
1085         self.assertEquals(str(res[0]["cn"]), "ldaptest2computer")
1086         self.assertEquals(str(res[0]["name"]), "ldaptest2computer")
1087         self.assertEquals(list(res[0]["objectClass"]), ["top", "person", "organizationalPerson", "user", "computer"])
1088         self.assertTrue("objectGUID" in res[0])
1089         self.assertTrue("whenCreated" in res[0])
1090         self.assertEquals(res[0]["objectCategory"][0], "CN=Computer,CN=Schema,CN=Configuration," + self.base_dn)
1091         self.assertEquals(int(res[0]["sAMAccountType"][0]), ATYPE_WORKSTATION_TRUST)
1092         self.assertEquals(int(res[0]["userAccountControl"][0]), UF_WORKSTATION_TRUST_ACCOUNT)
1093
1094         ldb.delete("<SID=" + ldb.schema_format_value("objectSID", res[0]["objectSID"][0]) + ">")
1095
1096         attrs = ["cn", "name", "objectClass", "objectGUID", "objectSID", "whenCreated", "nTSecurityDescriptor", "memberOf", "allowedAttributes", "allowedAttributesEffective"]
1097         print "Testing ldb.search for (&(cn=ldaptestUSer2)(objectClass=user))"
1098         res_user = ldb.search(self.base_dn, expression="(&(cn=ldaptestUSer2)(objectClass=user))", scope=SCOPE_SUBTREE, attrs=attrs)
1099         self.assertEquals(len(res_user), 1, "Could not find (&(cn=ldaptestUSer2)(objectClass=user))")
1100
1101         self.assertEquals(str(res_user[0].dn), ("CN=ldaptestuser2,CN=Users," + self.base_dn))
1102         self.assertEquals(str(res_user[0]["cn"]), "ldaptestuser2")
1103         self.assertEquals(str(res_user[0]["name"]), "ldaptestuser2")
1104         self.assertEquals(list(res_user[0]["objectClass"]), ["top", "person", "organizationalPerson", "user"])
1105         self.assertTrue("objectSid" in res_user[0])
1106         self.assertTrue("objectGUID" in res_user[0])
1107         self.assertTrue("whenCreated" in res_user[0])
1108         self.assertTrue("nTSecurityDescriptor" in res_user[0])
1109         self.assertTrue("allowedAttributes" in res_user[0])
1110         self.assertTrue("allowedAttributesEffective" in res_user[0])
1111         self.assertEquals(res_user[0]["memberOf"][0].upper(), ("CN=ldaptestgroup2,CN=Users," + self.base_dn).upper())
1112
1113         ldaptestuser2_sid = res_user[0]["objectSid"][0]
1114         ldaptestuser2_guid = res_user[0]["objectGUID"][0]
1115
1116         attrs = ["cn", "name", "objectClass", "objectGUID", "objectSID", "whenCreated", "nTSecurityDescriptor", "member", "allowedAttributes", "allowedAttributesEffective"]
1117         print "Testing ldb.search for (&(cn=ldaptestgroup2)(objectClass=group))"
1118         res = ldb.search(self.base_dn, expression="(&(cn=ldaptestgroup2)(objectClass=group))", scope=SCOPE_SUBTREE, attrs=attrs)
1119         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestgroup2)(objectClass=group))")
1120
1121         self.assertEquals(str(res[0].dn), ("CN=ldaptestgroup2,CN=Users," + self.base_dn))
1122         self.assertEquals(str(res[0]["cn"]), "ldaptestgroup2")
1123         self.assertEquals(str(res[0]["name"]), "ldaptestgroup2")
1124         self.assertEquals(list(res[0]["objectClass"]), ["top", "group"])
1125         self.assertTrue("objectGUID" in res[0])
1126         self.assertTrue("objectSid" in res[0])
1127         self.assertTrue("whenCreated" in res[0])
1128         self.assertTrue("nTSecurityDescriptor" in res[0])
1129         self.assertTrue("allowedAttributes" in res[0])
1130         self.assertTrue("allowedAttributesEffective" in res[0])
1131         memberUP = []
1132         for m in res[0]["member"]:
1133             memberUP.append(m.upper())
1134         self.assertTrue(("CN=ldaptestuser2,CN=Users," + self.base_dn).upper() in memberUP)
1135
1136         res = ldb.search(self.base_dn, expression="(&(cn=ldaptestgroup2)(objectClass=group))", scope=SCOPE_SUBTREE, attrs=attrs, controls=["extended_dn:1:1"])
1137         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestgroup2)(objectClass=group))")
1138
1139         print res[0]["member"]
1140         memberUP = []
1141         for m in res[0]["member"]:
1142             memberUP.append(m.upper())
1143         print ("<GUID=" + ldb.schema_format_value("objectGUID", ldaptestuser2_guid) + ">;<SID=" + ldb.schema_format_value("objectSid", ldaptestuser2_sid) + ">;CN=ldaptestuser2,CN=Users," + self.base_dn).upper()
1144
1145         self.assertTrue(("<GUID=" + ldb.schema_format_value("objectGUID", ldaptestuser2_guid) + ">;<SID=" + ldb.schema_format_value("objectSid", ldaptestuser2_sid) + ">;CN=ldaptestuser2,CN=Users," + self.base_dn).upper() in memberUP)
1146
1147         print "Testing Linked attribute behaviours"
1148         ldb.modify_ldif("""
1149 dn: cn=ldaptestgroup2,cn=users,""" + self.base_dn + """
1150 changetype: modify
1151 replace: member
1152 member: CN=ldaptestuser2,CN=Users,""" + self.base_dn + """
1153 member: CN=ldaptestutf8user èùéìòà,CN=Users,""" + self.base_dn + """
1154 """)
1155
1156         ldb.modify_ldif("""
1157 dn: <GUID=""" + ldb.schema_format_value("objectGUID", res[0]["objectGUID"][0]) + """>
1158 changetype: modify
1159 replace: member
1160 member: CN=ldaptestutf8user èùéìòà,CN=Users,""" + self.base_dn + """
1161 """)
1162
1163         ldb.modify_ldif("""
1164 dn: <SID=""" + ldb.schema_format_value("objectSid", res[0]["objectSid"][0]) + """>
1165 changetype: modify
1166 delete: member
1167 """)
1168
1169         ldb.modify_ldif("""
1170 dn: cn=ldaptestgroup2,cn=users,""" + self.base_dn + """
1171 changetype: modify
1172 add: member
1173 member: <GUID=""" + ldb.schema_format_value("objectGUID", res[0]["objectGUID"][0]) + """>
1174 member: CN=ldaptestutf8user èùéìòà,CN=Users,""" + self.base_dn + """
1175 """)
1176
1177         ldb.modify_ldif("""
1178 dn: cn=ldaptestgroup2,cn=users,""" + self.base_dn + """
1179 changetype: modify
1180 replace: member
1181 """)
1182
1183         ldb.modify_ldif("""
1184 dn: cn=ldaptestgroup2,cn=users,""" + self.base_dn + """
1185 changetype: modify
1186 add: member
1187 member: <SID=""" + ldb.schema_format_value("objectSid", res_user[0]["objectSid"][0]) + """>
1188 member: CN=ldaptestutf8user èùéìòà,CN=Users,""" + self.base_dn + """
1189 """)
1190
1191         ldb.modify_ldif("""
1192 dn: cn=ldaptestgroup2,cn=users,""" + self.base_dn + """
1193 changetype: modify
1194 delete: member
1195 member: CN=ldaptestutf8user èùéìòà,CN=Users,""" + self.base_dn + """
1196 """)
1197
1198         res = ldb.search(self.base_dn, expression="(&(cn=ldaptestgroup2)(objectClass=group))", scope=SCOPE_SUBTREE, attrs=attrs)
1199         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestgroup2)(objectClass=group))")
1200
1201         self.assertEquals(str(res[0].dn), ("CN=ldaptestgroup2,CN=Users," + self.base_dn))
1202         self.assertEquals(res[0]["member"][0], ("CN=ldaptestuser2,CN=Users," + self.base_dn))
1203         self.assertEquals(len(res[0]["member"]), 1)
1204
1205         ldb.delete(("CN=ldaptestuser2,CN=Users," + self.base_dn))
1206
1207         time.sleep(4)
1208
1209         attrs = ["cn", "name", "objectClass", "objectGUID", "whenCreated", "nTSecurityDescriptor", "member"]
1210         print "Testing ldb.search for (&(cn=ldaptestgroup2)(objectClass=group)) to check linked delete"
1211         res = ldb.search(self.base_dn, expression="(&(cn=ldaptestgroup2)(objectClass=group))", scope=SCOPE_SUBTREE, attrs=attrs)
1212         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestgroup2)(objectClass=group)) to check linked delete")
1213
1214         self.assertEquals(str(res[0].dn), ("CN=ldaptestgroup2,CN=Users," + self.base_dn))
1215         self.assertTrue("member" not in res[0])
1216
1217         print "Testing ldb.search for (&(cn=ldaptestutf8user ÈÙÉÌÒÀ)(objectClass=user))"
1218         res = ldb.search(expression="(&(cn=ldaptestutf8user ÈÙÉÌÒÀ)(objectClass=user))")
1219         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestutf8user ÈÙÉÌÒÀ)(objectClass=user))")
1220
1221         self.assertEquals(str(res[0].dn), ("CN=ldaptestutf8user èùéìòà,CN=Users," + self.base_dn))
1222         self.assertEquals(str(res[0]["cn"]), "ldaptestutf8user èùéìòà")
1223         self.assertEquals(str(res[0]["name"]), "ldaptestutf8user èùéìòà")
1224         self.assertEquals(list(res[0]["objectClass"]), ["top", "person", "organizationalPerson", "user"])
1225         self.assertTrue("objectGUID" in res[0])
1226         self.assertTrue("whenCreated" in res[0])
1227
1228         ldb.delete(res[0].dn)
1229
1230         print "Testing ldb.search for (&(cn=ldaptestutf8user2*)(objectClass=user))"
1231         res = ldb.search(expression="(&(cn=ldaptestutf8user2*)(objectClass=user))")
1232         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestutf8user2*)(objectClass=user))")
1233
1234         ldb.delete(res[0].dn)
1235
1236         ldb.delete(("CN=ldaptestgroup2,CN=Users," + self.base_dn))
1237
1238         print "Testing ldb.search for (&(cn=ldaptestutf8user2 ÈÙÉÌÒÀ)(objectClass=user))"
1239         res = ldb.search(expression="(&(cn=ldaptestutf8user ÈÙÉÌÒÀ)(objectClass=user))")
1240
1241         #FIXME: self.assert len(res) == 1, "Could not find (expect space collapse, win2k3 fails) (&(cn=ldaptestutf8user2 ÈÙÉÌÒÀ)(objectClass=user))"
1242
1243         print "Testing that we can't get at the configuration DN from the main search base"
1244         res = ldb.search(self.base_dn, expression="objectClass=crossRef", scope=SCOPE_SUBTREE, attrs=["cn"])
1245         self.assertEquals(len(res), 0)
1246
1247         print "Testing that we can get at the configuration DN from the main search base on the LDAP port with the 'phantom root' search_options control"
1248         res = ldb.search(self.base_dn, expression="objectClass=crossRef", scope=SCOPE_SUBTREE, attrs=["cn"], controls=["search_options:1:2"])
1249         self.assertTrue(len(res) > 0)
1250
1251         if gc_ldb is not None:
1252             print "Testing that we can get at the configuration DN from the main search base on the GC port with the search_options control == 0"
1253
1254             res = gc_ldb.search(self.base_dn, expression="objectClass=crossRef", scope=SCOPE_SUBTREE, attrs=["cn"], controls=["search_options:1:0"])
1255             self.assertTrue(len(res) > 0)
1256
1257             print "Testing that we do find configuration elements in the global catlog"
1258             res = gc_ldb.search(self.base_dn, expression="objectClass=crossRef", scope=SCOPE_SUBTREE, attrs=["cn"])
1259             self.assertTrue(len(res) > 0)
1260
1261             print "Testing that we do find configuration elements and user elements at the same time"
1262             res = gc_ldb.search(self.base_dn, expression="(|(objectClass=crossRef)(objectClass=person))", scope=SCOPE_SUBTREE, attrs=["cn"])
1263             self.assertTrue(len(res) > 0)
1264
1265             print "Testing that we do find configuration elements in the global catlog, with the configuration basedn"
1266             res = gc_ldb.search(self.configuration_dn, expression="objectClass=crossRef", scope=SCOPE_SUBTREE, attrs=["cn"])
1267             self.assertTrue(len(res) > 0)
1268
1269         print "Testing that we can get at the configuration DN on the main LDAP port"
1270         res = ldb.search(self.configuration_dn, expression="objectClass=crossRef", scope=SCOPE_SUBTREE, attrs=["cn"])
1271         self.assertTrue(len(res) > 0)
1272
1273         print "Testing objectCategory canonacolisation"
1274         res = ldb.search(self.configuration_dn, expression="objectCategory=ntDsDSA", scope=SCOPE_SUBTREE, attrs=["cn"])
1275         self.assertTrue(len(res) > 0, "Didn't find any records with objectCategory=ntDsDSA")
1276         self.assertTrue(len(res) != 0)
1277
1278         res = ldb.search(self.configuration_dn, expression="objectCategory=CN=ntDs-DSA," + self.schema_dn, scope=SCOPE_SUBTREE, attrs=["cn"])
1279         self.assertTrue(len(res) > 0, "Didn't find any records with objectCategory=CN=ntDs-DSA," + self.schema_dn)
1280         self.assertTrue(len(res) != 0)
1281
1282         print "Testing objectClass attribute order on "+ self.base_dn
1283         res = ldb.search(expression="objectClass=domain", base=self.base_dn,
1284                          scope=SCOPE_BASE, attrs=["objectClass"])
1285         self.assertEquals(len(res), 1)
1286
1287         self.assertEquals(list(res[0]["objectClass"]), ["top", "domain", "domainDNS"])
1288
1289     #  check enumeration
1290
1291         print "Testing ldb.search for objectCategory=person"
1292         res = ldb.search(self.base_dn, expression="objectCategory=person", scope=SCOPE_SUBTREE, attrs=["cn"])
1293         self.assertTrue(len(res) > 0)
1294
1295         print "Testing ldb.search for objectCategory=person with domain scope control"
1296         res = ldb.search(self.base_dn, expression="objectCategory=person", scope=SCOPE_SUBTREE, attrs=["cn"], controls=["domain_scope:1"])
1297         self.assertTrue(len(res) > 0)
1298
1299         print "Testing ldb.search for objectCategory=user"
1300         res = ldb.search(self.base_dn, expression="objectCategory=user", scope=SCOPE_SUBTREE, attrs=["cn"])
1301         self.assertTrue(len(res) > 0)
1302
1303         print "Testing ldb.search for objectCategory=user with domain scope control"
1304         res = ldb.search(self.base_dn, expression="objectCategory=user", scope=SCOPE_SUBTREE, attrs=["cn"], controls=["domain_scope:1"])
1305         self.assertTrue(len(res) > 0)
1306
1307         print "Testing ldb.search for objectCategory=group"
1308         res = ldb.search(self.base_dn, expression="objectCategory=group", scope=SCOPE_SUBTREE, attrs=["cn"])
1309         self.assertTrue(len(res) > 0)
1310
1311         print "Testing ldb.search for objectCategory=group with domain scope control"
1312         res = ldb.search(self.base_dn, expression="objectCategory=group", scope=SCOPE_SUBTREE, attrs=["cn"], controls=["domain_scope:1"])
1313         self.assertTrue(len(res) > 0)
1314
1315         self.delete_force(self.ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
1316         self.delete_force(self.ldb, "cn=ldaptestuser2,cn=users," + self.base_dn)
1317         self.delete_force(self.ldb, "cn=ldaptestuser3,cn=users," + self.base_dn)
1318         self.delete_force(self.ldb, "cn=ldaptestuser4,cn=users," + self.base_dn)
1319         self.delete_force(self.ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
1320         self.delete_force(self.ldb, "cn=ldaptestgroup2,cn=users," + self.base_dn)
1321         self.delete_force(self.ldb, "cn=ldaptestcomputer,cn=computers," + self.base_dn)
1322         self.delete_force(self.ldb, "cn=ldaptest2computer,cn=computers," + self.base_dn)
1323         self.delete_force(self.ldb, "cn=ldaptestcomputer3,cn=computers," + self.base_dn)
1324         self.delete_force(self.ldb, "cn=ldaptestutf8user èùéìòà ,cn=users," + self.base_dn)
1325         self.delete_force(self.ldb, "cn=ldaptestutf8user2  èùéìòà ,cn=users," + self.base_dn)
1326         self.delete_force(self.ldb, "cn=ldaptestcontainer," + self.base_dn)
1327         self.delete_force(self.ldb, "cn=ldaptestcontainer2," + self.base_dn)
1328
1329     def test_security_descriptor_add(self):
1330         """ Testing ldb.add_ldif() for nTSecurityDescriptor """
1331         user_name = "testdescriptoruser1"
1332         user_dn = "CN=%s,CN=Users,%s" % (user_name, self.base_dn)
1333         #
1334         # Test add_ldif() with SDDL security descriptor input
1335         #
1336         self.delete_force(self.ldb, user_dn)
1337         try:
1338             sddl = "O:DUG:DUD:PAI(A;;RPWP;;;AU)S:PAI"
1339             self.ldb.add_ldif("""
1340 dn: """ + user_dn + """
1341 objectclass: user
1342 sAMAccountName: """ + user_name + """
1343 nTSecurityDescriptor: """ + sddl)
1344             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1345             desc = res[0]["nTSecurityDescriptor"][0]
1346             desc = ndr_unpack( security.descriptor, desc )
1347             desc_sddl = desc.as_sddl( self.domain_sid )
1348             self.assertEqual(desc_sddl, sddl)
1349         finally:
1350             self.delete_force(self.ldb, user_dn)
1351         #
1352         # Test add_ldif() with BASE64 security descriptor
1353         #
1354         try:
1355             sddl = "O:DUG:DUD:PAI(A;;RPWP;;;AU)S:PAI"
1356             desc = security.descriptor.from_sddl(sddl, self.domain_sid)
1357             desc_binary = ndr_pack(desc)
1358             desc_base64 = base64.b64encode(desc_binary)
1359             self.ldb.add_ldif("""
1360 dn: """ + user_dn + """
1361 objectclass: user
1362 sAMAccountName: """ + user_name + """
1363 nTSecurityDescriptor:: """ + desc_base64)
1364             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1365             desc = res[0]["nTSecurityDescriptor"][0]
1366             desc = ndr_unpack(security.descriptor, desc)
1367             desc_sddl = desc.as_sddl(self.domain_sid)
1368             self.assertEqual(desc_sddl, sddl)
1369         finally:
1370             self.delete_force(self.ldb, user_dn)
1371
1372     def test_security_descriptor_add_neg(self):
1373         """Test add_ldif() with BASE64 security descriptor input using WRONG domain SID
1374             Negative test
1375         """
1376         user_name = "testdescriptoruser1"
1377         user_dn = "CN=%s,CN=Users,%s" % (user_name, self.base_dn)
1378         self.delete_force(self.ldb, user_dn)
1379         try:
1380             sddl = "O:DUG:DUD:PAI(A;;RPWP;;;AU)S:PAI"
1381             desc = security.descriptor.from_sddl(sddl, security.dom_sid('S-1-5-21'))
1382             desc_base64 = base64.b64encode( ndr_pack(desc) )
1383             self.ldb.add_ldif("""
1384 dn: """ + user_dn + """
1385 objectclass: user
1386 sAMAccountName: """ + user_name + """
1387 nTSecurityDescriptor:: """ + desc_base64)
1388             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1389             print res
1390             self.assertRaises(KeyError, lambda: res[0]["nTSecurityDescriptor"])
1391         finally:
1392             self.delete_force(self.ldb, user_dn)
1393
1394     def test_security_descriptor_modify(self):
1395         """ Testing ldb.modify_ldif() for nTSecurityDescriptor """
1396         user_name = "testdescriptoruser2"
1397         user_dn = "CN=%s,CN=Users,%s" % (user_name, self.base_dn)
1398         #
1399         # Delete user object and test modify_ldif() with SDDL security descriptor input
1400         # Add ACE to the original descriptor test
1401         #
1402         try:
1403             self.delete_force(self.ldb, user_dn)
1404             self.ldb.add_ldif("""
1405 dn: """ + user_dn + """
1406 objectclass: user
1407 sAMAccountName: """ + user_name)
1408             # Modify descriptor
1409             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1410             desc = res[0]["nTSecurityDescriptor"][0]
1411             desc = ndr_unpack(security.descriptor, desc)
1412             desc_sddl = desc.as_sddl(self.domain_sid)
1413             sddl = desc_sddl[:desc_sddl.find("(")] + "(A;;RPWP;;;AU)" + desc_sddl[desc_sddl.find("("):]
1414             mod = """
1415 dn: """ + user_dn + """
1416 changetype: modify
1417 replace: nTSecurityDescriptor
1418 nTSecurityDescriptor: """ + sddl
1419             self.ldb.modify_ldif(mod)
1420             # Read modified descriptor
1421             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1422             desc = res[0]["nTSecurityDescriptor"][0]
1423             desc = ndr_unpack(security.descriptor, desc)
1424             desc_sddl = desc.as_sddl(self.domain_sid)
1425             self.assertEqual(desc_sddl, sddl)
1426         finally:
1427             self.delete_force(self.ldb, user_dn)
1428         #
1429         # Test modify_ldif() with SDDL security descriptor input
1430         # New desctiptor test
1431         #
1432         try:
1433             self.ldb.add_ldif("""
1434 dn: """ + user_dn + """
1435 objectclass: user
1436 sAMAccountName: """ + user_name)
1437             # Modify descriptor
1438             sddl = "O:DUG:DUD:PAI(A;;RPWP;;;AU)S:PAI"
1439             mod = """
1440 dn: """ + user_dn + """
1441 changetype: modify
1442 replace: nTSecurityDescriptor
1443 nTSecurityDescriptor: """ + sddl
1444             self.ldb.modify_ldif(mod)
1445             # Read modified descriptor
1446             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1447             desc = res[0]["nTSecurityDescriptor"][0]
1448             desc = ndr_unpack(security.descriptor, desc)
1449             desc_sddl = desc.as_sddl(self.domain_sid)
1450             self.assertEqual(desc_sddl, sddl)
1451         finally:
1452             self.delete_force(self.ldb, user_dn)
1453         #
1454         # Test modify_ldif() with BASE64 security descriptor input
1455         # Add ACE to the original descriptor test
1456         #
1457         try:
1458             self.ldb.add_ldif("""
1459 dn: """ + user_dn + """
1460 objectclass: user
1461 sAMAccountName: """ + user_name)
1462             # Modify descriptor
1463             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1464             desc = res[0]["nTSecurityDescriptor"][0]
1465             desc = ndr_unpack(security.descriptor, desc)
1466             desc_sddl = desc.as_sddl(self.domain_sid)
1467             sddl = desc_sddl[:desc_sddl.find("(")] + "(A;;RPWP;;;AU)" + desc_sddl[desc_sddl.find("("):]
1468             desc = security.descriptor.from_sddl(sddl, self.domain_sid)
1469             desc_base64 = base64.b64encode(ndr_pack(desc))
1470             mod = """
1471 dn: """ + user_dn + """
1472 changetype: modify
1473 replace: nTSecurityDescriptor
1474 nTSecurityDescriptor:: """ + desc_base64
1475             self.ldb.modify_ldif(mod)
1476             # Read modified descriptor
1477             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1478             desc = res[0]["nTSecurityDescriptor"][0]
1479             desc = ndr_unpack(security.descriptor, desc)
1480             desc_sddl = desc.as_sddl(self.domain_sid)
1481             self.assertEqual(desc_sddl, sddl)
1482         finally:
1483             self.delete_force(self.ldb, user_dn)
1484         #
1485         # Test modify_ldif() with BASE64 security descriptor input
1486         # New descriptor test
1487         #
1488         try:
1489             self.delete_force(self.ldb, user_dn)
1490             self.ldb.add_ldif("""
1491 dn: """ + user_dn + """
1492 objectclass: user
1493 sAMAccountName: """ + user_name)
1494             # Modify descriptor
1495             sddl = "O:DUG:DUD:PAI(A;;RPWP;;;AU)S:PAI"
1496             desc = security.descriptor.from_sddl(sddl, self.domain_sid)
1497             desc_base64 = base64.b64encode(ndr_pack(desc))
1498             mod = """
1499 dn: """ + user_dn + """
1500 changetype: modify
1501 replace: nTSecurityDescriptor
1502 nTSecurityDescriptor:: """ + desc_base64
1503             self.ldb.modify_ldif(mod)
1504             # Read modified descriptor
1505             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1506             desc = res[0]["nTSecurityDescriptor"][0]
1507             desc = ndr_unpack(security.descriptor, desc)
1508             desc_sddl = desc.as_sddl(self.domain_sid)
1509             self.assertEqual(desc_sddl, sddl)
1510         finally:
1511             self.delete_force(self.ldb, user_dn)
1512
1513 class BaseDnTests(unittest.TestCase):
1514     def setUp(self):
1515         self.ldb = ldb
1516
1517     def test_rootdse_attrs(self):
1518         """Testing for all rootDSE attributes"""
1519         res = self.ldb.search(scope=SCOPE_BASE, attrs=[])
1520         self.assertEquals(len(res), 1)
1521
1522     def test_highestcommittedusn(self):
1523         """Testing for highestCommittedUSN"""
1524         res = self.ldb.search("", scope=SCOPE_BASE, attrs=["highestCommittedUSN"])
1525         self.assertEquals(len(res), 1)
1526         self.assertTrue(int(res[0]["highestCommittedUSN"][0]) != 0)
1527
1528     def test_netlogon(self):
1529         """Testing for netlogon via LDAP"""
1530         res = self.ldb.search("", scope=SCOPE_BASE, attrs=["netlogon"])
1531         self.assertEquals(len(res), 0)
1532
1533     def test_netlogon_highestcommitted_usn(self):
1534         """Testing for netlogon and highestCommittedUSN via LDAP"""
1535         res = self.ldb.search("", scope=SCOPE_BASE,
1536                 attrs=["netlogon", "highestCommittedUSN"])
1537         self.assertEquals(len(res), 0)
1538
1539 class SchemaTests(unittest.TestCase):
1540     def delete_force(self, ldb, dn):
1541         try:
1542             ldb.delete(dn)
1543         except LdbError, (num, _):
1544             self.assertEquals(num, ERR_NO_SUCH_OBJECT)
1545
1546     def find_schemadn(self, ldb):
1547         res = ldb.search(base="", expression="", scope=SCOPE_BASE, attrs=["schemaNamingContext"])
1548         self.assertEquals(len(res), 1)
1549         return res[0]["schemaNamingContext"][0]
1550
1551     def find_basedn(self, ldb):
1552         res = ldb.search(base="", expression="", scope=SCOPE_BASE,
1553                          attrs=["defaultNamingContext"])
1554         self.assertEquals(len(res), 1)
1555         return res[0]["defaultNamingContext"][0]
1556
1557     def setUp(self):
1558         self.ldb = ldb
1559         self.schema_dn = self.find_schemadn(ldb)
1560         self.base_dn = self.find_basedn(ldb)
1561
1562     def test_generated_schema(self):
1563         """Testing we can read the generated schema via LDAP"""
1564         res = self.ldb.search("cn=aggregate,"+self.schema_dn, scope=SCOPE_BASE,
1565                 attrs=["objectClasses", "attributeTypes", "dITContentRules"])
1566         self.assertEquals(len(res), 1)
1567         self.assertTrue("dITContentRules" in res[0])
1568         self.assertTrue("objectClasses" in res[0])
1569         self.assertTrue("attributeTypes" in res[0])
1570
1571     def test_generated_schema_is_operational(self):
1572         """Testing we don't get the generated schema via LDAP by default"""
1573         res = self.ldb.search("cn=aggregate,"+self.schema_dn, scope=SCOPE_BASE,
1574                 attrs=["*"])
1575         self.assertEquals(len(res), 1)
1576         self.assertFalse("dITContentRules" in res[0])
1577         self.assertFalse("objectClasses" in res[0])
1578         self.assertFalse("attributeTypes" in res[0])
1579
1580     def test_schemaUpdateNow(self):
1581         """Testing schemaUpdateNow"""
1582         class_name = "test-class" + time.strftime("%s", time.gmtime())
1583         class_ldap_display_name = class_name.replace("-", "")
1584         object_name = "obj" + time.strftime("%s", time.gmtime())
1585
1586         ldif = """
1587 dn: CN=%s,%s""" % (class_name, self.schema_dn) + """
1588 lDAPDisplayName: """ + class_ldap_display_name + """
1589 objectClass: top
1590 objectClass: classSchema
1591 adminDescription: """ + class_name + """
1592 adminDisplayName: """ + class_name + """
1593 cn: """ + class_name + """
1594 objectCategory: CN=Class-Schema,""" + self.schema_dn + """
1595 defaultObjectCategory: CN=%s,%s""" % (class_name, self.schema_dn) + """
1596 distinguishedName: CN=%s,%s""" % (class_name, self.schema_dn) + """
1597 governsID: 1.2.840.""" + str(random.randint(1,100000)) + """.1.5.9939
1598 instanceType: 4
1599 name: """ + class_name + """
1600 objectClassCategory: 1
1601 subClassOf: organizationalPerson
1602 systemFlags: 16
1603 rDNAttID: cn
1604 systemMustContain: cn
1605 systemOnly: FALSE
1606 """
1607         self.ldb.add_ldif(ldif)
1608         ldif = """
1609 dn:
1610 changetype: modify
1611 add: schemaUpdateNow
1612 schemaUpdateNow: 1
1613 """
1614         self.ldb.modify_ldif(ldif)
1615         ldif = """
1616 dn: CN=%s,CN=Users,%s"""% (object_name, self.base_dn) + """
1617 objectClass: organizationalPerson
1618 objectClass: person
1619 objectClass: """ + class_ldap_display_name + """
1620 objectClass: top
1621 cn: """ + object_name + """
1622 instanceType: 4
1623 objectCategory: CN=%s,%s"""% (class_name, self.schema_dn) + """
1624 distinguishedName: CN=%s,CN=Users,%s"""% (object_name, self.base_dn) + """
1625 name: """ + object_name + """
1626 """
1627         self.ldb.add_ldif(ldif)
1628         # Search for created objectClass
1629         res = []
1630         res = self.ldb.search("cn=%s,%s" % (class_name, self.schema_dn), scope=SCOPE_BASE, attrs=["*"])
1631         self.assertNotEqual(res, [])
1632
1633         res = []
1634         res = self.ldb.search("cn=%s,cn=Users,%s" % (object_name, self.base_dn), scope=SCOPE_BASE, attrs=["*"])
1635         self.assertNotEqual(res, [])
1636         # Delete the object
1637         self.delete_force(self.ldb, "cn=%s,cn=Users,%s" % (object_name, self.base_dn))
1638
1639 if not "://" in host:
1640     host = "ldap://%s" % host
1641
1642 ldb = Ldb(host, credentials=creds, session_info=system_session(), lp=lp)
1643 gc_ldb = Ldb("%s:3268" % host, credentials=creds,
1644              session_info=system_session(), lp=lp)
1645
1646 runner = SubunitTestRunner()
1647 rc = 0
1648 if not runner.run(unittest.makeSuite(BaseDnTests)).wasSuccessful():
1649     rc = 1
1650 if not runner.run(unittest.makeSuite(BasicTests)).wasSuccessful():
1651     rc = 1
1652 if not runner.run(unittest.makeSuite(SchemaTests)).wasSuccessful():
1653     rc = 1
1654 sys.exit(rc)