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.assertEqual(fromString, fromList) fromStringToText = fromString.getText() fromListToText = fromList.getText() assert fromStringToText == fromListToText canon = fromStringToText # DNs equal their byte string representation. Note this does # not mean they equal all the possible string # representations -- just the canonical one. self.assertEqual(fromString, canon) self.assertEqual(fromList, canon) self.assertEqual(canon, fromString) self.assertEqual(canon, fromList) # DNs can be used interchangeably with their canonical # string representation as hash keys. self.assertEqual(hash(fromString), hash(canon)) self.assertEqual(hash(fromList), hash(canon)) self.assertEqual(hash(canon), hash(fromString)) self.assertEqual(hash(canon), hash(fromList))
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: 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()) root = interfaces.IConnectedLDAPEntry(self.factory) d = root.lookup(dn) def _gotEntry(entry): d = entry.move(newdn) return d def _report(entry): return pureldap.LDAPModifyDNResponse(resultCode=0) d.addCallback(_gotEntry) d.addCallback(_report) return d
def testDeleteChild(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="cn=foo", attributes={ "objectClass": ["a", "b"], "cn": ["foo"], }, ) bar = a.addChild( rdn="cn=bar", attributes={ "objectClass": ["a", "b"], "cn": ["bar"], }, ) d = a.diffTree(b) d.addCallback( self.assertEqual, [ delta.DeleteOp(bar), delta.DeleteOp(foo), ], ) return d
def main(): import sys from twisted.python import log log.startLogging(sys.stderr, setStdout=0) config = { "base": distinguishedname.DistinguishedName("ou=People,dc=example,dc=com"), "serviceLocationOverrides": { distinguishedname.DistinguishedName("dc=example,dc=com"): ( "localhost", 10389, ), }, } d = search(config) def _show(results): for item in results: print(item) d.addCallback(_show) d.addErrback(defer.logError) d.addBoth(lambda _: reactor.stop()) reactor.run()
def main(cfg, fromDN, toDN, binddn, bindPassword): fromDN = distinguishedname.DistinguishedName(stringValue=fromDN) toDN = distinguishedname.DistinguishedName(stringValue=toDN) c = ldapconnector.LDAPClientCreator(reactor, ldapclient.LDAPClient) d = c.connect(dn=fromDN, overrides=cfg.getServiceLocationOverrides()) def _bind(proto, binddn, bindPassword): if binddn: pwd = bindPassword if pwd is None: pwd = getpass.getpass("Password for %s: " % binddn) d = proto.bind(binddn, pwd) else: d = proto.bind() d.addCallback(lambda _: proto) return d d.addCallback(_bind, binddn, bindPassword) d.addCallback(move, fromDN, toDN) d.addErrback(error) d.addBoth(lambda x: reactor.stop()) reactor.run() sys.exit(exitStatus)
def __init__(self, baseDN, serviceLocationOverrides=None): self.baseDN = distinguishedname.DistinguishedName(baseDN) self.serviceLocationOverrides = {} if serviceLocationOverrides is not None: for k, v in serviceLocationOverrides.items(): dn = distinguishedname.DistinguishedName(k) self.serviceLocationOverrides[dn] = v
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
def cb(children): self.assertEqual(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] six.assertCountEqual(self, got, want)
def test_parent_child(self): """ The parent is greater than the child. """ dn1=dn.DistinguishedName('dc=example,dc=com') dn2=dn.DistinguishedName('dc=and,dc=example,dc=com') self.assertLess(dn2, dn1) self.assertGreater(dn1, dn2)
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.assertItemsEqual(got, want)
def cb2(children): self.assertEqual(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.assertCountEqual(got, want)
def coerce(self, *a, **kw): val = super(LDAPDN, self).coerce(*a, **kw) try: dn = distinguishedname.DistinguishedName(stringValue=val) except distinguishedname.InvalidRelativeDistinguishedName, e: raise annotate.InputError, \ "%r is not a valid LDAP DN: %s" % (val, e)
def _gotUPNResult(results): if len(results) != 1: # Not exactly one result, so this might not be an UNP. return distinguishedname.DistinguishedName(request.dn) # A single result, so the UPN might exist. return results[0].dn
def console_script(): import sys, os from twisted.python import log log.startLogging(sys.stderr, setStdout=0) try: config = MyOptions() config.parseOptions() except usage.UsageError as ue: print("%s:" % sys.argv[0], ue, file=sys.stderr) sys.exit(1) bindPassword = None if config.opts["bind-auth-fd"]: f = os.fdopen(config.opts["bind-auth-fd"]) bindPassword = f.readline() assert bindPassword[-1] == "\n" bindPassword = bindPassword[:-1] f.close() s = PasswdClientFactory( dnlist=config.opts["dnlist"], binddn=config.opts["binddn"], bindPassword=bindPassword, generatePasswords=config.opts["generate"], ) dn = distinguishedname.DistinguishedName(stringValue=config.opts["binddn"]) c = ldapconnector.LDAPConnector(reactor, dn, s, overrides=config.opts["service-location"]) c.connect() reactor.run() sys.exit(exitStatus)
def cb(children): self.assertEqual(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() six.assertCountEqual(self, got, want)
def test_exception_with_dn(self): """Exception with a distinguished name""" dn = distinguishedname.DistinguishedName( stringValue='dc=example,dc=org') exception = ldaperrors.LDAPNoSuchObject(dn) self.assertEqual(exception.toWire(), b'noSuchObject: dc=example,dc=org')
def childFactory(self, context, name): unquoted = uriUnquote(name) try: dn = distinguishedname.DistinguishedName(stringValue=unquoted) except distinguishedname.InvalidRelativeDistinguishedName, e: # TODO There's no way to throw a FormException at this stage. return None
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.getText())
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'], })
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=self.dn.getText(), newrdn=newrdn.getText(), deleteoldrdn=1, newSuperior=newSuperior.getText()) d = self.client.send(op) d.addCallback(self._cbMoveDone, newDN) return d
def addChild(self, rdn, attributes): self._checkState() a = [] if attributes.get('objectClass', None): a.append(('objectClass', attributes['objectClass'])) del attributes['objectClass'] attributes = a + sorted(attributes.items()) del a rdn = distinguishedname.RelativeDistinguishedName(rdn) dn = distinguishedname.DistinguishedName(listOfRDNs=(rdn, ) + self.dn.split()) ldapAttrs = [] for attrType, values in attributes: ldapAttrType = pureldap.LDAPAttributeDescription(attrType) lst = [] for value in values: if (isinstance(value, six.text_type)): value = value.encode('utf-8') lst.append(pureldap.LDAPAttributeValue(value)) ldapValues = pureber.BERSet(lst) ldapAttrs.append((ldapAttrType, ldapValues)) op = pureldap.LDAPAddRequest(entry=dn.getText(), attributes=ldapAttrs) d = self.client.send(op) d.addCallback(self._cbAddDone, dn) return d
def test_lookup_deep_dn(self): """Entry lookup with a DN instance returns entry instance with this DN""" dn = distinguishedname.DistinguishedName( "cn=bar,ou=metasyntactic,dc=example,dc=com") d = self.root.lookup(dn) d.addCallback(self.assertEqual, self.bar) return d
def _get(path, dn): path = to_unicode(path) dn = distinguishedname.DistinguishedName(dn) l = list(dn.split()) assert len(l) >= 1 l.reverse() parser = StoreParsedLDIF() entry = os.path.join(path, *[u'%s.dir' % rdn.getText() for rdn in l[:-1]]) entry = os.path.join(entry, u'%s.ldif' % l[-1].getText()) f = open(entry, 'rb') while 1: data = f.read(8192) if not data: break parser.dataReceived(data) parser.connectionLost(failure.Failure(error.ConnectionDone())) assert parser.done entries = parser.seen if len(entries) == 0: raise LDIFTreeEntryContainsNoEntries() elif len(entries) > 1: raise LDIFTreeEntryContainsMultipleEntries(entries) else: return entries[0]
def _sync_children(self): children = [] try: filenames = os.listdir(self.path) except OSError as e: if e.errno == errno.ENOENT: pass else: raise else: seen = set() for fn in filenames: base, ext = os.path.splitext(fn) if ext not in [u'.dir', u'.ldif']: continue if base in seen: continue seen.add(base) dn = distinguishedname.DistinguishedName(listOfRDNs=( (distinguishedname.RelativeDistinguishedName(base), ) + self.dn.split())) e = self.__class__(os.path.join(self.path, base + u'.dir'), dn) children.append(e) return children
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.assertEqual(fail.value.message, dn) d.addCallbacks(testutil.mustRaise, eb) return d
def test_lookup_fail_outOfTree(self): dn = distinguishedname.DistinguishedName('dc=invalid') d = self.root.lookup(dn) def eb(fail): fail.trap(ldaperrors.LDAPNoSuchObject) self.assertEqual(fail.value.message, dn) d.addCallbacks(testutil.mustRaise, eb) 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
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)
def cb(children): self.assertEqual(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.assertCountEqual(got, want)
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