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