aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/test/test_strcred.py
blob: 7233a58e977fbe61fb72cb2324291411ab86e1ff (plain)
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.

"""
Tests for L{twisted.cred.strcred}.
"""

import os
import StringIO

from twisted import plugin
from twisted.trial import unittest
from twisted.cred import credentials, checkers, error, strcred
from twisted.plugins import cred_file, cred_anonymous
from twisted.python import usage
from twisted.python.filepath import FilePath
from twisted.python.fakepwd import UserDatabase

try:
    import crypt
except ImportError:
    crypt = None

try:
    import pwd
except ImportError:
    pwd = None

try:
    import spwd
except ImportError:
    spwd = None



def getInvalidAuthType():
    """
    Helper method to produce an auth type that doesn't exist.
    """
    invalidAuthType = 'ThisPluginDoesNotExist'
    while (invalidAuthType in
           [factory.authType for factory in strcred.findCheckerFactories()]):
        invalidAuthType += '_'
    return invalidAuthType



class TestPublicAPI(unittest.TestCase):

    def test_emptyDescription(self):
        """
        Test that the description string cannot be empty.
        """
        iat = getInvalidAuthType()
        self.assertRaises(strcred.InvalidAuthType, strcred.makeChecker, iat)
        self.assertRaises(
            strcred.InvalidAuthType, strcred.findCheckerFactory, iat)


    def test_invalidAuthType(self):
        """
        Test that an unrecognized auth type raises an exception.
        """
        iat = getInvalidAuthType()
        self.assertRaises(strcred.InvalidAuthType, strcred.makeChecker, iat)
        self.assertRaises(
            strcred.InvalidAuthType, strcred.findCheckerFactory, iat)



class TestStrcredFunctions(unittest.TestCase):

    def test_findCheckerFactories(self):
        """
        Test that findCheckerFactories returns all available plugins.
        """
        availablePlugins = list(strcred.findCheckerFactories())
        for plg in plugin.getPlugins(strcred.ICheckerFactory):
            self.assertIn(plg, availablePlugins)


    def test_findCheckerFactory(self):
        """
        Test that findCheckerFactory returns the first plugin
        available for a given authentication type.
        """
        self.assertIdentical(strcred.findCheckerFactory('file'),
                             cred_file.theFileCheckerFactory)



class TestMemoryChecker(unittest.TestCase):

    def setUp(self):
        self.admin = credentials.UsernamePassword('admin', 'asdf')
        self.alice = credentials.UsernamePassword('alice', 'foo')
        self.badPass = credentials.UsernamePassword('alice', 'foobar')
        self.badUser = credentials.UsernamePassword('x', 'yz')
        self.checker = strcred.makeChecker('memory:admin:asdf:alice:foo')


    def test_isChecker(self):
        """
        Verifies that strcred.makeChecker('memory') returns an object
        that implements the L{ICredentialsChecker} interface.
        """
        self.assertTrue(checkers.ICredentialsChecker.providedBy(self.checker))
        self.assertIn(credentials.IUsernamePassword,
                      self.checker.credentialInterfaces)


    def test_badFormatArgString(self):
        """
        Test that an argument string which does not contain user:pass
        pairs (i.e., an odd number of ':' characters) raises an exception.
        """
        self.assertRaises(strcred.InvalidAuthArgumentString,
                          strcred.makeChecker, 'memory:a:b:c')


    def test_memoryCheckerSucceeds(self):
        """
        Test that the checker works with valid credentials.
        """
        def _gotAvatar(username):
            self.assertEqual(username, self.admin.username)
        return (self.checker
                .requestAvatarId(self.admin)
                .addCallback(_gotAvatar))


    def test_memoryCheckerFailsUsername(self):
        """
        Test that the checker fails with an invalid username.
        """
        return self.assertFailure(self.checker.requestAvatarId(self.badUser),
                                  error.UnauthorizedLogin)


    def test_memoryCheckerFailsPassword(self):
        """
        Test that the checker fails with an invalid password.
        """
        return self.assertFailure(self.checker.requestAvatarId(self.badPass),
                                  error.UnauthorizedLogin)



class TestAnonymousChecker(unittest.TestCase):

    def test_isChecker(self):
        """
        Verifies that strcred.makeChecker('anonymous') returns an object
        that implements the L{ICredentialsChecker} interface.
        """
        checker = strcred.makeChecker('anonymous')
        self.assertTrue(checkers.ICredentialsChecker.providedBy(checker))
        self.assertIn(credentials.IAnonymous, checker.credentialInterfaces)


    def testAnonymousAccessSucceeds(self):
        """
        Test that we can log in anonymously using this checker.
        """
        checker = strcred.makeChecker('anonymous')
        request = checker.requestAvatarId(credentials.Anonymous())
        def _gotAvatar(avatar):
            self.assertIdentical(checkers.ANONYMOUS, avatar)
        return request.addCallback(_gotAvatar)



class TestUnixChecker(unittest.TestCase):
    users = {
        'admin': 'asdf',
        'alice': 'foo',
        }


    def _spwd(self, username):
        return (username, crypt.crypt(self.users[username], 'F/'),
                0, 0, 99999, 7, -1, -1, -1)


    def setUp(self):
        self.admin = credentials.UsernamePassword('admin', 'asdf')
        self.alice = credentials.UsernamePassword('alice', 'foo')
        self.badPass = credentials.UsernamePassword('alice', 'foobar')
        self.badUser = credentials.UsernamePassword('x', 'yz')
        self.checker = strcred.makeChecker('unix')

        # Hack around the pwd and spwd modules, since we can't really
        # go about reading your /etc/passwd or /etc/shadow files
        if pwd:
            database = UserDatabase()
            for username, password in self.users.items():
                database.addUser(
                    username, crypt.crypt(password, 'F/'),
                    1000, 1000, username, '/home/' + username, '/bin/sh')
            self.patch(pwd, 'getpwnam', database.getpwnam)
        if spwd:
            self._spwd_getspnam = spwd.getspnam
            spwd.getspnam = self._spwd


    def tearDown(self):
        if spwd:
            spwd.getspnam = self._spwd_getspnam


    def test_isChecker(self):
        """
        Verifies that strcred.makeChecker('unix') returns an object
        that implements the L{ICredentialsChecker} interface.
        """
        self.assertTrue(checkers.ICredentialsChecker.providedBy(self.checker))
        self.assertIn(credentials.IUsernamePassword,
                      self.checker.credentialInterfaces)


    def test_unixCheckerSucceeds(self):
        """
        Test that the checker works with valid credentials.
        """
        def _gotAvatar(username):
            self.assertEqual(username, self.admin.username)
        return (self.checker
                .requestAvatarId(self.admin)
                .addCallback(_gotAvatar))


    def test_unixCheckerFailsUsername(self):
        """
        Test that the checker fails with an invalid username.
        """
        return self.assertFailure(self.checker.requestAvatarId(self.badUser),
                                  error.UnauthorizedLogin)


    def test_unixCheckerFailsPassword(self):
        """
        Test that the checker fails with an invalid password.
        """
        return self.assertFailure(self.checker.requestAvatarId(self.badPass),
                                  error.UnauthorizedLogin)


    if None in (pwd, spwd, crypt):
        availability = []
        for module, name in ((pwd, "pwd"), (spwd, "swpd"), (crypt, "crypt")):
            if module is None:
                availability += [name]
        for method in (test_unixCheckerSucceeds,
                       test_unixCheckerFailsUsername,
                       test_unixCheckerFailsPassword):
            method.skip = ("Required module(s) are unavailable: " +
                           ", ".join(availability))



class TestFileDBChecker(unittest.TestCase):
    """
    Test for the --auth=file:... file checker.
    """

    def setUp(self):
        self.admin = credentials.UsernamePassword('admin', 'asdf')
        self.alice = credentials.UsernamePassword('alice', 'foo')
        self.badPass = credentials.UsernamePassword('alice', 'foobar')
        self.badUser = credentials.UsernamePassword('x', 'yz')
        self.filename = self.mktemp()
        FilePath(self.filename).setContent('admin:asdf\nalice:foo\n')
        self.checker = strcred.makeChecker('file:' + self.filename)


    def _fakeFilename(self):
        filename = '/DoesNotExist'
        while os.path.exists(filename):
            filename += '_'
        return filename


    def test_isChecker(self):
        """
        Verifies that strcred.makeChecker('memory') returns an object
        that implements the L{ICredentialsChecker} interface.
        """
        self.assertTrue(checkers.ICredentialsChecker.providedBy(self.checker))
        self.assertIn(credentials.IUsernamePassword,
                      self.checker.credentialInterfaces)


    def test_fileCheckerSucceeds(self):
        """
        Test that the checker works with valid credentials.
        """
        def _gotAvatar(username):
            self.assertEqual(username, self.admin.username)
        return (self.checker
                .requestAvatarId(self.admin)
                .addCallback(_gotAvatar))


    def test_fileCheckerFailsUsername(self):
        """
        Test that the checker fails with an invalid username.
        """
        return self.assertFailure(self.checker.requestAvatarId(self.badUser),
                                  error.UnauthorizedLogin)


    def test_fileCheckerFailsPassword(self):
        """
        Test that the checker fails with an invalid password.
        """
        return self.assertFailure(self.checker.requestAvatarId(self.badPass),
                                  error.UnauthorizedLogin)


    def test_failsWithEmptyFilename(self):
        """
        Test that an empty filename raises an error.
        """
        self.assertRaises(ValueError, strcred.makeChecker, 'file')
        self.assertRaises(ValueError, strcred.makeChecker, 'file:')


    def test_warnWithBadFilename(self):
        """
        When the file auth plugin is given a file that doesn't exist, it
        should produce a warning.
        """
        oldOutput = cred_file.theFileCheckerFactory.errorOutput
        newOutput = StringIO.StringIO()
        cred_file.theFileCheckerFactory.errorOutput = newOutput
        checker = strcred.makeChecker('file:' + self._fakeFilename())
        cred_file.theFileCheckerFactory.errorOutput = oldOutput
        self.assertIn(cred_file.invalidFileWarning, newOutput.getvalue())



class TestSSHChecker(unittest.TestCase):
    """
    Tests for the --auth=sshkey:... checker.  The majority of the tests for the
    ssh public key database checker are in
    L{twisted.conch.test.test_checkers.SSHPublicKeyDatabaseTestCase}.
    """

    try:
        import Crypto
        import pyasn1
    except ImportError:
        skip = "PyCrypto is not available"


    def test_isChecker(self):
        """
        Verifies that strcred.makeChecker('sshkey') returns an object
        that implements the L{ICredentialsChecker} interface.
        """
        sshChecker = strcred.makeChecker('sshkey')
        self.assertTrue(checkers.ICredentialsChecker.providedBy(sshChecker))
        self.assertIn(
            credentials.ISSHPrivateKey, sshChecker.credentialInterfaces)



class DummyOptions(usage.Options, strcred.AuthOptionMixin):
    """
    Simple options for testing L{strcred.AuthOptionMixin}.
    """



class TestCheckerOptions(unittest.TestCase):

    def test_createsList(self):
        """
        Test that the --auth command line creates a list in the
        Options instance and appends values to it.
        """
        options = DummyOptions()
        options.parseOptions(['--auth', 'memory'])
        self.assertEqual(len(options['credCheckers']), 1)
        options = DummyOptions()
        options.parseOptions(['--auth', 'memory', '--auth', 'memory'])
        self.assertEqual(len(options['credCheckers']), 2)


    def test_invalidAuthError(self):
        """
        Test that the --auth command line raises an exception when it
        gets a parameter it doesn't understand.
        """
        options = DummyOptions()
        # If someone adds a 'ThisPluginDoesNotExist' then this unit
        # test should still run.
        invalidParameter = getInvalidAuthType()
        self.assertRaises(
            usage.UsageError,
            options.parseOptions, ['--auth', invalidParameter])
        self.assertRaises(
            usage.UsageError,
            options.parseOptions, ['--help-auth-type', invalidParameter])


    def test_createsDictionary(self):
        """
        Test that the --auth command line creates a dictionary
        mapping supported interfaces to the list of credentials
        checkers that support it.
        """
        options = DummyOptions()
        options.parseOptions(['--auth', 'memory', '--auth', 'anonymous'])
        chd = options['credInterfaces']
        self.assertEqual(len(chd[credentials.IAnonymous]), 1)
        self.assertEqual(len(chd[credentials.IUsernamePassword]), 1)
        chdAnonymous = chd[credentials.IAnonymous][0]
        chdUserPass = chd[credentials.IUsernamePassword][0]
        self.assertTrue(checkers.ICredentialsChecker.providedBy(chdAnonymous))
        self.assertTrue(checkers.ICredentialsChecker.providedBy(chdUserPass))
        self.assertIn(credentials.IAnonymous,
                      chdAnonymous.credentialInterfaces)
        self.assertIn(credentials.IUsernamePassword,
                      chdUserPass.credentialInterfaces)


    def test_credInterfacesProvidesLists(self):
        """
        Test that when two --auth arguments are passed along which
        support the same interface, a list with both is created.
        """
        options = DummyOptions()
        options.parseOptions(['--auth', 'memory', '--auth', 'unix'])
        self.assertEqual(
            options['credCheckers'],
            options['credInterfaces'][credentials.IUsernamePassword])


    def test_listDoesNotDisplayDuplicates(self):
        """
        Test that the list for --help-auth does not duplicate items.
        """
        authTypes = []
        options = DummyOptions()
        for cf in options._checkerFactoriesForOptHelpAuth():
            self.assertNotIn(cf.authType, authTypes)
            authTypes.append(cf.authType)


    def test_displaysListCorrectly(self):
        """
        Test that the --help-auth argument correctly displays all
        available authentication plugins, then exits.
        """
        newStdout = StringIO.StringIO()
        options = DummyOptions()
        options.authOutput = newStdout
        self.assertRaises(SystemExit, options.parseOptions, ['--help-auth'])
        for checkerFactory in strcred.findCheckerFactories():
            self.assertIn(checkerFactory.authType, newStdout.getvalue())


    def test_displaysHelpCorrectly(self):
        """
        Test that the --help-auth-for argument will correctly display
        the help file for a particular authentication plugin.
        """
        newStdout = StringIO.StringIO()
        options = DummyOptions()
        options.authOutput = newStdout
        self.assertRaises(
            SystemExit, options.parseOptions, ['--help-auth-type', 'file'])
        for line in cred_file.theFileCheckerFactory.authHelp:
            if line.strip():
                self.assertIn(line.strip(), newStdout.getvalue())


    def test_unexpectedException(self):
        """
        When the checker specified by --auth raises an unexpected error, it
        should be caught and re-raised within a L{usage.UsageError}.
        """
        options = DummyOptions()
        err = self.assertRaises(usage.UsageError, options.parseOptions,
                                ['--auth', 'file'])
        self.assertEqual(str(err),
                          "Unexpected error: 'file' requires a filename")



class OptionsForUsernamePassword(usage.Options, strcred.AuthOptionMixin):
    supportedInterfaces = (credentials.IUsernamePassword,)



class OptionsForUsernameHashedPassword(usage.Options, strcred.AuthOptionMixin):
    supportedInterfaces = (credentials.IUsernameHashedPassword,)



class OptionsSupportsAllInterfaces(usage.Options, strcred.AuthOptionMixin):
    supportedInterfaces = None



class OptionsSupportsNoInterfaces(usage.Options, strcred.AuthOptionMixin):
    supportedInterfaces = []



class TestLimitingInterfaces(unittest.TestCase):
    """
    Tests functionality that allows an application to limit the
    credential interfaces it can support. For the purposes of this
    test, we use IUsernameHashedPassword, although this will never
    really be used by the command line.

    (I have, to date, not thought of a half-decent way for a user to
    specify a hash algorithm via the command-line. Nor do I think it's
    very useful.)

    I should note that, at first, this test is counter-intuitive,
    because we're using the checker with a pre-defined hash function
    as the 'bad' checker. See the documentation for
    L{twisted.cred.checkers.FilePasswordDB.hash} for more details.
    """

    def setUp(self):
        self.filename = self.mktemp()
        file(self.filename, 'w').write('admin:asdf\nalice:foo\n')
        self.goodChecker = checkers.FilePasswordDB(self.filename)
        self.badChecker = checkers.FilePasswordDB(
            self.filename, hash=self._hash)
        self.anonChecker = checkers.AllowAnonymousAccess()


    def _hash(self, networkUsername, networkPassword, storedPassword):
        """
        A dumb hash that doesn't really do anything.
        """
        return networkPassword


    def test_supportsInterface(self):
        """
        Test that the supportsInterface method behaves appropriately.
        """
        options = OptionsForUsernamePassword()
        self.assertTrue(
            options.supportsInterface(credentials.IUsernamePassword))
        self.assertFalse(
            options.supportsInterface(credentials.IAnonymous))
        self.assertRaises(
            strcred.UnsupportedInterfaces, options.addChecker,
            self.anonChecker)


    def test_supportsAllInterfaces(self):
        """
        Test that the supportsInterface method behaves appropriately
        when the supportedInterfaces attribute is None.
        """
        options = OptionsSupportsAllInterfaces()
        self.assertTrue(
            options.supportsInterface(credentials.IUsernamePassword))
        self.assertTrue(
            options.supportsInterface(credentials.IAnonymous))


    def test_supportsCheckerFactory(self):
        """
        Test that the supportsCheckerFactory method behaves appropriately.
        """
        options = OptionsForUsernamePassword()
        fileCF = cred_file.theFileCheckerFactory
        anonCF = cred_anonymous.theAnonymousCheckerFactory
        self.assertTrue(options.supportsCheckerFactory(fileCF))
        self.assertFalse(options.supportsCheckerFactory(anonCF))


    def test_canAddSupportedChecker(self):
        """
        Test that when addChecker is called with a checker that
        implements at least one of the interfaces our application
        supports, it is successful.
        """
        options = OptionsForUsernamePassword()
        options.addChecker(self.goodChecker)
        iface = options.supportedInterfaces[0]
        # Test that we did get IUsernamePassword
        self.assertIdentical(
            options['credInterfaces'][iface][0], self.goodChecker)
        self.assertIdentical(options['credCheckers'][0], self.goodChecker)
        # Test that we didn't get IUsernameHashedPassword
        self.assertEqual(len(options['credInterfaces'][iface]), 1)
        self.assertEqual(len(options['credCheckers']), 1)


    def test_failOnAddingUnsupportedChecker(self):
        """
        Test that when addChecker is called with a checker that does
        not implement any supported interfaces, it fails.
        """
        options = OptionsForUsernameHashedPassword()
        self.assertRaises(strcred.UnsupportedInterfaces,
                          options.addChecker, self.badChecker)


    def test_unsupportedInterfaceError(self):
        """
        Test that the --auth command line raises an exception when it
        gets a checker we don't support.
        """
        options = OptionsSupportsNoInterfaces()
        authType = cred_anonymous.theAnonymousCheckerFactory.authType
        self.assertRaises(
            usage.UsageError,
            options.parseOptions, ['--auth', authType])


    def test_helpAuthLimitsOutput(self):
        """
        Test that --help-auth will only list checkers that purport to
        supply at least one of the credential interfaces our
        application can use.
        """
        options = OptionsForUsernamePassword()
        for factory in options._checkerFactoriesForOptHelpAuth():
            invalid = True
            for interface in factory.credentialInterfaces:
                if options.supportsInterface(interface):
                    invalid = False
            if invalid:
                raise strcred.UnsupportedInterfaces()


    def test_helpAuthTypeLimitsOutput(self):
        """
        Test that --help-auth-type will display a warning if you get
        help for an authType that does not supply at least one of the
        credential interfaces our application can use.
        """
        options = OptionsForUsernamePassword()
        # Find an interface that we can use for our test
        invalidFactory = None
        for factory in strcred.findCheckerFactories():
            if not options.supportsCheckerFactory(factory):
                invalidFactory = factory
                break
        self.assertNotIdentical(invalidFactory, None)
        # Capture output and make sure the warning is there
        newStdout = StringIO.StringIO()
        options.authOutput = newStdout
        self.assertRaises(SystemExit, options.parseOptions,
                          ['--help-auth-type', 'anonymous'])
        self.assertIn(strcred.notSupportedWarning, newStdout.getvalue())