Example #1
0
 def test_112(self):
     args = {'openid.assoc_handle': 'fa1f5ff0-cde4-11dc-a183-3714bfd55ca8',
             'openid.claimed_id': 'http://binkley.lan/user/test01',
             'openid.identity': 'http://test01.binkley.lan/',
             'openid.mode': 'id_res',
             'openid.ns': 'http://specs.openid.net/auth/2.0',
             'openid.ns.pape': 'http://specs.openid.net/extensions/pape/1.0',
             'openid.op_endpoint': 'http://binkley.lan/server',
             'openid.pape.auth_policies': 'none',
             'openid.pape.auth_time': '2008-01-28T20:42:36Z',
             'openid.pape.nist_auth_level': '0',
             'openid.response_nonce': '2008-01-28T21:07:04Z99Q=',
             'openid.return_to': 'http://binkley.lan:8001/process?janrain_nonce=2008-01-28T21%3A07%3A02Z0tMIKx',
             'openid.sig': 'YJlWH4U6SroB1HoPkmEKx9AyGGg=',
             'openid.signed': 'assoc_handle,identity,response_nonce,return_to,claimed_id,op_endpoint,pape.auth_time,ns.pape,pape.nist_auth_level,pape.auth_policies'
             }
     self.failUnlessEqual(OPENID2_NS, args['openid.ns'])
     incoming = Message.fromPostArgs(args)
     self.failUnless(incoming.isOpenID2())
     car = self.consumer._createCheckAuthRequest(incoming)
     expected_args = args.copy()
     expected_args['openid.mode'] = 'check_authentication'
     expected =Message.fromPostArgs(expected_args)
     self.failUnless(expected.isOpenID2())
     self.failUnlessEqual(expected, car)
     self.failUnlessEqual(expected_args, car.toPostArgs())
Example #2
0
    def test(self):
        # Create a request message with simple registration fields
        sreg_req = sreg.SRegRequest(required=['nickname', 'email'],
                                    optional=['fullname'])
        req_msg = Message()
        req_msg.updateArgs(sreg.ns_uri, sreg_req.getExtensionArgs())

        req = OpenIDRequest(req_msg)

        # -> send checkid_* request

        # Create an empty response message
        resp_msg = Message()
        resp = OpenIDResponse(req)
        resp.fields = resp_msg

        # Put the requested data fields in the response message
        sreg_resp = sreg.SRegResponse.extractResponse(sreg_req, data)
        resp.addExtension(sreg_resp)

        # <- send id_res response

        # Extract the fields that were sent
        sreg_data_resp = resp_msg.getArgs(sreg.ns_uri)
        sent_data = {'nickname': 'linusaur', 'email': '*****@*****.**', 'fullname': 'Leonhard Euler'}
        self.assertEqual(sreg_data_resp, sent_data)
 def runOneTest(self):
     csess = self.csess_fact()
     msg = Message.fromOpenIDArgs(csess.getRequest())
     ssess = self.ssess_fact.fromMessage(msg)
     check_secret = csess.extractSecret(
         Message.fromOpenIDArgs(ssess.answer(self.secret)))
     self.failUnlessEqual(self.secret, check_secret)
Example #4
0
 def test_setOpenIDNamespace_deprecated(self):
     message = Message()
     warning_msg = "Method 'setOpenIDNamespace' is deprecated. Pass namespace to Message constructor instead."
     with ShouldWarn(DeprecationWarning(warning_msg)):
         warnings.simplefilter('always')
         message.setOpenIDNamespace(OPENID2_NS, False)
     self.assertEqual(message.getOpenIDNamespace(), OPENID2_NS)
Example #5
0
 def test(self):
     for csess_fact, ssess_fact in self.session_factories:
         for secret in self.secrets:
             csess = csess_fact()
             msg = Message.fromOpenIDArgs(csess.getRequest())
             ssess = ssess_fact.fromMessage(msg)
             check_secret = csess.extractSecret(
                 Message.fromOpenIDArgs(ssess.answer(secret)))
             self.assertEqual(secret, check_secret)
Example #6
0
 def test_aintGotSignedList(self):
     m = Message(OPENID2_NS)
     m.updateArgs(OPENID2_NS, {'mode': 'id_res',
                               'identifier': '=example',
                               'sig': 'coyote',
                               })
     m.updateArgs(BARE_NS, {'xey': 'value'})
     assoc = association.Association.fromExpiresIn(3600, '{sha1}', b'very_secret', "HMAC-SHA1")
     self.assertRaises(ValueError, assoc.checkMessageSignature, m)
Example #7
0
    def test_isOpenID1(self):
        v1_namespaces = [
            # Yes, there are two of them.
            'http://openid.net/signon/1.1',
            'http://openid.net/signon/1.0',
        ]

        for ns in v1_namespaces:
            m = Message(ns)
            self.assertTrue(m.isOpenID1(), "%r not recognized as OpenID 1" % ns)
            self.assertEqual(m.getOpenIDNamespace(), ns)
            self.assertTrue(m.namespaces.isImplicit(ns))
    def make_response_ax(
            self, schema="http://axschema.org/",
            fullname="Some User", nickname="someuser", email="*****@*****.**",
            first=None, last=None, verified=False):
        endpoint = OpenIDServiceEndpoint()
        message = Message(OPENID2_NS)
        attributes = [
            ("nickname", schema + "namePerson/friendly", nickname),
            ("fullname", schema + "namePerson", fullname),
            ("email", schema + "contact/email", email),
            ("account_verified",
             "http://ns.login.ubuntu.com/2013/validation/account",
             "token_via_email" if verified else "no")
            ]
        if first:
            attributes.append(
                ("first", "http://axschema.org/namePerson/first", first))
        if last:
            attributes.append(
                ("last", "http://axschema.org/namePerson/last", last))

        message.setArg(AX_NS, "mode", "fetch_response")
        for (alias, uri, value) in attributes:
            message.setArg(AX_NS, "type.%s" % alias, uri)
            message.setArg(AX_NS, "value.%s" % alias, value)
        return SuccessResponse(
            endpoint, message, signed_fields=message.toPostArgs().keys())
Example #9
0
    def testEmptySessionType(self):
        msg = Message(self.endpoint.preferredNamespace())
        msg.setArg(OPENID_NS, 'error', 'Unsupported type')
        msg.setArg(OPENID_NS, 'error_code', 'unsupported-type')
        msg.setArg(OPENID_NS, 'assoc_type', 'new-assoc-type')
        msg.setArg(OPENID_NS, 'session_type', None)

        self.consumer.return_messages = [msg]
        self.assertEqual(self.consumer._negotiateAssociation(self.endpoint), None)

        self.failUnlessLogMatches('Server error when requesting an association')
Example #10
0
 def test_bad_args(self):
     query = {
         'openid.signed':'foo',
         'closid.foo':'something',
         }
     consumer = BadArgCheckingConsumer(self.store)
     consumer._checkAuth(Message.fromPostArgs(query), 'does://not.matter')
Example #11
0
 def test_112B(self):
     args = {
         'openid.assoc_handle': 'fa1f5ff0-cde4-11dc-a183-3714bfd55ca8',
         'openid.claimed_id': 'http://binkley.lan/user/test01',
         'openid.identity': 'http://test01.binkley.lan/',
         'openid.mode': 'id_res',
         'openid.ns': 'http://specs.openid.net/auth/2.0',
         'openid.ns.pape': 'http://specs.openid.net/extensions/pape/1.0',
         'openid.op_endpoint': 'http://binkley.lan/server',
         'openid.pape.auth_policies': 'none',
         'openid.pape.auth_time': '2008-01-28T20:42:36Z',
         'openid.pape.nist_auth_level': '0',
         'openid.response_nonce': '2008-01-28T21:07:04Z99Q=',
         'openid.return_to': 'http://binkley.lan:8001/process?janrain_nonce=2008-01-28T21%3A07%3A02Z0tMIKx',
         'openid.sig': 'YJlWH4U6SroB1HoPkmEKx9AyGGg=',
         'openid.signed': 'assoc_handle,identity,response_nonce,return_to,claimed_id,op_endpoint,pape.auth_time,'
                          'ns.pape,pape.nist_auth_level,pape.auth_policies'}
     m = Message.fromPostArgs(args)
     missing = []
     for k in args['openid.signed'].split(','):
         if not ("openid." + k) in m.toPostArgs().keys():
             missing.append(k)
     self.assertEqual(missing, [], missing)
     self.assertEqual(m.toPostArgs(), args)
     self.assertTrue(m.isOpenID2())
Example #12
0
    def test_mysterious_missing_namespace_bug(self):
        """A failing test for bug #112"""
        openid_args = {
            'assoc_handle': '{{HMAC-SHA256}{1211477242.29743}{v5cadg==}',
            'claimed_id': 'http://nerdbank.org/OPAffirmative/AffirmativeIdentityWithSregNoAssoc.aspx',
            'ns.sreg': 'http://openid.net/extensions/sreg/1.1',
            'response_nonce': '2008-05-22T17:27:22ZUoW5.\\NV',
            'signed': 'return_to,identity,claimed_id,op_endpoint,response_nonce,ns.sreg,sreg.email,sreg.nickname,'
                      'assoc_handle',
            'sig': 'e3eGZ10+TNRZitgq5kQlk5KmTKzFaCRI8OrRoXyoFa4=',
            'mode': 'check_authentication',
            'op_endpoint': 'http://nerdbank.org/OPAffirmative/ProviderNoAssoc.aspx',
            'sreg.nickname': 'Andy',
            'return_to': 'http://localhost.localdomain:8001/process?janrain_nonce=2008-05-22T17%3A27%3A21ZnxHULd',
            'invalidate_handle': '{{HMAC-SHA1}{1211477241.92242}{H0akXw==}',
            'identity': 'http://nerdbank.org/OPAffirmative/AffirmativeIdentityWithSregNoAssoc.aspx',
            'sreg.email': '*****@*****.**'}
        m = Message.fromOpenIDArgs(openid_args)

        self.assertEqual(m.namespaces.getAlias('http://openid.net/extensions/sreg/1.1'), 'sreg')
        missing = []
        for k in openid_args['signed'].split(','):
            if not ("openid." + k) in m.toPostArgs().keys():
                missing.append(k)
        self.assertEqual(missing, [])
        self.assertEqual(m.toArgs(), openid_args)
        self.assertTrue(m.isOpenID1())
Example #13
0
 def test_fromSuccessResponse_signed(self):
     message = Message.fromOpenIDArgs({
         'sreg.nickname':'The Mad Stork',
         })
     success_resp = DummySuccessResponse(message, {})
     sreg_resp = sreg.SRegResponse.fromSuccessResponse(success_resp)
     self.failIf(sreg_resp)
    def setUp(self):
        BaseAssocTest.setUp(self)
        self.session_type = "testing-session"

        # This must something that works for Association.fromExpiresIn
        self.assoc_type = "HMAC-SHA1"

        self.assoc_handle = "testing-assoc-handle"

        # These arguments should all be valid
        self.assoc_response = Message.fromOpenIDArgs(
            {
                "expires_in": "1000",
                "assoc_handle": self.assoc_handle,
                "assoc_type": self.assoc_type,
                "session_type": self.session_type,
                "ns": OPENID2_NS,
            }
        )

        self.assoc_session = DummyAssociationSession()

        # Make the session for the response's session type
        self.assoc_session.session_type = self.session_type
        self.assoc_session.allowed_assoc_types = [self.assoc_type]
Example #15
0
    def test_fromSuccessResponseWithData(self):
        name = 'ext0'
        value = 'snozzberry'
        uri = "http://willy.wonka.name/"
        args = {
            'mode': 'id_res',
            'ns': OPENID2_NS,
            'ns.ax': ax.AXMessage.ns_uri,
            'ax.update_url': 'http://example.com/realm/update_path',
            'ax.mode': 'fetch_response',
            'ax.type.' + name: uri,
            'ax.count.' + name: '1',
            'ax.value.%s.1' % name: value,
        }
        sf = ['openid.' + i for i in list(args.keys())]
        msg = Message.fromOpenIDArgs(args)

        class Endpoint:
            claimed_id = 'http://invalid.'

        resp = SuccessResponse(Endpoint(), msg, signed_fields=sf)
        ax_resp = ax.FetchResponse.fromSuccessResponse(resp)
        values = ax_resp.get(uri)
        # coming through the system they'll be bytes-ified...
        self.assertEqual([value], values)
    def setUp(self):
        BaseAssocTest.setUp(self)
        self.session_type = 'testing-session'

        # This must something that works for Association.fromExpiresIn
        self.assoc_type = 'HMAC-SHA1'

        self.assoc_handle = 'testing-assoc-handle'

        # These arguments should all be valid
        self.assoc_response = Message.fromOpenIDArgs({
            'expires_in':
            '1000',
            'assoc_handle':
            self.assoc_handle,
            'assoc_type':
            self.assoc_type,
            'session_type':
            self.session_type,
            'ns':
            OPENID2_NS,
        })

        self.assoc_session = DummyAssociationSession()

        # Make the session for the response's session type
        self.assoc_session.session_type = self.session_type
        self.assoc_session.allowed_assoc_types = [self.assoc_type]
Example #17
0
 def test_tamperedNonce(self):
     """Malformed nonce"""
     self.response = Message.fromOpenIDArgs(
                               {'ns':OPENID2_NS,
                                'response_nonce':'malformed'})
     self.failUnlessRaises(ProtocolError, self.consumer._idResCheckNonce,
                           self.response, self.endpoint)
Example #18
0
 def test_implicit_sreg_ns(self):
     openid_args = {'sreg.email': '*****@*****.**'}
     m = Message.fromOpenIDArgs(openid_args)
     self.assertEqual(m.namespaces.getAlias(sreg.ns_uri), 'sreg')
     self.assertEqual(m.getArg(sreg.ns_uri, 'email'), '*****@*****.**')
     self.assertEqual(m.toArgs(), openid_args)
     self.assertTrue(m.isOpenID1())
Example #19
0
 def test_idResMissingField(self):
     # XXX - this test is passing, but not necessarily by what it
     # is supposed to test for.  status in FAILURE, but it's because
     # *check_auth* failed, not because it's missing an arg, exactly.
     message = Message.fromPostArgs({'openid.mode': 'id_res'})
     self.failUnlessRaises(ProtocolError, self.consumer._doIdRes,
                           message, self.endpoint, None)
Example #20
0
    def test_newerAssoc(self):
        lifetime = 1000

        good_issued = time.time() - 10
        good_handle = 'handle'
        good_assoc = association.Association(
            good_handle, 'secret', good_issued, lifetime, 'HMAC-SHA1')
        self.store.storeAssociation(self.server_url, good_assoc)

        bad_issued = time.time() - 5
        bad_handle = 'handle2'
        bad_assoc = association.Association(
            bad_handle, 'secret', bad_issued, lifetime, 'HMAC-SHA1')
        self.store.storeAssociation(self.server_url, bad_assoc)

        query = {
            'return_to':self.return_to,
            'identity':self.server_id,
            'assoc_handle':good_handle,
            }

        message = Message.fromOpenIDArgs(query)
        message = good_assoc.signMessage(message)
        self.disableReturnToChecking()
        info = self.consumer._doIdRes(message, self.endpoint, None)
        self.failUnlessEqual(info.status, SUCCESS, info.message)
        self.failUnlessEqual(self.consumer_id, info.identity_url)
Example #21
0
    def test_idResURLMismatch(self):
        class VerifiedError(Exception): pass

        def discoverAndVerify(claimed_id, _to_match_endpoints):
            raise VerifiedError

        self.consumer._discoverAndVerify = discoverAndVerify
        self.disableReturnToChecking()

        message = Message.fromPostArgs(
            {'openid.mode': 'id_res',
             'openid.return_to': 'return_to (just anything)',
             'openid.identity': 'something wrong (not self.consumer_id)',
             'openid.assoc_handle': 'does not matter',
             'openid.sig': GOODSIG,
             'openid.signed': 'identity,return_to',
             })
        self.consumer.store = GoodAssocStore()

        self.failUnlessRaises(VerifiedError,
                              self.consumer.complete,
                              message, self.endpoint)

        self.failUnlessLogMatches('Error attempting to use stored',
                                  'Attempting discovery')
Example #22
0
    def test_openID1_sregNSfromArgs(self):
        args = {"sreg.optional": "nickname", "sreg.required": "dob"}

        m = Message.fromOpenIDArgs(args)

        self.assertTrue(m.getArg(sreg.ns_uri_1_1, "optional") == "nickname")
        self.assertTrue(m.getArg(sreg.ns_uri_1_1, "required") == "dob")
Example #23
0
    def setUp(self):
        self.store = GoodAssocStore()
        self.consumer = GenericConsumer(self.store)
        self.server_url = "http://idp.unittest/"
        CatchLogs.setUp(self)

        claimed_id = 'bogus.claimed'

        self.message = Message.fromOpenIDArgs(
            {'mode': 'id_res',
             'return_to': 'return_to (just anything)',
             'identity': claimed_id,
             'assoc_handle': 'does not matter',
             'sig': GOODSIG,
             'response_nonce': mkNonce(),
             'signed': 'identity,return_to,response_nonce,assoc_handle,claimed_id,op_endpoint',
             'claimed_id': claimed_id,
             'op_endpoint': self.server_url,
             'ns':OPENID2_NS,
             })

        self.endpoint = OpenIDServiceEndpoint()
        self.endpoint.server_url = self.server_url
        self.endpoint.claimed_id = claimed_id
        self.consumer._checkReturnTo = lambda unused1, unused2 : True
Example #24
0
    def test_noSetupNeededOpenID1(self):
        """When the user_setup_url is missing on an OpenID 1 message,
        we assume that it's not a cancel response to checkid_immediate"""
        message = Message.fromOpenIDArgs({'mode': 'id_res'})
        self.failUnless(message.isOpenID1())

        # No SetupNeededError raised
        self.consumer._checkSetupNeeded(message)
Example #25
0
 def test_openid1Success(self):
     """use consumer-generated nonce"""
     nonce_value = mkNonce()
     self.return_to = 'http://rt.unittest/?nonce=%s' % (nonce_value,)
     self.response = Message.fromOpenIDArgs({'return_to': self.return_to})
     self.response.setArg(BARE_NS, 'nonce', nonce_value)
     self.consumer._idResCheckNonce(self.response, self.endpoint)
     self.failUnlessLogEmpty()
Example #26
0
 def test_consumerNonceOpenID2(self):
     """OpenID 2 does not use consumer-generated nonce"""
     self.return_to = 'http://rt.unittest/?nonce=%s' % (mkNonce(),)
     self.response = Message.fromOpenIDArgs(
         {'return_to': self.return_to, 'ns':OPENID2_NS})
     self.failUnlessRaises(ProtocolError, self.consumer._idResCheckNonce,
                           self.response, self.endpoint)
     self.failUnlessLogEmpty()
Example #27
0
 def test_fromSuccessResponse_unsigned(self):
     message = Message.fromOpenIDArgs({
         'sreg.nickname': 'The Mad Stork',
     })
     success_resp = DummySuccessResponse(message, {})
     sreg_resp = sreg.SRegResponse.fromSuccessResponse(success_resp,
                                                       signed_only=False)
     self.assertEqual(list(sreg_resp.items()), [('nickname', 'The Mad Stork')])
Example #28
0
    def test_completeGoodReturnTo(self):
        """Test GenericConsumer.complete()'s handling of good
        return_to values.
        """
        return_to = "http://some.url/path"

        good_return_tos = [
            (return_to, {}),
            (return_to + "?another=arg", {(BARE_NS, 'another'): 'arg'}),
            (return_to + "?another=arg#fragment", {(BARE_NS, 'another'): 'arg'}),
            ("HTTP"+return_to[4:], {}),
            (return_to.replace('url','URL'), {}),
            ("http://some.url:80/path", {}),
            ("http://some.url/p%61th", {}),
            ("http://some.url/./path", {}),
            ]

        endpoint = None

        for good, extra in good_return_tos:
            m = Message(OPENID1_NS)
            m.setArg(OPENID_NS, 'mode', 'cancel')

            for ns, key in extra:
                m.setArg(ns, key, extra[(ns, key)])

            m.setArg(OPENID_NS, 'return_to', good)
            result = self.consumer.complete(m, endpoint, return_to)
            self.failUnless(isinstance(result, CancelResponse), \
                            "Expected CancelResponse, got %r for %s" % (result, good,))
Example #29
0
    def test_completeBadReturnTo(self):
        """Test GenericConsumer.complete()'s handling of bad return_to
        values.
        """
        return_to = "http://some.url/path?foo=bar"

        # Scheme, authority, and path differences are checked by
        # GenericConsumer._checkReturnTo.  Query args checked by
        # GenericConsumer._verifyReturnToArgs.
        bad_return_tos = [
            # Scheme only
            "https://some.url/path?foo=bar",
            # Authority only
            "http://some.url.invalid/path?foo=bar",
            # Path only
            "http://some.url/path_extra?foo=bar",
            # Query args differ
            "http://some.url/path?foo=bar2",
            "http://some.url/path?foo2=bar",
            ]

        m = Message(OPENID1_NS)
        m.setArg(OPENID_NS, 'mode', 'cancel')
        m.setArg(BARE_NS, 'foo', 'bar')
        endpoint = None

        for bad in bad_return_tos:
            m.setArg(OPENID_NS, 'return_to', bad)
            self.failIf(self.consumer._checkReturnTo(m, return_to))
def mkAssocResponse(*keys):
    """Build an association response message that contains the
    specified subset of keys. The values come from
    `association_response_values`.

    This is useful for testing for missing keys and other times that
    we don't care what the values are."""
    args = dict([(key, association_response_values[key]) for key in keys])
    return Message.fromOpenIDArgs(args)
Example #31
0
 def test_toFormMarkup_bug_with_utf8_values(self):
     postargs = {
         'openid.ns': OPENID2_NS,
         'openid.mode': 'checkid_setup',
         'openid.identity': 'http://bogus.example.invalid:port/',
         'openid.assoc_handle': 'FLUB',
         'openid.return_to': 'Neverland',
         'ünicöde_key': 'ünicöde_välüe',
     }
     m = Message.fromPostArgs(postargs)
     html = m.toFormMarkup(self.action_url, self.form_tag_attrs,
                           self.submit_text)
     self.assertIn('ünicöde_key', html)
     self.assertIn('ünicöde_välüe', html)
     self.assertNotIn('&#195;&#188;nic&#195;&#182;de_key', html,
                      'UTF-8 bytes should not convert to XML character references')
     self.assertNotIn('&#195;&#188;nic&#195;&#182;de_v&#195;&#164;l&#195;&#188;e', html,
                      'UTF-8 bytes should not convert to XML character references')
Example #32
0
    def test_fromSuccessResponseWithoutData(self):
        """return something for SuccessResponse with AX paramaters,
        even if it is the empty set."""
        args = {
            'mode': 'id_res',
            'ns': OPENID2_NS,
            'ns.ax': ax.AXMessage.ns_uri,
            'ax.mode': 'fetch_response',
        }
        sf = ['openid.' + i for i in args.keys()]
        msg = Message.fromOpenIDArgs(args)

        class Endpoint:
            claimed_id = 'http://invalid.'

        oreq = SuccessResponse(Endpoint(), msg, signed_fields=sf)
        r = ax.FetchResponse.fromSuccessResponse(oreq)
        self.assertIsNotNone(r)
    def testUnsupportedWithRetry(self):
        """
        Test the case where an unsupported-type response triggers a
        retry to get an association with the new preferred type.
        """
        msg = Message(self.endpoint.preferredNamespace())
        msg.setArg(OPENID_NS, 'error', 'Unsupported type')
        msg.setArg(OPENID_NS, 'error_code', 'unsupported-type')
        msg.setArg(OPENID_NS, 'assoc_type', 'HMAC-SHA1')
        msg.setArg(OPENID_NS, 'session_type', 'DH-SHA1')

        assoc = association.Association('handle', 'secret', 'issued', 10000,
                                        'HMAC-SHA1')

        self.consumer.return_messages = [msg, assoc]
        with LogCapture() as logbook:
            self.assertEqual(
                self.consumer._negotiateAssociation(self.endpoint), assoc)
        logbook.check(('openid.consumer.consumer', 'ERROR',
                       StringComparison('Unsupported association type .*')))
Example #34
0
    def post(self):
        if not self.CheckUser():
            self.ShowFrontPage()
            return

        args = self.ArgsToDict()

        try:
            global oidserver
            from openid.message import Message
            message = Message.fromPostArgs(args)
            oidrequest = OpenIDServer.CheckIDRequest.fromMessage(
                message, oidserver.op_endpoint)
        except:
            trace = ''.join(traceback.format_exception(*sys.exc_info()))
            self.ReportError('Error decoding login request:\n%s' % trace)
            return

        if args.has_key('yes'):
            logging.debug('Confirming identity to %s' % oidrequest.trust_root)
            if args.get('remember', '') == 'yes':
                logging.info('Setting cookie to remember login for two weeks.')

                expires = datetime.datetime.now() + datetime.timedelta(weeks=2)
                expires_rfc822 = expires.strftime(
                    '%a, %d %b %Y %H:%M:%S +0000')
                self.response.headers.add_header(
                    'Set-Cookie', 'openid_remembered_%s=yes; expires=%s' %
                    (digest(oidrequest.trust_root), expires_rfc822))

            self.store_login(oidrequest, 'confirmed')
            answer = oidrequest.answer(True,
                                       identity=get_identity_url(self.request))
            logging.info('answer:%s', answer)
            self.Respond(answer)

        elif args.has_key('no'):
            logging.debug('Login denied, sending cancel to %s' %
                          oidrequest.trust_root)
            self.store_login(oidrequest, 'declined')
            return self.Respond(oidrequest.answer(False))

        else:
            self.ReportError('Bad login request.')
    def test_extract_user_details_ax_split_name(self):
        endpoint = OpenIDServiceEndpoint()
        message = Message(OPENID2_NS)
        attributes = [
            ("nickname", "http://axschema.org/namePerson/friendly", "someuser"),
            # Include this key too to show that the split data takes
            # precedence.
            ("fullname", "http://axschema.org/namePerson", "Bad Data"),
            ("first", "http://axschema.org/namePerson/first", "Some"),
            ("last", "http://axschema.org/namePerson/last", "User"),
            ("email", "http://axschema.org/contact/email", "*****@*****.**"),
            ]
        message.setArg(AX_NS, "mode", "fetch_response")
        for (alias, uri, value) in attributes:
            message.setArg(AX_NS, "type.%s" % alias, uri)
            message.setArg(AX_NS, "value.%s" % alias, value)
        response = SuccessResponse(
            endpoint, message, signed_fields=message.toPostArgs().keys())

        data = self.backend._extract_user_details(response)
        self.assertEqual(data, {"nickname": "someuser",
                                "first_name": "Some",
                                "last_name": "User",
                                "email": "*****@*****.**"})
Example #36
0
    def test_fromSuccessResponseNoSignedArgs(self):
        policy_uris = [pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT]
        openid_req_msg = Message.fromOpenIDArgs({
            'mode': 'id_res',
            'ns': OPENID2_NS,
            'ns.pape': pape.ns_uri,
            'pape.auth_policies': ' '.join(policy_uris),
            'pape.auth_time': '1970-01-01T00:00:00Z'
        })

        signed_stuff = {}

        class NoSigningDummyResponse(DummySuccessResponse):
            def getSignedNS(self, ns_uri):
                return None

        oid_req = NoSigningDummyResponse(openid_req_msg, signed_stuff)
        resp = pape.Response.fromSuccessResponse(oid_req)
        self.assertIsNone(resp)
 def test_fromOpenIDRequest(self):
     policy_uris = [pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT]
     openid_req_msg = Message.fromOpenIDArgs({
         'mode':
         'checkid_setup',
         'ns':
         OPENID2_NS,
         'ns.pape':
         pape.ns_uri,
         'pape.preferred_auth_policies':
         ' '.join(policy_uris),
         'pape.max_auth_age':
         '5476'
     })
     oid_req = server.OpenIDRequest()
     oid_req.message = openid_req_msg
     req = pape.Request.fromOpenIDRequest(oid_req)
     self.assertEqual(req.preferred_auth_policies, policy_uris)
     self.assertEqual(req.max_auth_age, 5476)
Example #38
0
    def test_unreachableRealm(self):
        self.request = dummyRequest()

        id_url = util.getViewURL(self.request, views.idPage)

        # Set up the OpenID request we're responding to.
        op_endpoint = 'http://127.0.0.1:8080/endpoint'
        message = Message.fromPostArgs({
            'openid.mode': 'checkid_setup',
            'openid.identity': id_url,
            'openid.return_to': 'http://unreachable.invalid/%s' % (self.id(),),
            'openid.sreg.required': 'postcode',
            })
        self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint)

        views.setRequest(self.request, self.openid_request)

        response = views.showDecidePage(self.request, self.openid_request)
        self.assertContains(response, 'trust_root_valid is Unreachable')
Example #39
0
    def setUp(self):
        self.request = dummyRequest()

        id_url = urljoin('http://example.cz/', reverse('server:local_id'))

        # Set up the OpenID request we're responding to.
        op_endpoint = 'http://127.0.0.1:8080/endpoint'
        message = Message.fromPostArgs({
            'openid.mode':
            'checkid_setup',
            'openid.identity':
            id_url,
            'openid.return_to':
            'http://127.0.0.1/%s' % (self.id(), ),
            'openid.sreg.required':
            'postcode',
        })
        self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint)

        views.setRequest(self.request, self.openid_request)
Example #40
0
    def setUp(self):
        self.request = dummyRequest()

        id_url = util.get_view_url(self.request, views.idPage)

        # Set up the OpenID request we're responding to.
        op_endpoint = 'http://127.0.0.1:8080/endpoint'
        message = Message.fromPostArgs({
            'openid.mode':
            'checkid_setup',
            'openid.identity':
            id_url,
            'openid.return_to':
            'http://127.0.0.1/%s' % (self.id(), ),
            'openid.sreg.required':
            'postcode',
        })
        self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint)

        views.set_request(self.request, self.openid_request)
  def post(self):
  
    # We _must_ be authenticated.
    userpass = self.getBasicAuth()
    self.user = userpass[0] if userpass else None # just trust it 
    if not self.user:
      self.sendAuthenticationChallenge()
      return
  
    # Um.  How do we safely determine which endpoint the user has granted access to?
    # Do we need to sign the trust_root/identity tuple somehow?

    # For now we just pull it out of the request.  This is not right.
    go = self.request.arguments['go'][0]
    root = self.request.arguments['root'][0]
    id = self.request.arguments['id'][0]
    return_to = self.request.arguments['return_to'][0] if 'return_to' in self.request.arguments else None
    assoc_handle = self.request.arguments['assoc_handle'][0] if 'assoc_handle' in self.request.arguments else None
    op_endpoint = self.request.arguments['op_endpoint'][0] if 'op_endpoint' in self.request.arguments else None

    request = server.CheckIDRequest(id, return_to, root, assoc_handle=assoc_handle, op_endpoint=op_endpoint)
    request.message = Message(OPENID2_NS) # XXX version?

    remember = self.request.arguments['remember'][0] == 'yes' if 'remember' in self.request.arguments else False

    if 'Yes, allow this site to know who I am' == go:
      if remember:
        # Persist remember on the user
        # self.server.approved[(identity, trust_root)] = 'always'
        pass
      response = self.approved(request, id)

    elif 'no' in query:
      response = request.answer(False)

    else:
      logging.error('strange allow post.  %r' % (query,))
      raise tornado.web.HTTPError("400", "Strange Allow Post")

    self.displayResponse(response)
Example #42
0
    def test_openid_namespace_invalid(self):
        invalid_things = [
            # Empty string is not okay here.
            '',
            # Good guess!  But wrong.
            'http://openid.net/signon/2.0',
            # What?
            'http://specs%\\\r2Eopenid.net/auth/2.0',
            # Too much escapings!
            'http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0',
            # This is a Type URI, not a openid.ns value.
            'http://specs.openid.net/auth/2.0/signon',
        ]
        warning_msg = "Method 'setOpenIDNamespace' is deprecated. Pass namespace to Message constructor instead."

        for x in invalid_things:
            self.assertRaises(InvalidOpenIDNamespace, Message, x, False)
            # Test also deprecated setOpenIDNamespace
            message = Message()
            with ShouldWarn(DeprecationWarning(warning_msg)):
                warnings.simplefilter('always')
                self.assertRaises(InvalidOpenIDNamespace, message.setOpenIDNamespace, x, False)
Example #43
0
 def test_toFormMarkup_bug_with_utf8_values(self):
     postargs = {
         'openid.ns': OPENID2_NS,
         'openid.mode': 'checkid_setup',
         'openid.identity': 'http://bogus.example.invalid:port/',
         'openid.assoc_handle': 'FLUB',
         'openid.return_to': 'Neverland',
         'ünicöde_key': 'ünicöde_välüe',
     }
     m = Message.fromPostArgs(postargs)
     # Calling m.toFormMarkup with lxml used for ElementTree will throw
     # a ValueError.
     html = m.toFormMarkup(self.action_url, self.form_tag_attrs,
                           self.submit_text)
     # Using the (c)ElementTree from stdlib will result in the UTF-8
     # encoded strings to be converted to XML character references,
     # "ünicöde_key" becomes "&#195;&#188;nic&#195;&#182;de_key" and
     # "ünicöde_välüe" becomes "&#195;&#188;nic&#195;&#182;de_v&#195;&#164;l&#195;&#188;e"
     self.assertNotIn('&#195;&#188;nic&#195;&#182;de_key', html,
                      'UTF-8 bytes should not convert to XML character references')
     self.assertNotIn('&#195;&#188;nic&#195;&#182;de_v&#195;&#164;l&#195;&#188;e', html,
                      'UTF-8 bytes should not convert to XML character references')
 def test_fromSuccessResponse(self):
     policy_uris = [pape.AUTH_MULTI_FACTOR, pape.AUTH_PHISHING_RESISTANT]
     openid_req_msg = Message.fromOpenIDArgs({
         'mode':
         'id_res',
         'ns':
         OPENID2_NS,
         'ns.pape':
         pape.ns_uri,
         'pape.auth_policies':
         ' '.join(policy_uris),
         'pape.auth_time':
         '1970-01-01T00:00:00Z'
     })
     signed_stuff = {
         'auth_policies': ' '.join(policy_uris),
         'auth_time': '1970-01-01T00:00:00Z'
     }
     oid_req = DummySuccessResponse(openid_req_msg, signed_stuff)
     req = pape.Response.fromSuccessResponse(oid_req)
     self.assertEqual(req.auth_policies, policy_uris)
     self.assertEqual(req.auth_time, '1970-01-01T00:00:00Z')
    def setUp(self):
        BaseAssocTest.setUp(self)
        self.session_type = 'testing-session'

        # This must something that works for Association.fromExpiresIn
        self.assoc_type = 'HMAC-SHA1'

        self.assoc_handle = 'testing-assoc-handle'

        # These arguments should all be valid
        self.assoc_response = Message.fromOpenIDArgs({
            'expires_in': '1000',
            'assoc_handle': self.assoc_handle,
            'assoc_type': self.assoc_type,
            'session_type': self.session_type,
            'ns': OPENID2_NS,
        })

        self.assoc_session = DummyAssociationSession()

        # Make the session for the response's session type
        self.assoc_session.session_type = self.session_type
        self.assoc_session.allowed_assoc_types = [self.assoc_type]
Example #46
0
    def test_unreachableRealm(self):
        self.request = dummyRequest()

        id_url = urljoin('http://example.cz/', reverse('server:local_id'))

        # Set up the OpenID request we're responding to.
        op_endpoint = 'http://127.0.0.1:8080/endpoint'
        message = Message.fromPostArgs({
            'openid.mode':
            'checkid_setup',
            'openid.identity':
            id_url,
            'openid.return_to':
            'http://unreachable.invalid/%s' % (self.id(), ),
            'openid.sreg.required':
            'postcode',
        })
        self.openid_request = CheckIDRequest.fromMessage(message, op_endpoint)

        views.setRequest(self.request, self.openid_request)

        response = views.showDecidePage(self.request, self.openid_request)
        self.assertIn('trust_root_valid is Unreachable', response.content)
Example #47
0
    def test_fromSuccessResponseWithData(self):
        name = 'ext0'
        value = 'snozzberry'
        uri = "http://willy.wonka.name/"
        args = {
            'mode': 'id_res',
            'ns': OPENID2_NS,
            'ns.ax': ax.AXMessage.ns_uri,
            'ax.update_url': 'http://example.com/realm/update_path',
            'ax.mode': 'fetch_response',
            'ax.type.' + name: uri,
            'ax.count.' + name: '1',
            'ax.value.%s.1' % name: value,
        }
        sf = ['openid.' + i for i in args.keys()]
        msg = Message.fromOpenIDArgs(args)

        class Endpoint:
            claimed_id = 'http://invalid.'

        resp = SuccessResponse(Endpoint(), msg, signed_fields=sf)
        ax_resp = ax.FetchResponse.fromSuccessResponse(resp)
        values = ax_resp.get(uri)
        self.assertEqual(values, [value])
Example #48
0
 def test_openid1_namespace_implicit(self):
     m = Message(THE_OTHER_OPENID1_NS, True)
     self.assertTrue(m.namespaces.isImplicit(THE_OTHER_OPENID1_NS))
Example #49
0
 def test_fromOpenIDRequest_no_pape(self):
     message = Message()
     openid_req = server.OpenIDRequest()
     openid_req.message = message
     pape_req = pape.Request.fromOpenIDRequest(openid_req)
     assert(pape_req is None)
Example #50
0
 def test_openid1_namespace_explicit(self):
     m = Message(THE_OTHER_OPENID1_NS, False)
     self.assertFalse(m.namespaces.isImplicit(THE_OTHER_OPENID1_NS))
Example #51
0
 def testBadResponse(self):
     self.consumer.return_messages = [Message(self.endpoint.preferredNamespace())]
     with LogCapture() as logbook:
         self.assertIsNone(self.consumer._negotiateAssociation(self.endpoint))
     logbook.check(
         ('openid.consumer.consumer', 'ERROR', StringComparison('Server error when requesting an association .*')))
Example #52
0
 def test_isOpenID2(self):
     ns = 'http://specs.openid.net/auth/2.0'
     m = Message(ns)
     self.assertTrue(m.isOpenID2())
     self.assertFalse(m.namespaces.isImplicit(NULL_NAMESPACE))
     self.assertEqual(m.getOpenIDNamespace(), ns)
Example #53
0
 def setUp(self):
     self.msg = Message.fromPostArgs({'openid.mode': 'error', 'openid.error': 'unit test', 'openid.ns': OPENID2_NS})
     self.msg.setArg(BARE_NS, "xey", "value")
Example #54
0
 def test_toPostArgs_bug_with_utf8_encoded_values(self):
     msg = Message.fromPostArgs({'openid.mode': 'error', 'openid.error': 'unit test', 'openid.ns': OPENID2_NS})
     msg.setArg(BARE_NS, 'ünicöde_key', 'ünicöde_välüe')
     post_args = {'openid.mode': 'error', 'openid.error': 'unit test', 'openid.ns': OPENID2_NS,
                  'ünicöde_key': 'ünicöde_välüe'}
     self.assertEqual(msg.toPostArgs(), post_args)
 def __init__(self):
     self.message = Message()
Example #56
0
    def test_explicitOpenID11NSSerialzation(self):
        m = Message(THE_OTHER_OPENID1_NS, False)

        post_args = m.toPostArgs()
        self.assertEqual(post_args, {'openid.ns': THE_OTHER_OPENID1_NS})
Example #57
0
 def testBadResponse(self):
     self.consumer.return_messages = [Message(self.endpoint.preferredNamespace())]
     self.assertEqual(self.consumer._negotiateAssociation(self.endpoint), None)
     self.failUnlessLogMatches('Server error when requesting an association')
Example #58
0
 def __init__(self, status, identity_url):
     self.status = status
     self.identity_url = identity_url
     self.message = Message()
Example #59
0
 def test_getAliasedArgSuccess(self):
     msg = Message.fromPostArgs({'openid.ns.test': 'urn://foo', 'openid.test.flub': 'bogus'})
     actual_uri = msg.getAliasedArg('ns.test', no_default)
     self.assertEqual("urn://foo", actual_uri)
Example #60
0
 def test_toFormMarkup(self):
     m = Message.fromPostArgs(self.postargs)
     html = m.toFormMarkup(self.action_url, self.form_tag_attrs,
                           self.submit_text)
     self._checkForm(html, m, self.action_url,
                     self.form_tag_attrs, self.submit_text)