s4-ldb: improve detection of whether the server has a GC port
[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         if gc_ldb is not None:
1370             res3control = gc_ldb.search(self.base_dn, expression="(&(cn=ldaptestuser)(objectCategory=PerSon))", scope=SCOPE_SUBTREE, attrs=["cn"], controls=["search_options:1:2"])
1371             self.assertEquals(len(res3control), 1, "Could not find (&(cn=ldaptestuser)(objectCategory=PerSon)) in Global Catalog")
1372
1373             self.assertEquals(res[0].dn, res3control[0].dn)
1374
1375         ldb.delete(res[0].dn)
1376
1377         print "Testing ldb.search for (&(cn=ldaptestcomputer)(objectClass=user))"
1378         res = ldb.search(expression="(&(cn=ldaptestcomputer)(objectClass=user))")
1379         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestuser)(objectClass=user))")
1380
1381         self.assertEquals(str(res[0].dn), ("CN=ldaptestcomputer,CN=Computers," + self.base_dn))
1382         self.assertEquals(str(res[0]["cn"]), "ldaptestcomputer")
1383         self.assertEquals(str(res[0]["name"]), "ldaptestcomputer")
1384         self.assertEquals(set(res[0]["objectClass"]), set(["top", "person", "organizationalPerson", "user", "computer"]))
1385         self.assertTrue("objectGUID" in res[0])
1386         self.assertTrue("whenCreated" in res[0])
1387         self.assertEquals(str(res[0]["objectCategory"]), ("CN=Computer,CN=Schema,CN=Configuration," + self.base_dn))
1388         self.assertEquals(int(res[0]["primaryGroupID"][0]), 513)
1389         self.assertEquals(int(res[0]["sAMAccountType"][0]), ATYPE_NORMAL_ACCOUNT)
1390         self.assertEquals(int(res[0]["userAccountControl"][0]), UF_NORMAL_ACCOUNT | UF_PASSWD_NOTREQD | UF_ACCOUNTDISABLE)
1391         self.assertEquals(res[0]["memberOf"][0].upper(), ("CN=ldaptestgroup2,CN=Users," + self.base_dn).upper())
1392         self.assertEquals(len(res[0]["memberOf"]), 1)
1393
1394         print "Testing ldb.search for (&(cn=ldaptestcomputer)(objectCategory=cn=computer,cn=schema,cn=configuration," + self.base_dn + "))"
1395         res2 = ldb.search(expression="(&(cn=ldaptestcomputer)(objectCategory=cn=computer,cn=schema,cn=configuration," + self.base_dn + "))")
1396         self.assertEquals(len(res2), 1, "Could not find (&(cn=ldaptestcomputer)(objectCategory=cn=computer,cn=schema,cn=configuration," + self.base_dn + "))")
1397
1398         self.assertEquals(res[0].dn, res2[0].dn)
1399
1400         if gc_ldb is not None:
1401             print "Testing ldb.search for (&(cn=ldaptestcomputer)(objectCategory=cn=computer,cn=schema,cn=configuration," + self.base_dn + ")) in Global Catlog"
1402             res2gc = gc_ldb.search(expression="(&(cn=ldaptestcomputer)(objectCategory=cn=computer,cn=schema,cn=configuration," + self.base_dn + "))")
1403             self.assertEquals(len(res2gc), 1, "Could not find (&(cn=ldaptestcomputer)(objectCategory=cn=computer,cn=schema,cn=configuration," + self.base_dn + ")) in Global Catlog")
1404
1405             self.assertEquals(res[0].dn, res2gc[0].dn)
1406
1407         print "Testing ldb.search for (&(cn=ldaptestcomputer)(objectCategory=compuTER))"
1408         res3 = ldb.search(expression="(&(cn=ldaptestcomputer)(objectCategory=compuTER))")
1409         self.assertEquals(len(res3), 1, "Could not find (&(cn=ldaptestcomputer)(objectCategory=compuTER))")
1410
1411         self.assertEquals(res[0].dn, res3[0].dn)
1412
1413         if gc_ldb is not None:
1414             print "Testing ldb.search for (&(cn=ldaptestcomputer)(objectCategory=compuTER)) in Global Catalog"
1415             res3gc = gc_ldb.search(expression="(&(cn=ldaptestcomputer)(objectCategory=compuTER))")
1416             self.assertEquals(len(res3gc), 1, "Could not find (&(cn=ldaptestcomputer)(objectCategory=compuTER)) in Global Catalog")
1417
1418             self.assertEquals(res[0].dn, res3gc[0].dn)
1419
1420         print "Testing ldb.search for (&(cn=ldaptestcomp*r)(objectCategory=compuTER))"
1421         res4 = ldb.search(expression="(&(cn=ldaptestcomp*r)(objectCategory=compuTER))")
1422         self.assertEquals(len(res4), 1, "Could not find (&(cn=ldaptestcomp*r)(objectCategory=compuTER))")
1423
1424         self.assertEquals(res[0].dn, res4[0].dn)
1425
1426         print "Testing ldb.search for (&(cn=ldaptestcomput*)(objectCategory=compuTER))"
1427         res5 = ldb.search(expression="(&(cn=ldaptestcomput*)(objectCategory=compuTER))")
1428         self.assertEquals(len(res5), 1, "Could not find (&(cn=ldaptestcomput*)(objectCategory=compuTER))")
1429
1430         self.assertEquals(res[0].dn, res5[0].dn)
1431
1432         print "Testing ldb.search for (&(cn=*daptestcomputer)(objectCategory=compuTER))"
1433         res6 = ldb.search(expression="(&(cn=*daptestcomputer)(objectCategory=compuTER))")
1434         self.assertEquals(len(res6), 1, "Could not find (&(cn=*daptestcomputer)(objectCategory=compuTER))")
1435
1436         self.assertEquals(res[0].dn, res6[0].dn)
1437
1438         ldb.delete("<GUID=" + ldb.schema_format_value("objectGUID", res[0]["objectGUID"][0]) + ">")
1439
1440         print "Testing ldb.search for (&(cn=ldaptest2computer)(objectClass=user))"
1441         res = ldb.search(expression="(&(cn=ldaptest2computer)(objectClass=user))")
1442         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptest2computer)(objectClass=user))")
1443
1444         self.assertEquals(str(res[0].dn), "CN=ldaptest2computer,CN=Computers," + self.base_dn)
1445         self.assertEquals(str(res[0]["cn"]), "ldaptest2computer")
1446         self.assertEquals(str(res[0]["name"]), "ldaptest2computer")
1447         self.assertEquals(list(res[0]["objectClass"]), ["top", "person", "organizationalPerson", "user", "computer"])
1448         self.assertTrue("objectGUID" in res[0])
1449         self.assertTrue("whenCreated" in res[0])
1450         self.assertEquals(res[0]["objectCategory"][0], "CN=Computer,CN=Schema,CN=Configuration," + self.base_dn)
1451         self.assertEquals(int(res[0]["sAMAccountType"][0]), ATYPE_WORKSTATION_TRUST)
1452         self.assertEquals(int(res[0]["userAccountControl"][0]), UF_WORKSTATION_TRUST_ACCOUNT)
1453
1454         ldb.delete("<SID=" + ldb.schema_format_value("objectSID", res[0]["objectSID"][0]) + ">")
1455
1456         attrs = ["cn", "name", "objectClass", "objectGUID", "objectSID", "whenCreated", "nTSecurityDescriptor", "memberOf", "allowedAttributes", "allowedAttributesEffective"]
1457         print "Testing ldb.search for (&(cn=ldaptestUSer2)(objectClass=user))"
1458         res_user = ldb.search(self.base_dn, expression="(&(cn=ldaptestUSer2)(objectClass=user))", scope=SCOPE_SUBTREE, attrs=attrs)
1459         self.assertEquals(len(res_user), 1, "Could not find (&(cn=ldaptestUSer2)(objectClass=user))")
1460
1461         self.assertEquals(str(res_user[0].dn), ("CN=ldaptestuser2,CN=Users," + self.base_dn))
1462         self.assertEquals(str(res_user[0]["cn"]), "ldaptestuser2")
1463         self.assertEquals(str(res_user[0]["name"]), "ldaptestuser2")
1464         self.assertEquals(list(res_user[0]["objectClass"]), ["top", "person", "organizationalPerson", "user"])
1465         self.assertTrue("objectSid" in res_user[0])
1466         self.assertTrue("objectGUID" in res_user[0])
1467         self.assertTrue("whenCreated" in res_user[0])
1468         self.assertTrue("nTSecurityDescriptor" in res_user[0])
1469         self.assertTrue("allowedAttributes" in res_user[0])
1470         self.assertTrue("allowedAttributesEffective" in res_user[0])
1471         self.assertEquals(res_user[0]["memberOf"][0].upper(), ("CN=ldaptestgroup2,CN=Users," + self.base_dn).upper())
1472
1473         ldaptestuser2_sid = res_user[0]["objectSid"][0]
1474         ldaptestuser2_guid = res_user[0]["objectGUID"][0]
1475
1476         attrs = ["cn", "name", "objectClass", "objectGUID", "objectSID", "whenCreated", "nTSecurityDescriptor", "member", "allowedAttributes", "allowedAttributesEffective"]
1477         print "Testing ldb.search for (&(cn=ldaptestgroup2)(objectClass=group))"
1478         res = ldb.search(self.base_dn, expression="(&(cn=ldaptestgroup2)(objectClass=group))", scope=SCOPE_SUBTREE, attrs=attrs)
1479         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestgroup2)(objectClass=group))")
1480
1481         self.assertEquals(str(res[0].dn), ("CN=ldaptestgroup2,CN=Users," + self.base_dn))
1482         self.assertEquals(str(res[0]["cn"]), "ldaptestgroup2")
1483         self.assertEquals(str(res[0]["name"]), "ldaptestgroup2")
1484         self.assertEquals(list(res[0]["objectClass"]), ["top", "group"])
1485         self.assertTrue("objectGUID" in res[0])
1486         self.assertTrue("objectSid" in res[0])
1487         self.assertTrue("whenCreated" in res[0])
1488         self.assertTrue("nTSecurityDescriptor" in res[0])
1489         self.assertTrue("allowedAttributes" in res[0])
1490         self.assertTrue("allowedAttributesEffective" in res[0])
1491         memberUP = []
1492         for m in res[0]["member"]:
1493             memberUP.append(m.upper())
1494         self.assertTrue(("CN=ldaptestuser2,CN=Users," + self.base_dn).upper() in memberUP)
1495
1496         res = ldb.search(self.base_dn, expression="(&(cn=ldaptestgroup2)(objectClass=group))", scope=SCOPE_SUBTREE, attrs=attrs, controls=["extended_dn:1:1"])
1497         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestgroup2)(objectClass=group))")
1498
1499         print res[0]["member"]
1500         memberUP = []
1501         for m in res[0]["member"]:
1502             memberUP.append(m.upper())
1503         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()
1504
1505         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)
1506
1507         print "Testing Linked attribute behaviours"
1508         ldb.modify_ldif("""
1509 dn: cn=ldaptestgroup2,cn=users,""" + self.base_dn + """
1510 changetype: modify
1511 replace: member
1512 member: CN=ldaptestuser2,CN=Users,""" + self.base_dn + """
1513 member: CN=ldaptestutf8user èùéìòà,CN=Users,""" + self.base_dn + """
1514 """)
1515
1516         ldb.modify_ldif("""
1517 dn: <GUID=""" + ldb.schema_format_value("objectGUID", res[0]["objectGUID"][0]) + """>
1518 changetype: modify
1519 replace: member
1520 member: CN=ldaptestutf8user èùéìòà,CN=Users,""" + self.base_dn + """
1521 """)
1522
1523         ldb.modify_ldif("""
1524 dn: <SID=""" + ldb.schema_format_value("objectSid", res[0]["objectSid"][0]) + """>
1525 changetype: modify
1526 delete: member
1527 """)
1528
1529         ldb.modify_ldif("""
1530 dn: cn=ldaptestgroup2,cn=users,""" + self.base_dn + """
1531 changetype: modify
1532 add: member
1533 member: <GUID=""" + ldb.schema_format_value("objectGUID", res[0]["objectGUID"][0]) + """>
1534 member: CN=ldaptestutf8user èùéìòà,CN=Users,""" + self.base_dn + """
1535 """)
1536
1537         ldb.modify_ldif("""
1538 dn: cn=ldaptestgroup2,cn=users,""" + self.base_dn + """
1539 changetype: modify
1540 replace: member
1541 """)
1542
1543         ldb.modify_ldif("""
1544 dn: cn=ldaptestgroup2,cn=users,""" + self.base_dn + """
1545 changetype: modify
1546 add: member
1547 member: <SID=""" + ldb.schema_format_value("objectSid", res_user[0]["objectSid"][0]) + """>
1548 member: CN=ldaptestutf8user èùéìòà,CN=Users,""" + self.base_dn + """
1549 """)
1550
1551         ldb.modify_ldif("""
1552 dn: cn=ldaptestgroup2,cn=users,""" + self.base_dn + """
1553 changetype: modify
1554 delete: member
1555 member: CN=ldaptestutf8user èùéìòà,CN=Users,""" + self.base_dn + """
1556 """)
1557
1558         res = ldb.search(self.base_dn, expression="(&(cn=ldaptestgroup2)(objectClass=group))", scope=SCOPE_SUBTREE, attrs=attrs)
1559         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestgroup2)(objectClass=group))")
1560
1561         self.assertEquals(str(res[0].dn), ("CN=ldaptestgroup2,CN=Users," + self.base_dn))
1562         self.assertEquals(res[0]["member"][0], ("CN=ldaptestuser2,CN=Users," + self.base_dn))
1563         self.assertEquals(len(res[0]["member"]), 1)
1564
1565         ldb.delete(("CN=ldaptestuser2,CN=Users," + self.base_dn))
1566
1567         time.sleep(4)
1568
1569         attrs = ["cn", "name", "objectClass", "objectGUID", "whenCreated", "nTSecurityDescriptor", "member"]
1570         print "Testing ldb.search for (&(cn=ldaptestgroup2)(objectClass=group)) to check linked delete"
1571         res = ldb.search(self.base_dn, expression="(&(cn=ldaptestgroup2)(objectClass=group))", scope=SCOPE_SUBTREE, attrs=attrs)
1572         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestgroup2)(objectClass=group)) to check linked delete")
1573
1574         self.assertEquals(str(res[0].dn), ("CN=ldaptestgroup2,CN=Users," + self.base_dn))
1575         self.assertTrue("member" not in res[0])
1576
1577         print "Testing ldb.search for (&(cn=ldaptestutf8user ÈÙÉÌÒÀ)(objectClass=user))"
1578 # TODO UTF8 users don't seem to work fully anymore
1579 #        res = ldb.search(expression="(&(cn=ldaptestutf8user ÈÙÉÌÒÀ)(objectClass=user))")
1580         res = ldb.search(expression="(&(cn=ldaptestutf8user èùéìòà)(objectclass=user))")
1581         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestutf8user ÈÙÉÌÒÀ)(objectClass=user))")
1582
1583         self.assertEquals(str(res[0].dn), ("CN=ldaptestutf8user èùéìòà,CN=Users," + self.base_dn))
1584         self.assertEquals(str(res[0]["cn"]), "ldaptestutf8user èùéìòà")
1585         self.assertEquals(str(res[0]["name"]), "ldaptestutf8user èùéìòà")
1586         self.assertEquals(list(res[0]["objectClass"]), ["top", "person", "organizationalPerson", "user"])
1587         self.assertTrue("objectGUID" in res[0])
1588         self.assertTrue("whenCreated" in res[0])
1589
1590         ldb.delete(res[0].dn)
1591
1592         print "Testing ldb.search for (&(cn=ldaptestutf8user2*)(objectClass=user))"
1593         res = ldb.search(expression="(&(cn=ldaptestutf8user2*)(objectClass=user))")
1594         self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestutf8user2*)(objectClass=user))")
1595
1596         ldb.delete(res[0].dn)
1597
1598         ldb.delete(("CN=ldaptestgroup2,CN=Users," + self.base_dn))
1599
1600         print "Testing ldb.search for (&(cn=ldaptestutf8user2 ÈÙÉÌÒÀ)(objectClass=user))"
1601 # TODO UTF8 users don't seem to work fully anymore
1602 #        res = ldb.search(expression="(&(cn=ldaptestutf8user ÈÙÉÌÒÀ)(objectClass=user))")
1603 #        self.assertEquals(len(res), 1, "Could not find (&(cn=ldaptestutf8user ÈÙÉÌÒÀ)(objectClass=user))")
1604
1605         print "Testing that we can't get at the configuration DN from the main search base"
1606         res = ldb.search(self.base_dn, expression="objectClass=crossRef", scope=SCOPE_SUBTREE, attrs=["cn"])
1607         self.assertEquals(len(res), 0)
1608
1609         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"
1610         res = ldb.search(self.base_dn, expression="objectClass=crossRef", scope=SCOPE_SUBTREE, attrs=["cn"], controls=["search_options:1:2"])
1611         self.assertTrue(len(res) > 0)
1612
1613         if gc_ldb is not None:
1614             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"
1615
1616             res = gc_ldb.search(self.base_dn, expression="objectClass=crossRef", scope=SCOPE_SUBTREE, attrs=["cn"], controls=["search_options:1:0"])
1617             self.assertTrue(len(res) > 0)
1618
1619             print "Testing that we do find configuration elements in the global catlog"
1620             res = gc_ldb.search(self.base_dn, expression="objectClass=crossRef", scope=SCOPE_SUBTREE, attrs=["cn"])
1621             self.assertTrue(len(res) > 0)
1622
1623             print "Testing that we do find configuration elements and user elements at the same time"
1624             res = gc_ldb.search(self.base_dn, expression="(|(objectClass=crossRef)(objectClass=person))", scope=SCOPE_SUBTREE, attrs=["cn"])
1625             self.assertTrue(len(res) > 0)
1626
1627             print "Testing that we do find configuration elements in the global catlog, with the configuration basedn"
1628             res = gc_ldb.search(self.configuration_dn, expression="objectClass=crossRef", scope=SCOPE_SUBTREE, attrs=["cn"])
1629             self.assertTrue(len(res) > 0)
1630
1631         print "Testing that we can get at the configuration DN on the main LDAP port"
1632         res = ldb.search(self.configuration_dn, expression="objectClass=crossRef", scope=SCOPE_SUBTREE, attrs=["cn"])
1633         self.assertTrue(len(res) > 0)
1634
1635         print "Testing objectCategory canonacolisation"
1636         res = ldb.search(self.configuration_dn, expression="objectCategory=ntDsDSA", scope=SCOPE_SUBTREE, attrs=["cn"])
1637         self.assertTrue(len(res) > 0, "Didn't find any records with objectCategory=ntDsDSA")
1638         self.assertTrue(len(res) != 0)
1639
1640         res = ldb.search(self.configuration_dn, expression="objectCategory=CN=ntDs-DSA," + self.schema_dn, scope=SCOPE_SUBTREE, attrs=["cn"])
1641         self.assertTrue(len(res) > 0, "Didn't find any records with objectCategory=CN=ntDs-DSA," + self.schema_dn)
1642         self.assertTrue(len(res) != 0)
1643
1644         print "Testing objectClass attribute order on "+ self.base_dn
1645         res = ldb.search(expression="objectClass=domain", base=self.base_dn,
1646                          scope=SCOPE_BASE, attrs=["objectClass"])
1647         self.assertEquals(len(res), 1)
1648
1649         self.assertEquals(list(res[0]["objectClass"]), ["top", "domain", "domainDNS"])
1650
1651     #  check enumeration
1652
1653         print "Testing ldb.search for objectCategory=person"
1654         res = ldb.search(self.base_dn, expression="objectCategory=person", scope=SCOPE_SUBTREE, attrs=["cn"])
1655         self.assertTrue(len(res) > 0)
1656
1657         print "Testing ldb.search for objectCategory=person with domain scope control"
1658         res = ldb.search(self.base_dn, expression="objectCategory=person", scope=SCOPE_SUBTREE, attrs=["cn"], controls=["domain_scope:1"])
1659         self.assertTrue(len(res) > 0)
1660
1661         print "Testing ldb.search for objectCategory=user"
1662         res = ldb.search(self.base_dn, expression="objectCategory=user", scope=SCOPE_SUBTREE, attrs=["cn"])
1663         self.assertTrue(len(res) > 0)
1664
1665         print "Testing ldb.search for objectCategory=user with domain scope control"
1666         res = ldb.search(self.base_dn, expression="objectCategory=user", scope=SCOPE_SUBTREE, attrs=["cn"], controls=["domain_scope:1"])
1667         self.assertTrue(len(res) > 0)
1668
1669         print "Testing ldb.search for objectCategory=group"
1670         res = ldb.search(self.base_dn, expression="objectCategory=group", scope=SCOPE_SUBTREE, attrs=["cn"])
1671         self.assertTrue(len(res) > 0)
1672
1673         print "Testing ldb.search for objectCategory=group with domain scope control"
1674         res = ldb.search(self.base_dn, expression="objectCategory=group", scope=SCOPE_SUBTREE, attrs=["cn"], controls=["domain_scope:1"])
1675         self.assertTrue(len(res) > 0)
1676
1677         self.delete_force(self.ldb, "cn=ldaptestuser,cn=users," + self.base_dn)
1678         self.delete_force(self.ldb, "cn=ldaptestuser2,cn=users," + self.base_dn)
1679         self.delete_force(self.ldb, "cn=ldaptestuser3,cn=users," + self.base_dn)
1680         self.delete_force(self.ldb, "cn=ldaptestuser4,cn=ldaptestcontainer," + self.base_dn)
1681         self.delete_force(self.ldb, "cn=ldaptestuser4,cn=ldaptestcontainer2," + self.base_dn)
1682         self.delete_force(self.ldb, "cn=ldaptestuser5,cn=users," + self.base_dn)
1683         self.delete_force(self.ldb, "cn=ldaptestgroup,cn=users," + self.base_dn)
1684         self.delete_force(self.ldb, "cn=ldaptestgroup2,cn=users," + self.base_dn)
1685         self.delete_force(self.ldb, "cn=ldaptestcomputer,cn=computers," + self.base_dn)
1686         self.delete_force(self.ldb, "cn=ldaptest2computer,cn=computers," + self.base_dn)
1687         self.delete_force(self.ldb, "cn=ldaptestcomputer3,cn=computers," + self.base_dn)
1688         self.delete_force(self.ldb, "cn=ldaptestutf8user èùéìòà,cn=users," + self.base_dn)
1689         self.delete_force(self.ldb, "cn=ldaptestutf8user2  èùéìòà,cn=users," + self.base_dn)
1690         self.delete_force(self.ldb, "cn=ldaptestcontainer," + self.base_dn)
1691         self.delete_force(self.ldb, "cn=ldaptestcontainer2," + self.base_dn)
1692
1693     def test_security_descriptor_add(self):
1694         """ Testing ldb.add_ldif() for nTSecurityDescriptor """
1695         user_name = "testdescriptoruser1"
1696         user_dn = "CN=%s,CN=Users,%s" % (user_name, self.base_dn)
1697         #
1698         # Test add_ldif() with SDDL security descriptor input
1699         #
1700         self.delete_force(self.ldb, user_dn)
1701         try:
1702             sddl = "O:DUG:DUD:PAI(A;;RPWP;;;AU)S:PAI"
1703             self.ldb.add_ldif("""
1704 dn: """ + user_dn + """
1705 objectclass: user
1706 sAMAccountName: """ + user_name + """
1707 nTSecurityDescriptor: """ + sddl)
1708             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1709             desc = res[0]["nTSecurityDescriptor"][0]
1710             desc = ndr_unpack( security.descriptor, desc )
1711             desc_sddl = desc.as_sddl( self.domain_sid )
1712             self.assertEqual(desc_sddl, sddl)
1713         finally:
1714             self.delete_force(self.ldb, user_dn)
1715         #
1716         # Test add_ldif() with BASE64 security descriptor
1717         #
1718         try:
1719             sddl = "O:DUG:DUD:PAI(A;;RPWP;;;AU)S:PAI"
1720             desc = security.descriptor.from_sddl(sddl, self.domain_sid)
1721             desc_binary = ndr_pack(desc)
1722             desc_base64 = base64.b64encode(desc_binary)
1723             self.ldb.add_ldif("""
1724 dn: """ + user_dn + """
1725 objectclass: user
1726 sAMAccountName: """ + user_name + """
1727 nTSecurityDescriptor:: """ + desc_base64)
1728             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1729             desc = res[0]["nTSecurityDescriptor"][0]
1730             desc = ndr_unpack(security.descriptor, desc)
1731             desc_sddl = desc.as_sddl(self.domain_sid)
1732             self.assertEqual(desc_sddl, sddl)
1733         finally:
1734             self.delete_force(self.ldb, user_dn)
1735
1736     def test_security_descriptor_add_neg(self):
1737         """Test add_ldif() with BASE64 security descriptor input using WRONG domain SID
1738             Negative test
1739         """
1740         user_name = "testdescriptoruser1"
1741         user_dn = "CN=%s,CN=Users,%s" % (user_name, self.base_dn)
1742         self.delete_force(self.ldb, user_dn)
1743         try:
1744             sddl = "O:DUG:DUD:PAI(A;;RPWP;;;AU)S:PAI"
1745             desc = security.descriptor.from_sddl(sddl, security.dom_sid('S-1-5-21'))
1746             desc_base64 = base64.b64encode( ndr_pack(desc) )
1747             self.ldb.add_ldif("""
1748 dn: """ + user_dn + """
1749 objectclass: user
1750 sAMAccountName: """ + user_name + """
1751 nTSecurityDescriptor:: """ + desc_base64)
1752             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1753             print res
1754             self.assertRaises(KeyError, lambda: res[0]["nTSecurityDescriptor"])
1755         finally:
1756             self.delete_force(self.ldb, user_dn)
1757
1758     def test_security_descriptor_modify(self):
1759         """ Testing ldb.modify_ldif() for nTSecurityDescriptor """
1760         user_name = "testdescriptoruser2"
1761         user_dn = "CN=%s,CN=Users,%s" % (user_name, self.base_dn)
1762         #
1763         # Delete user object and test modify_ldif() with SDDL security descriptor input
1764         # Add ACE to the original descriptor test
1765         #
1766         try:
1767             self.delete_force(self.ldb, user_dn)
1768             self.ldb.add_ldif("""
1769 dn: """ + user_dn + """
1770 objectclass: user
1771 sAMAccountName: """ + user_name)
1772             # Modify descriptor
1773             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1774             desc = res[0]["nTSecurityDescriptor"][0]
1775             desc = ndr_unpack(security.descriptor, desc)
1776             desc_sddl = desc.as_sddl(self.domain_sid)
1777             sddl = desc_sddl[:desc_sddl.find("(")] + "(A;;RPWP;;;AU)" + desc_sddl[desc_sddl.find("("):]
1778             mod = """
1779 dn: """ + user_dn + """
1780 changetype: modify
1781 replace: nTSecurityDescriptor
1782 nTSecurityDescriptor: """ + sddl
1783             self.ldb.modify_ldif(mod)
1784             # Read modified descriptor
1785             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1786             desc = res[0]["nTSecurityDescriptor"][0]
1787             desc = ndr_unpack(security.descriptor, desc)
1788             desc_sddl = desc.as_sddl(self.domain_sid)
1789             self.assertEqual(desc_sddl, sddl)
1790         finally:
1791             self.delete_force(self.ldb, user_dn)
1792         #
1793         # Test modify_ldif() with SDDL security descriptor input
1794         # New desctiptor test
1795         #
1796         try:
1797             self.ldb.add_ldif("""
1798 dn: """ + user_dn + """
1799 objectclass: user
1800 sAMAccountName: """ + user_name)
1801             # Modify descriptor
1802             sddl = "O:DUG:DUD:PAI(A;;RPWP;;;AU)S:PAI"
1803             mod = """
1804 dn: """ + user_dn + """
1805 changetype: modify
1806 replace: nTSecurityDescriptor
1807 nTSecurityDescriptor: """ + sddl
1808             self.ldb.modify_ldif(mod)
1809             # Read modified descriptor
1810             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1811             desc = res[0]["nTSecurityDescriptor"][0]
1812             desc = ndr_unpack(security.descriptor, desc)
1813             desc_sddl = desc.as_sddl(self.domain_sid)
1814             self.assertEqual(desc_sddl, sddl)
1815         finally:
1816             self.delete_force(self.ldb, user_dn)
1817         #
1818         # Test modify_ldif() with BASE64 security descriptor input
1819         # Add ACE to the original descriptor test
1820         #
1821         try:
1822             self.ldb.add_ldif("""
1823 dn: """ + user_dn + """
1824 objectclass: user
1825 sAMAccountName: """ + user_name)
1826             # Modify descriptor
1827             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1828             desc = res[0]["nTSecurityDescriptor"][0]
1829             desc = ndr_unpack(security.descriptor, desc)
1830             desc_sddl = desc.as_sddl(self.domain_sid)
1831             sddl = desc_sddl[:desc_sddl.find("(")] + "(A;;RPWP;;;AU)" + desc_sddl[desc_sddl.find("("):]
1832             desc = security.descriptor.from_sddl(sddl, self.domain_sid)
1833             desc_base64 = base64.b64encode(ndr_pack(desc))
1834             mod = """
1835 dn: """ + user_dn + """
1836 changetype: modify
1837 replace: nTSecurityDescriptor
1838 nTSecurityDescriptor:: """ + desc_base64
1839             self.ldb.modify_ldif(mod)
1840             # Read modified descriptor
1841             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1842             desc = res[0]["nTSecurityDescriptor"][0]
1843             desc = ndr_unpack(security.descriptor, desc)
1844             desc_sddl = desc.as_sddl(self.domain_sid)
1845             self.assertEqual(desc_sddl, sddl)
1846         finally:
1847             self.delete_force(self.ldb, user_dn)
1848         #
1849         # Test modify_ldif() with BASE64 security descriptor input
1850         # New descriptor test
1851         #
1852         try:
1853             self.delete_force(self.ldb, user_dn)
1854             self.ldb.add_ldif("""
1855 dn: """ + user_dn + """
1856 objectclass: user
1857 sAMAccountName: """ + user_name)
1858             # Modify descriptor
1859             sddl = "O:DUG:DUD:PAI(A;;RPWP;;;AU)S:PAI"
1860             desc = security.descriptor.from_sddl(sddl, self.domain_sid)
1861             desc_base64 = base64.b64encode(ndr_pack(desc))
1862             mod = """
1863 dn: """ + user_dn + """
1864 changetype: modify
1865 replace: nTSecurityDescriptor
1866 nTSecurityDescriptor:: """ + desc_base64
1867             self.ldb.modify_ldif(mod)
1868             # Read modified descriptor
1869             res = self.ldb.search(base=user_dn, attrs=["nTSecurityDescriptor"])
1870             desc = res[0]["nTSecurityDescriptor"][0]
1871             desc = ndr_unpack(security.descriptor, desc)
1872             desc_sddl = desc.as_sddl(self.domain_sid)
1873             self.assertEqual(desc_sddl, sddl)
1874         finally:
1875             self.delete_force(self.ldb, user_dn)
1876
1877 class BaseDnTests(unittest.TestCase):
1878     def setUp(self):
1879         self.ldb = ldb
1880
1881     def test_rootdse_attrs(self):
1882         """Testing for all rootDSE attributes"""
1883         res = self.ldb.search(scope=SCOPE_BASE, attrs=[])
1884         self.assertEquals(len(res), 1)
1885
1886     def test_highestcommittedusn(self):
1887         """Testing for highestCommittedUSN"""
1888         res = self.ldb.search("", scope=SCOPE_BASE, attrs=["highestCommittedUSN"])
1889         self.assertEquals(len(res), 1)
1890         self.assertTrue(int(res[0]["highestCommittedUSN"][0]) != 0)
1891
1892     def test_netlogon(self):
1893         """Testing for netlogon via LDAP"""
1894         res = self.ldb.search("", scope=SCOPE_BASE, attrs=["netlogon"])
1895         self.assertEquals(len(res), 0)
1896
1897     def test_netlogon_highestcommitted_usn(self):
1898         """Testing for netlogon and highestCommittedUSN via LDAP"""
1899         res = self.ldb.search("", scope=SCOPE_BASE,
1900                 attrs=["netlogon", "highestCommittedUSN"])
1901         self.assertEquals(len(res), 0)
1902
1903 class SchemaTests(unittest.TestCase):
1904     def delete_force(self, ldb, dn):
1905         try:
1906             ldb.delete(dn)
1907         except LdbError, (num, _):
1908             self.assertEquals(num, ERR_NO_SUCH_OBJECT)
1909
1910     def find_schemadn(self, ldb):
1911         res = ldb.search(base="", expression="", scope=SCOPE_BASE, attrs=["schemaNamingContext"])
1912         self.assertEquals(len(res), 1)
1913         return res[0]["schemaNamingContext"][0]
1914
1915     def find_basedn(self, ldb):
1916         res = ldb.search(base="", expression="", scope=SCOPE_BASE,
1917                          attrs=["defaultNamingContext"])
1918         self.assertEquals(len(res), 1)
1919         return res[0]["defaultNamingContext"][0]
1920
1921     def setUp(self):
1922         self.ldb = ldb
1923         self.schema_dn = self.find_schemadn(ldb)
1924         self.base_dn = self.find_basedn(ldb)
1925
1926     def test_generated_schema(self):
1927         """Testing we can read the generated schema via LDAP"""
1928         res = self.ldb.search("cn=aggregate,"+self.schema_dn, scope=SCOPE_BASE,
1929                 attrs=["objectClasses", "attributeTypes", "dITContentRules"])
1930         self.assertEquals(len(res), 1)
1931         self.assertTrue("dITContentRules" in res[0])
1932         self.assertTrue("objectClasses" in res[0])
1933         self.assertTrue("attributeTypes" in res[0])
1934
1935     def test_generated_schema_is_operational(self):
1936         """Testing we don't get the generated schema via LDAP by default"""
1937         res = self.ldb.search("cn=aggregate,"+self.schema_dn, scope=SCOPE_BASE,
1938                 attrs=["*"])
1939         self.assertEquals(len(res), 1)
1940         self.assertFalse("dITContentRules" in res[0])
1941         self.assertFalse("objectClasses" in res[0])
1942         self.assertFalse("attributeTypes" in res[0])
1943
1944
1945     def test_schemaUpdateNow(self):
1946         """Testing schemaUpdateNow"""
1947         attr_name = "test-Attr" + time.strftime("%s", time.gmtime())
1948         attr_ldap_display_name = attr_name.replace("-", "")
1949
1950         ldif = """
1951 dn: CN=%s,%s""" % (attr_name, self.schema_dn) + """
1952 objectClass: top
1953 objectClass: attributeSchema
1954 adminDescription: """ + attr_name + """
1955 adminDisplayName: """ + attr_name + """
1956 cn: """ + attr_name + """
1957 attributeId: 1.2.840.""" + str(random.randint(1,100000)) + """.1.5.9940
1958 attributeSyntax: 2.5.5.12
1959 omSyntax: 64
1960 instanceType: 4
1961 isSingleValued: TRUE
1962 systemOnly: FALSE
1963 """
1964         self.ldb.add_ldif(ldif)
1965
1966         class_name = "test-Class" + time.strftime("%s", time.gmtime())
1967         class_ldap_display_name = class_name.replace("-", "")
1968
1969         ldif = """
1970 dn: CN=%s,%s""" % (class_name, self.schema_dn) + """
1971 objectClass: top
1972 objectClass: classSchema
1973 adminDescription: """ + class_name + """
1974 adminDisplayName: """ + class_name + """
1975 cn: """ + class_name + """
1976 governsId: 1.2.840.""" + str(random.randint(1,100000)) + """.1.5.9939
1977 instanceType: 4
1978 objectClassCategory: 1
1979 subClassOf: organizationalPerson
1980 systemFlags: 16
1981 rDNAttID: cn
1982 systemMustContain: cn
1983 systemMustContain: """ + attr_ldap_display_name + """
1984 systemOnly: FALSE
1985 """
1986         self.ldb.add_ldif(ldif)
1987
1988         ldif = """
1989 dn:
1990 changetype: modify
1991 add: schemaUpdateNow
1992 schemaUpdateNow: 1
1993 """
1994         self.ldb.modify_ldif(ldif)
1995
1996         object_name = "obj" + time.strftime("%s", time.gmtime())
1997
1998         ldif = """
1999 dn: CN=%s,CN=Users,%s"""% (object_name, self.base_dn) + """
2000 objectClass: organizationalPerson
2001 objectClass: person
2002 objectClass: """ + class_ldap_display_name + """
2003 objectClass: top
2004 cn: """ + object_name + """
2005 instanceType: 4
2006 objectCategory: CN=%s,%s"""% (class_name, self.schema_dn) + """
2007 distinguishedName: CN=%s,CN=Users,%s"""% (object_name, self.base_dn) + """
2008 name: """ + object_name + """
2009 """ + attr_ldap_display_name + """: test
2010 """
2011         self.ldb.add_ldif(ldif)
2012
2013         # Search for created attribute
2014         res = []
2015         res = self.ldb.search("cn=%s,%s" % (attr_name, self.schema_dn), scope=SCOPE_BASE, attrs=["*"])
2016         self.assertEquals(len(res), 1)
2017         self.assertEquals(res[0]["lDAPDisplayName"][0], attr_ldap_display_name)
2018         self.assertTrue("schemaIDGUID" in res[0])
2019
2020         # Search for created objectclass
2021         res = []
2022         res = self.ldb.search("cn=%s,%s" % (class_name, self.schema_dn), scope=SCOPE_BASE, attrs=["*"])
2023         self.assertEquals(len(res), 1)
2024         self.assertEquals(res[0]["lDAPDisplayName"][0], class_ldap_display_name)
2025         self.assertEquals(res[0]["defaultObjectCategory"][0], res[0]["distinguishedName"][0])
2026         self.assertTrue("schemaIDGUID" in res[0])
2027
2028         # Search for created object
2029         res = []
2030         res = self.ldb.search("cn=%s,cn=Users,%s" % (object_name, self.base_dn), scope=SCOPE_BASE, attrs=["*"])
2031         self.assertEquals(len(res), 1)
2032         # Delete the object
2033         self.delete_force(self.ldb, "cn=%s,cn=Users,%s" % (object_name, self.base_dn))
2034
2035 if not "://" in host:
2036     if os.path.isfile(host):
2037         host = "tdb://%s" % host
2038     else:
2039         host = "ldap://%s" % host
2040
2041 ldb = Ldb(host, credentials=creds, session_info=system_session(), lp=lp)
2042 if not "tdb://" in host:
2043     gc_ldb = Ldb("%s:3268" % host, credentials=creds,
2044                  session_info=system_session(), lp=lp)
2045 else:
2046     gc_ldb = None
2047
2048 runner = SubunitTestRunner()
2049 rc = 0
2050 if not runner.run(unittest.makeSuite(BaseDnTests)).wasSuccessful():
2051     rc = 1
2052 if not runner.run(unittest.makeSuite(BasicTests)).wasSuccessful():
2053     rc = 1
2054 if not runner.run(unittest.makeSuite(SchemaTests)).wasSuccessful():
2055     rc = 1
2056 sys.exit(rc)