Exemple #1
0
    def testKnownValues(self):
        for s, l in self.knownValues:
            fromString = dn.DistinguishedName(s)
            listOfRDNs = []
            for av in l:
                listOfAttributeTypesAndValues = []
                for a,v in av:
                    listOfAttributeTypesAndValues.append(dn.LDAPAttributeTypeAndValue(attributeType=a, value=v))
                r=dn.RelativeDistinguishedName(listOfAttributeTypesAndValues)
                listOfRDNs.append(r)
            fromList = dn.DistinguishedName(listOfRDNs)

            self.assertEquals(fromString, fromList)

            fromStringToString = str(fromString)
            fromListToString = str(fromList)

            assert fromStringToString == fromListToString

            canon = fromStringToString
            # DNs equal their string representation. Note this does
            # not mean they equal all the possible string
            # representations -- just the canonical one.
            self.assertEquals(fromString, canon)
            self.assertEquals(fromList, canon)
            self.assertEquals(canon, fromString)
            self.assertEquals(canon, fromList)

            # DNs can be used interchangeably with their canonical
            # string representation as hash keys.
            self.assertEquals(hash(fromString), hash(canon))
            self.assertEquals(hash(fromList), hash(canon))
            self.assertEquals(hash(canon), hash(fromString))
            self.assertEquals(hash(canon), hash(fromList))
    def testDeleteSubtree(self):
        a = inmemory.ReadOnlyInMemoryLDAPEntry(
            dn=distinguishedname.DistinguishedName('dc=example,dc=com'))
        b = inmemory.ReadOnlyInMemoryLDAPEntry(
            dn=distinguishedname.DistinguishedName('dc=example,dc=com'))

        foo=a.addChild(
            rdn='ou=foo',
            attributes={
            'objectClass': ['a', 'b'],
            'ou': ['foo'],
            })
        baz=foo.addChild(
            rdn='cn=baz',
            attributes={
            'objectClass': ['a', 'b'],
            'cn': ['baz'],
            })
        bar=a.addChild(
            rdn='cn=bar',
            attributes={
            'objectClass': ['a', 'b'],
            'cn': ['bar'],
            })

        d = a.diffTree(b)
        d.addCallback(self.assertEquals, [
            delta.DeleteOp(bar),
            delta.DeleteOp(baz),
            delta.DeleteOp(foo),
            ])
        return d
Exemple #3
0
    def handle_LDAPModifyDNRequest(self, request, controls, reply):
        self.checkControls(controls)

        dn = distinguishedname.DistinguishedName(request.entry)
        newrdn = distinguishedname.RelativeDistinguishedName(request.newrdn)
        deleteoldrdn = bool(request.deleteoldrdn)
        if not deleteoldrdn:
            #TODO support this
            raise ldaperrors.LDAPUnwillingToPerform(
                "Cannot handle preserving old RDN yet.")
        newSuperior = request.newSuperior
        if newSuperior is None:
            newSuperior = dn.up()
        else:
            newSuperior = distinguishedname.DistinguishedName(newSuperior)
        newdn = distinguishedname.DistinguishedName(listOfRDNs=(newrdn, ) +
                                                    newSuperior.split())

        #TODO make this more atomic
        root = interfaces.IConnectedLDAPEntry(self.factory)
        d = root.lookup(dn)

        def _gotEntry(entry):
            d = entry.move(newdn)
            return d

        d.addCallback(_gotEntry)

        def _report(entry):
            return pureldap.LDAPModifyDNResponse(resultCode=0)

        d.addCallback(_report)
        return d
 def cb(children):
     self.assertEquals(len(children), 2)
     want = [
         distinguishedname.DistinguishedName('cn=foo,ou=metasyntactic,dc=example,dc=com'),
         distinguishedname.DistinguishedName('cn=bar,ou=metasyntactic,dc=example,dc=com'),
         ]
     got = [e.dn for e in children]
     self.assertEquals(got, want)
 def cb2(children):
     self.assertEquals(len(children), 2)
     want = [
         distinguishedname.DistinguishedName('dc=example,dc=com'),
         distinguishedname.DistinguishedName('cn=foo,dc=example,dc=com'),
         ]
     got = [e.dn for e in children]
     self.assertEquals(got, want)
 def cb(children):
     self.assertEquals(len(children), 1)
     got = [e.dn for e in children]
     want = [distinguishedname.DistinguishedName('cn=theChild,ou=oneChild,dc=example,dc=com')]
     got.sort()
     want.sort()
     self.assertEquals(got, want)
Exemple #7
0
 def _cbNamingContext_Entries(self, results):
     for result in results:
         for namingContext in result.get('namingContexts', ()):
             dn = distinguishedname.DistinguishedName(namingContext)
             if dn.contains(self.dn):
                 return LDAPEntry(self.client, dn)
     raise NoContainingNamingContext, self.dn
Exemple #8
0
    def move(self, newDN):
        self._checkState()
        newDN = distinguishedname.DistinguishedName(newDN)

        newrdn = newDN.split()[0]
        newSuperior = distinguishedname.DistinguishedName(
            listOfRDNs=newDN.split()[1:])
        newDN = distinguishedname.DistinguishedName((newrdn, ) +
                                                    newSuperior.split())
        op = pureldap.LDAPModifyDNRequest(entry=str(self.dn),
                                          newrdn=str(newrdn),
                                          deleteoldrdn=1,
                                          newSuperior=str(newSuperior))
        d = self.client.send(op)
        d.addCallback(self._cbMoveDone, newDN)
        return d
 def test_delete_root(self):
     newRoot = inmemory.ReadOnlyInMemoryLDAPEntry(
         dn=distinguishedname.DistinguishedName('dc=example,dc=com'))
     d = newRoot.delete()
     def eb(fail):
         fail.trap(inmemory.LDAPCannotRemoveRootError)
     d.addCallbacks(testutil.mustRaise, eb)
     return d
Exemple #10
0
 def test_lookup_fail_outOfTree(self):
     dn = distinguishedname.DistinguishedName('dc=invalid')
     d = self.root.lookup(dn)
     def eb(fail):
         fail.trap(ldaperrors.LDAPNoSuchObject)
         self.assertEquals(fail.value.message, dn)
     d.addCallbacks(testutil.mustRaise, eb)
     return d
Exemple #11
0
 def test_lookup_fail(self):
     dn = distinguishedname.DistinguishedName('cn=thud,ou=metasyntactic,dc=example,dc=com')
     d = self.root.lookup(dn)
     def eb(fail):
         fail.trap(ldaperrors.LDAPNoSuchObject)
         self.assertEquals(fail.value.message, dn)
     d.addCallbacks(testutil.mustRaise, eb)
     return d
Exemple #12
0
 def cb(children):
     self.assertEquals(len(children), 1)
     got = [e.dn for e in children]
     want = [
         distinguishedname.DistinguishedName('a=b,ou=empty,dc=example,dc=com'),
         ]
     got.sort()
     want.sort()
     self.assertEquals(got, want)
Exemple #13
0
    def __init__(self, reactor, dn, factory, overrides=None):
        if not isinstance(dn, distinguishedname.DistinguishedName):
            dn = distinguishedname.DistinguishedName(stringValue=dn)
        if overrides is None:
            overrides = {}
        self.override = self._findOverRide(dn, overrides)

        domain = dn.getDomainName()
        SRVConnector.__init__(self, reactor, 'ldap', domain, factory)
Exemple #14
0
 def __init__(self,
              baseDN=None,
              serviceLocationOverrides=None,
              identityBaseDN=None,
              identitySearch=None):
     if baseDN is not None:
         baseDN = distinguishedname.DistinguishedName(baseDN)
         self.baseDN = baseDN
     self.serviceLocationOverrides = {}
     if serviceLocationOverrides is not None:
         for k, v in serviceLocationOverrides.items():
             dn = distinguishedname.DistinguishedName(k)
             self.serviceLocationOverrides[dn] = v
     if identityBaseDN is not None:
         identityBaseDN = distinguishedname.DistinguishedName(
             identityBaseDN)
         self.identityBaseDN = identityBaseDN
     if identitySearch is not None:
         self.identitySearch = identitySearch
Exemple #15
0
    def opt_service_location(self, value):
        """Service location, in the form BASEDN:HOST[:PORT]"""

        if not self.opts.has_key('service-location'):
            self.opts['service-location'] = {}

        base, location = value.split(':', 1)
        try:
            dn = distinguishedname.DistinguishedName(base)
        except distinguishedname.InvalidRelativeDistinguishedName, e:
            raise usage.UsageError, str(e)
Exemple #16
0
 def addChild(self, rdn, attributes):
     """TODO ugly API. Returns the created entry."""
     rdn = distinguishedname.RelativeDistinguishedName(rdn)
     for c in self._children:
         if c.dn.split()[0] == rdn:
             raise ldaperrors.LDAPEntryAlreadyExists, c.dn
     dn = distinguishedname.DistinguishedName(listOfRDNs=(rdn, ) +
                                              self.dn.split())
     e = ReadOnlyInMemoryLDAPEntry(dn, attributes)
     e._parent = self
     self._children.append(e)
     return e
Exemple #17
0
 def _move(self, newDN):
     if not isinstance(newDN, distinguishedname.DistinguishedName):
         newDN = distinguishedname.DistinguishedName(stringValue=newDN)
     if newDN.up() != self.dn.up():
         # climb up the tree to root
         root = self
         while root._parent is not None:
             root = root._parent
         d = defer.maybeDeferred(root.lookup, newDN.up())
     else:
         d = defer.succeed(None)
     d.addCallback(self._move2, newDN)
     return d
Exemple #18
0
    def handle_LDAPSearchRequest(self, request, controls, reply):
        self.checkControls(controls)

        if (request.baseObject == ''
                and request.scope == pureldap.LDAP_SCOPE_baseObject and
                request.filter == pureldap.LDAPFilter_present('objectClass')):
            return self.getRootDSE(request, reply)
        dn = distinguishedname.DistinguishedName(request.baseObject)
        root = interfaces.IConnectedLDAPEntry(self.factory)
        d = root.lookup(dn)
        d.addCallback(self._cbSearchGotBase, dn, request, reply)
        d.addErrback(self._cbSearchLDAPError)
        d.addErrback(defer.logError)
        d.addErrback(self._cbSearchOtherError)
        return d
Exemple #19
0
    def testOpenLDAPEqualsEscape(self):
        """Slapd wants = to be escaped in RDN attributeValues."""
        got = dn.DistinguishedName(listOfRDNs=[
            dn.RelativeDistinguishedName(
            attributeTypesAndValues=[
            dn.LDAPAttributeTypeAndValue(attributeType='cn', value=r'test'),
            dn.LDAPAttributeTypeAndValue(attributeType='owner', value=r'uid=foo,ou=depart'
                                         +r'ment,dc=example,dc=com'),
                                     ]),

            dn.RelativeDistinguishedName('dc=example'),
            dn.RelativeDistinguishedName('dc=com'),
            ])
        got = str(got)
        self.assertEquals(got,
                          r'cn=test+owner=uid\=foo\,ou\=depar'
                          +r'tment\,dc\=example\,dc\=com,dc=ex'
                          +r'ample,dc=com')
Exemple #20
0
    def handle_LDAPDelRequest(self, request, controls, reply):
        self.checkControls(controls)

        dn = distinguishedname.DistinguishedName(request.value)
        root = interfaces.IConnectedLDAPEntry(self.factory)
        d = root.lookup(dn)

        def _gotEntry(entry):
            d = entry.delete()
            return d

        d.addCallback(_gotEntry)

        def _report(entry):
            return pureldap.LDAPDelResponse(resultCode=0)

        d.addCallback(_report)
        return d
    def testExamples(self):
        for name, data, expected in self.examples:
            proto = LDIFDriver()
            proto.dataReceived(data)

            self.failUnlessEqual(len(proto.listOfCompleted), len(expected))

            for dn, attr in expected:
                o = proto.listOfCompleted.pop(0)
                self.failUnlessEqual(o.dn, distinguishedname.DistinguishedName(dn))

                got = sets.Set([x.lower() for x in o.keys()])
                want = sets.Set([x.lower() for x in attr.keys()])
                self.failUnlessEqual(got, want)

                for k, v in attr.items():
                    self.failUnlessEqual(o[k], v)

            self.failUnlessEqual(proto.listOfCompleted, [])
Exemple #22
0
    def addChild(self, rdn, attributes):
        self._checkState()

        rdn = distinguishedname.RelativeDistinguishedName(rdn)
        dn = distinguishedname.DistinguishedName(listOfRDNs=(rdn, ) +
                                                 self.dn.split())

        ldapAttrs = []
        for attrType, values in attributes.items():
            ldapAttrType = pureldap.LDAPAttributeDescription(attrType)
            l = []
            for value in values:
                l.append(pureldap.LDAPAttributeValue(value))
            ldapValues = pureber.BERSet(l)

            ldapAttrs.append((ldapAttrType, ldapValues))
        op = pureldap.LDAPAddRequest(entry=str(dn), attributes=ldapAttrs)
        d = self.client.send(op)
        d.addCallback(self._cbAddDone, dn)
        return d
Exemple #23
0
    def setUp(self):
        self.root = inmemory.ReadOnlyInMemoryLDAPEntry(
            dn=distinguishedname.DistinguishedName('dc=example,dc=com'))
        self.meta=self.root.addChild(
            rdn='ou=metasyntactic',
            attributes={
            'objectClass': ['a', 'b'],
            'ou': ['metasyntactic'],
            })
        self.foo=self.meta.addChild(
            rdn='cn=foo',
            attributes={
            'objectClass': ['a', 'b'],
            'cn': ['foo'],
            })
        self.bar=self.meta.addChild(
            rdn='cn=bar',
            attributes={
            'objectClass': ['a', 'b'],
            'cn': ['bar'],
            })

        self.empty=self.root.addChild(
            rdn='ou=empty',
            attributes={
            'objectClass': ['a', 'b'],
            'ou': ['empty'],
            })

        self.oneChild=self.root.addChild(
            rdn='ou=oneChild',
            attributes={
            'objectClass': ['a', 'b'],
            'ou': ['oneChild'],
            })
        self.theChild=self.oneChild.addChild(
            rdn='cn=theChild',
            attributes={
            'objectClass': ['a', 'b'],
            'cn': ['theChild'],
            })
Exemple #24
0
    def handle_LDAPBindRequest(self, request, controls, reply):
        if request.version != 3:
            raise ldaperrors.LDAPProtocolError, \
                  'Version %u not supported' % request.version

        self.checkControls(controls)

        if request.dn == '':
            # anonymous bind
            self.boundUser = None
            return pureldap.LDAPBindResponse(resultCode=0)
        else:
            dn = distinguishedname.DistinguishedName(request.dn)
            root = interfaces.IConnectedLDAPEntry(self.factory)
            d = root.lookup(dn)

            def _noEntry(fail):
                fail.trap(ldaperrors.LDAPNoSuchObject)
                return None

            d.addErrback(_noEntry)

            def _gotEntry(entry, auth):
                if entry is None:
                    raise ldaperrors.LDAPInvalidCredentials

                d = entry.bind(auth)

                def _cb(entry):
                    self.boundUser = entry
                    msg = pureldap.LDAPBindResponse(
                        resultCode=ldaperrors.Success.resultCode,
                        matchedDN=str(entry.dn))
                    return msg

                d.addCallback(_cb)
                return d

            d.addCallback(_gotEntry, request.auth)

            return d
Exemple #25
0
    def __init__(self, dn, attributes={}):
        """

        Initialize the object.

        @param dn: Distinguished Name of the object, as a string.

        @param attributes: Attributes of the object. A dictionary of
        attribute types to list of attribute values.

        """
        self._attributes=InsensitiveDict()
        self.dn = distinguishedname.DistinguishedName(dn)

        for k,vs in attributes.items():
            if k not in self._attributes:
                self._attributes[k] = []
            self._attributes[k].extend(vs)

        for k,vs in self._attributes.items():
            self._attributes[k] = self.buildAttributeSet(k, vs)
Exemple #26
0
    def _loadServiceLocationOverrides(self):
        serviceLocationOverride = {}
        cfg = loadConfig()
        for section in cfg.sections():
            if section.lower().startswith('service-location '):
                base = section[len('service-location '):].strip()

                host = None
                if cfg.has_option(section, 'host'):
                    host = cfg.get(section, 'host')
                    if not host:
                        host = None

                port = None
                if cfg.has_option(section, 'port'):
                    port = cfg.get(section, 'port')
                    if not port:
                        port = None

                dn = distinguishedname.DistinguishedName(stringValue=base)
                serviceLocationOverride[dn] = (host, port)
        return serviceLocationOverride
Exemple #27
0
    def handle_LDAPAddRequest(self, request, controls, reply):
        self.checkControls(controls)

        attributes = {}
        for name, vals in request.attributes:
            attributes.setdefault(name.value, sets.Set())
            attributes[name.value].update([x.value for x in vals])
        dn = distinguishedname.DistinguishedName(request.entry)
        rdn = str(dn.split()[0])
        parent = dn.up()
        root = interfaces.IConnectedLDAPEntry(self.factory)
        d = root.lookup(parent)

        def _gotEntry(parent):
            d = parent.addChild(rdn, attributes)
            return d

        d.addCallback(_gotEntry)

        def _report(entry):
            return pureldap.LDAPAddResponse(resultCode=0)

        d.addCallback(_report)
        return d
Exemple #28
0
 def __init__(self, dn, modifications=[]):
     if not isinstance(dn, distinguishedname.DistinguishedName):
         dn = distinguishedname.DistinguishedName(stringValue=dn)
     self.dn = dn
     self.modifications = modifications[:]
Exemple #29
0
 def testGT(self):
     dn1=dn.DistinguishedName('dc=example,dc=com')
     dn2=dn.DistinguishedName('dc=bar,dc=example,dc=com')
     self.failUnless(dn1 > dn2)
Exemple #30
0
 def testDN(self):
     proto=dn.DistinguishedName('dc=example,dc=com')
     d=dn.DistinguishedName(proto)
     self.assertEquals(str(d), 'dc=example,dc=com')