This file is indexed.

/usr/lib/python2.7/dist-packages/twext/who/directory.py is in python-twext 0.1.b2.dev15059-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
# -*- test-case-name: twext.who.test.test_directory -*-
##
# Copyright (c) 2006-2015 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##

"""
Generic directory service base implementation
"""

__all__ = [
    "DirectoryService",
    "DirectoryRecord",
]

from zope.interface import implementer, directlyProvides

from twisted.python.constants import (
    Names, NamedConstant,
    Values, ValueConstant,
    Flags, FlagConstant,
)
from twisted.internet.defer import inlineCallbacks, returnValue
from twisted.internet.defer import succeed, fail
from twisted.cred.credentials import DigestedCredentials

from .idirectory import (
    InvalidDirectoryRecordError,
    QueryNotSupportedError, NotAllowedError,
    FieldName, RecordType,
    IDirectoryService, IDirectoryRecord,
    IPlaintextPasswordVerifier, IHTTPDigestVerifier,
)
from .expression import CompoundExpression, Operand, MatchExpression
from .util import uniqueResult, describe, ConstantsContainer



@implementer(IDirectoryService)
class DirectoryService(object):
    """
    Generic (and abstract) implementation of L{IDirectoryService}.

    Most of the C{recordsWith*} methods call L{recordsWithFieldValue}, which in
    turn calls L{recordsFromExpression} with a corresponding
    L{MatchExpression}.

    L{recordsFromExpression} relies on L{recordsFromNonCompoundExpression} for
    all expression types other than L{CompoundExpression}, which it handles
    directly.

    L{recordsFromNonCompoundExpression} (and therefore most uses of the other
    methods) will always fail with a L{QueryNotSupportedError}.

    A subclass should therefore override L{recordsFromNonCompoundExpression}
    with an implementation that handles any queries that it can support (which
    should include L{MatchExpression}) and calls its superclass' implementation
    with any query it cannot support.

    A subclass may override L{recordsFromExpression} if it is to support
    L{CompoundExpression}s with operands other than L{Operand.AND} and
    L{Operand.OR}.

    A subclass may override L{recordsFromExpression} if it is built on top
    of a directory service that supports compound expressions, as that may be
    more effient than relying on L{DirectoryService}'s implementation.

    L{updateRecords} and L{removeRecords} will fail with L{NotAllowedError}
    when asked to modify data.
    A subclass should override these methods if is to allow editing of
    directory information.

    @cvar recordType: a L{Names} class or compatible object (eg.
        L{ConstantsContainer}) which contains the L{NamedConstant}s denoting
        the record types that are supported by this directory service.

    @cvar fieldName: a L{Names} class or compatible object (eg.
        L{ConstantsContainer}) which contains the L{NamedConstant}s denoting
        the record field names that are supported by this directory service.

    @cvar normalizedFields: a L{dict} mapping of (ie. L{NamedConstant}s
        contained in the C{fieldName} class variable) to callables that take
        a field value (a L{unicode}) and return a normalized field value (also
        a L{unicode}).
    """

    recordType = ConstantsContainer(())
    fieldName = FieldName

    normalizedFields = {
        FieldName.emailAddresses: lambda e: e.lower(),
    }


    def __init__(self, realmName):
        """
        @param realmName: a realm name
        @type realmName: L{unicode}
        """
        self.realmName = realmName


    def __repr__(self):
        return (
            "<{self.__class__.__name__} {self.realmName!r}>"
            .format(self=self)
        )


    def recordTypes(self):
        return self.recordType.iterconstants()


    def recordsFromNonCompoundExpression(
        self, expression, recordTypes=None, records=None,
        limitResults=None, timeoutSeconds=None
    ):
        """
        Finds records matching a non-compound expression.

        @note: This method is called by L{recordsFromExpression} to handle
            all expressions other than L{CompoundExpression}.
            This implementation always fails with L{QueryNotSupportedError}.
            Subclasses should override this in order to handle additional
            expression types, and call on the superclass' implementation
            for other expression types.

        @note: This interface is the same as L{recordsFromExpression}, except
            for the additional C{records} argument.

        @param expression: an expression to apply
        @type expression: L{object}

        @param recordTypes: the record types to match
        @type recordTypes: an iterable of L{NamedConstant}, or None for no
            filtering

        @param records: a set of records to limit the search to. C{None} if
            the whole directory should be searched.
            This is provided by L{recordsFromExpression} when it has already
            narrowed down results to a set of records.
            That is, it's a performance optimization; ignoring this and
            searching the entire directory will also work.
        @type records: L{set} or L{frozenset}

        @return: The matching records.
        @rtype: deferred iterable of L{IDirectoryRecord}s

        @raises: L{QueryNotSupportedError} if the expression is not
            supported by this directory service.
        """
        if records is not None:
            for _ignore_record in records:
                break
            else:
                return succeed(())

        return fail(QueryNotSupportedError(
            "Unknown expression: {0}".format(expression)
        ))


    @inlineCallbacks
    def recordsFromCompoundExpression(
        self, expression, recordTypes=None, records=None,
        limitResults=None, timeoutSeconds=None
    ):
        """
        Finds records matching a compound expression.

        @note: This method is called by L{recordsFromExpression} to handle
            all L{CompoundExpression}s.

        @note: This interface is the same as L{recordsFromExpression}, except
            for the additional C{records} argument.

        @param expression: an expression to apply
        @type expression: L{CompoundExpression}

        @param recordTypes: the record types to match
        @type recordTypes: an iterable of L{NamedConstant}, or None for no
            filtering

        @param records: a set of records to limit the search to. C{None} if
            the whole directory should be searched.
            This is provided by L{recordsFromExpression} when it has already
            narrowed down results to a set of records.
            That is, it's a performance optimization; ignoring this and
            searching the entire directory will also work.
        @type records: L{set} or L{frozenset}

        @return: The matching records.
        @rtype: deferred iterable of L{IDirectoryRecord}s

        @raises: L{QueryNotSupportedError} if the expression is not
            supported by this directory service.
        """
        operand = expression.operand
        subExpressions = iter(expression.expressions)

        try:
            subExpression = subExpressions.next()
        except StopIteration:
            returnValue(())

        results = set((
            yield self.recordsFromExpression(
                subExpression, recordTypes=recordTypes, records=records
            )
        ))

        for subExpression in subExpressions:
            if operand == Operand.AND:
                if not results:
                    # No need to bother continuing here
                    returnValue(())

                records = results
            else:
                records = None

            recordsMatchingExpression = frozenset((
                yield self.recordsFromExpression(
                    subExpression, recordTypes=recordTypes, records=records
                )
            ))

            if operand == Operand.AND:
                results &= recordsMatchingExpression
            elif operand == Operand.OR:
                results |= recordsMatchingExpression
            else:
                raise QueryNotSupportedError(
                    "Unknown operand: {0}".format(operand)
                )

        returnValue(results)


    def recordsFromExpression(
        self, expression, recordTypes=None, records=None,
        limitResults=None, timeoutSeconds=None
    ):
        """
        @note: This interface is the same as
            L{IDirectoryService.recordsFromExpression}, except for the
            additional C{records} argument.
        """
        if isinstance(expression, CompoundExpression):
            return self.recordsFromCompoundExpression(
                expression, recordTypes=recordTypes,
                limitResults=limitResults, timeoutSeconds=timeoutSeconds
            )
        else:
            return self.recordsFromNonCompoundExpression(
                expression, recordTypes=recordTypes,
                limitResults=limitResults, timeoutSeconds=timeoutSeconds
            )


    def recordsWithFieldValue(
        self, fieldName, value, recordTypes=None,
        limitResults=None, timeoutSeconds=None
    ):
        return self.recordsFromExpression(
            MatchExpression(fieldName, value),
            recordTypes=recordTypes,
            limitResults=limitResults,
            timeoutSeconds=timeoutSeconds
        )


    @inlineCallbacks
    def recordWithUID(self, uid, timeoutSeconds=None):
        returnValue(uniqueResult(
            (yield self.recordsWithFieldValue(
                FieldName.uid, uid, timeoutSeconds=timeoutSeconds
            ))
        ))


    @inlineCallbacks
    def recordWithGUID(self, guid, timeoutSeconds=None):
        returnValue(uniqueResult(
            (yield self.recordsWithFieldValue(
                FieldName.guid, guid, timeoutSeconds=timeoutSeconds
            ))
        ))


    def recordsWithRecordType(
        self, recordType, limitResults=None, timeoutSeconds=None
    ):
        return self.recordsWithFieldValue(
            FieldName.recordType, recordType,
            limitResults=limitResults, timeoutSeconds=timeoutSeconds
        )


    @inlineCallbacks
    def recordWithShortName(self, recordType, shortName, timeoutSeconds=None):
        returnValue(
            uniqueResult(
                (
                    yield self.recordsFromExpression(
                        MatchExpression(
                            FieldName.shortNames, shortName
                        ),
                        recordTypes=[recordType],
                        timeoutSeconds=timeoutSeconds
                    )
                )
            )
        )


    def recordsWithEmailAddress(
        self, emailAddress, limitResults=None, timeoutSeconds=None
    ):
        return self.recordsWithFieldValue(
            FieldName.emailAddresses,
            emailAddress,
            limitResults=limitResults,
            timeoutSeconds=timeoutSeconds
        )


    def updateRecords(self, records, create=False):
        for _ignore_record in records:
            return fail(NotAllowedError("Record updates not allowed."))
        return succeed(None)


    def removeRecords(self, uids):
        for _ignore_uid in uids:
            return fail(NotAllowedError("Record removal not allowed."))
        return succeed(None)


    def flush(self):
        return succeed(None)



@implementer(IDirectoryRecord)
class DirectoryRecord(object):
    """
    Generic implementation of L{IDirectoryService}.

    This is an incomplete implementation of L{IDirectoryRecord}.

    L{groups} will always fail with L{NotImplementedError} and L{members} will
    do so if this is a group record.
    A subclass should override these methods to support group membership and
    complete this implementation.

    @cvar requiredFields: an iterable of field names that must be present in
        all directory records.
    """

    requiredFields = (
        FieldName.uid,
        FieldName.recordType,
    )


    def __init__(self, service, fields):
        for fieldName in self.requiredFields:
            if fieldName not in fields or not fields[fieldName]:
                raise InvalidDirectoryRecordError(
                    "{0} field is required.".format(fieldName),
                    fields
                )

            if service.fieldName.isMultiValue(fieldName):
                values = fields[fieldName]
                for value in values:
                    if not value:
                        raise InvalidDirectoryRecordError(
                            "{0} field must not be empty.".format(fieldName),
                            fields
                        )

        if (
            fields[FieldName.recordType] not in
            service.recordType.iterconstants()
        ):
            raise InvalidDirectoryRecordError(
                "Unknown record type: {0!r} is not in {1!r}.".format(
                    fields[FieldName.recordType],
                    tuple(service.recordType.iterconstants()),
                ),
                fields
            )

        def checkType(name, value):
            expectedType = service.fieldName.valueType(name)

            if issubclass(expectedType, Flags):
                expectedType = FlagConstant
            elif issubclass(expectedType, Values):
                expectedType = ValueConstant
            elif issubclass(expectedType, Names):
                expectedType = NamedConstant

            if value is not None and not isinstance(value, expectedType):
                raise InvalidDirectoryRecordError(
                    "Value {0!r} for field {1} is not of type {2}".format(
                        value, name, expectedType
                    ),
                    fields
                )

        # Normalize fields
        normalizedFields = {}
        for name, value in fields.items():
            if not isinstance(name, NamedConstant):
                raise InvalidDirectoryRecordError(
                    "Field name {} is not a named constant".format(name),
                    fields
                )

            normalize = service.normalizedFields.get(name, None)

            if normalize is None:
                normalizedValue = value
            else:
                if service.fieldName.isMultiValue(name):
                    normalizedValue = tuple((normalize(v) for v in value))
                else:
                    normalizedValue = normalize(value)

            if service.fieldName.isMultiValue(name):
                for v in normalizedValue:
                    checkType(name, v)
            else:
                checkType(name, normalizedValue)

            normalizedFields[name] = normalizedValue

        self.service = service
        self.fields = normalizedFields

        if self.service.fieldName.password in self.fields:
            directlyProvides(
                self, IPlaintextPasswordVerifier, IHTTPDigestVerifier
            )


    def __repr__(self):
        try:
            return (
                "<{self.__class__.__name__} ({recordType}){shortName}>".format(
                    self=self,
                    recordType=describe(self.recordType),
                    shortName=self.shortNames[0],
                )
            )
        except (AttributeError, IndexError):
            return (
                "<{self.__class__.__name__} {uid}>".format(
                    self=self,
                    uid=self.uid,
                )
            )


    def __hash__(self):
        return hash(self.uid)


    def __eq__(self, other):
        if IDirectoryRecord.implementedBy(other.__class__):
            return (
                self.service == other.service and
                self.fields == other.fields
            )
        return NotImplemented


    def __ne__(self, other):
        eq = self.__eq__(other)
        if eq is NotImplemented:
            return NotImplemented
        return not eq


    def __getattr__(self, name):
        try:
            fieldName = self.service.fieldName.lookupByName(name)
        except ValueError:
            raise AttributeError(name)

        try:
            return self.fields[fieldName]
        except KeyError:
            raise AttributeError(name)


    def description(self):
        """
        Generate a string description of this directory record.

        @return: A description.
        @rtype: L{unicode}
        """
        def describeValue(value):
            if hasattr(value, "description"):
                value = value.description
            else:
                value = unicode(value)

            return value

        values = {}

        for fieldName in self.service.fieldName.iterconstants():
            if fieldName not in self.fields:
                continue

            value = self.fields[fieldName]

            if hasattr(fieldName, "description"):
                name = fieldName.description
            else:
                name = unicode(fieldName.name)

            if self.service.fieldName.isMultiValue(fieldName):
                values[name] = ", ".join(describeValue(v) for v in value)
            else:
                values[name] = describeValue(value)

        description = [self.__class__.__name__, u":"]

        for name in sorted(values.iterkeys()):
            description.append(u"\n  {0} = {1}".format(name, values[name]))

        description.append(u"\n")

        return u"".join(description)


    def members(self):
        if self.recordType == RecordType.group:
            return fail(
                NotImplementedError("Subclasses must implement members()")
            )
        return succeed(())


    def groups(self):
        return fail(NotImplementedError("Subclasses must implement groups()"))


    def addMembers(self, members):
        return fail(NotAllowedError("Membership updates not allowed."))


    def removeMembers(self, members):
        return fail(NotAllowedError("Membership updates not allowed."))


    def setMembers(self, members):
        return fail(NotAllowedError("Membership updates not allowed."))


    #
    # Verifiers for twext.who.checker stuff.
    #

    def verifyPlaintextPassword(self, password):
        if self.password == password:
            return succeed(True)
        else:
            return succeed(False)


    def verifyHTTPDigest(
        self, username, realm, uri, nonce, cnonce,
        algorithm, nc, qop, response, method,
    ):
        helperCreds = DigestedCredentials(
            username, method, realm,
            dict(
                realm=realm,
                uri=uri,
                nonce=nonce,
                cnonce=cnonce,
                algorithm=algorithm,
                nc=nc,
                qop=qop,
                response=response
            )
        )

        return succeed(helperCreds.checkPassword(self.password))