incubator-heraldry-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ket...@apache.org
Subject svn commit: r493362 - in /incubator/heraldry/libraries/python/openid/trunk/openid: consumer/consumer.py test/test_association.py test/test_consumer.py
Date Sat, 06 Jan 2007 05:25:09 GMT
Author: keturn
Date: Fri Jan  5 21:25:08 2007
New Revision: 493362

URL: http://svn.apache.org/viewvc?view=rev&rev=493362
Log:
[python-to-heraldry @ Make _makeKVPost return a Message object]
Also raises HTTPFetchingError instead of returning None. It might be
the wrong type of exception to raise, but it works for now.

This had a relatively wide-reaching impact, but I think it will
ultimately be an improvement. _makeKVPost still doesn't *take* a
Message object.

Original author: Josh Hoyt <josh@janrain.com>
Date: 2006-12-21 21:03:32+00:00

Modified:
    incubator/heraldry/libraries/python/openid/trunk/openid/consumer/consumer.py
    incubator/heraldry/libraries/python/openid/trunk/openid/test/test_association.py
    incubator/heraldry/libraries/python/openid/trunk/openid/test/test_consumer.py

Modified: incubator/heraldry/libraries/python/openid/trunk/openid/consumer/consumer.py
URL: http://svn.apache.org/viewvc/incubator/heraldry/libraries/python/openid/trunk/openid/consumer/consumer.py?view=diff&rev=493362&r1=493361&r2=493362
==============================================================================
--- incubator/heraldry/libraries/python/openid/trunk/openid/consumer/consumer.py (original)
+++ incubator/heraldry/libraries/python/openid/trunk/openid/consumer/consumer.py Fri Jan 
5 21:25:08 2007
@@ -192,7 +192,7 @@
 from openid.consumer.discover import discoverXRI
 from openid.consumer.discover import DiscoveryFailure
 from openid.message import Message, OPENID_NS, OPENID2_NS, OPENID1_NS, \
-     IDENTIFIER_SELECT
+     IDENTIFIER_SELECT, no_default
 from openid import cryptutil
 from openid import kvform
 from openid import oidutil
@@ -387,9 +387,12 @@
         return args
 
     def extractSecret(self, response):
-        spub = cryptutil.base64ToLong(response['dh_server_public'])
-        enc_mac_key = oidutil.fromBase64(response['enc_mac_key'])
-        return self.dh.xorSecret(spub, enc_mac_key, self.hash_func)
+        dh_server_public64 = response.getArg(
+            OPENID_NS, 'dh_server_public', no_default)
+        enc_mac_key64 = response.getArg(OPENID_NS, 'enc_mac_key', no_default)
+        dh_server_public = cryptutil.base64ToLong(dh_server_public64)
+        enc_mac_key = oidutil.fromBase64(enc_mac_key64)
+        return self.dh.xorSecret(dh_server_public, enc_mac_key, self.hash_func)
 
 class DiffieHellmanSHA256ConsumerSession(DiffieHellmanSHA1ConsumerSession):
     session_type = 'DH-SHA256'
@@ -404,7 +407,7 @@
         return {}
 
     def extractSecret(self, response):
-        return oidutil.fromBase64(response['mac_key'])
+        return oidutil.fromBase64(response.getArg(OPENID_NS, 'mac_key'))
 
 class UnsupportedAssocType(Exception):
     """Exception raised when the server tells us that the session type
@@ -498,27 +501,36 @@
         return response
 
     def _makeKVPost(self, args, server_url):
+        """Make a Direct Request to an OpenID Provider and return the
+        result as a Message object.
+
+        @raises fetchers.HTTPFetchingError
+        @rtype: openid.message.Message
+        """
+        # XXX: TESTME
+        # XXX: make me take a Message
         mode = args['openid.mode']
         body = urllib.urlencode(args)
 
         resp = fetchers.fetch(server_url, body=body)
         if resp is None:
-            fmt = 'openid.mode=%s: failed to fetch URL: %s'
-            oidutil.log(fmt % (mode, server_url))
-            return None
+            fmt = 'failed to fetch URL: %s'
+            raise fetchers.HTTPFetchingError(fmt % (mode, server_url))
 
         response = kvform.kvToDict(resp.body)
         if resp.status == 400:
-            server_error = response.get('error', '<no message from server>')
-            fmt = 'openid.mode=%s: error returned from server %s: %s'
-            oidutil.log(fmt % (mode, server_url, server_error))
-            return None
+            server_error = response.getArg(
+                OPENID_NS, 'error', '<no message from server>')
+            fmt = 'error returned from server %s: %s'
+            error_message = fmt % (mode, server_url, server_error)
+            raise fetchers.HTTPFetchingError(error_message)
+
         elif resp.status != 200:
-            fmt = 'openid.mode=%s: bad status code from server %s: %s'
-            oidutil.log(fmt % (mode, server_url, resp.status))
-            return None
+            fmt = 'bad status code from server %s: %s'
+            error_message = fmt % (server_url, resp.status)
+            raise fetchers.HTTPFetchingError(error_message)
 
-        return response
+        return Message.fromOpenIDArgs(response)
 
     def _doIdRes(self, message, endpoint):
         """Handle id_res responses.
@@ -704,10 +716,13 @@
         request = self._createCheckAuthRequest(message)
         if request is None:
             return False
-        response = self._makeKVPost(request, server_url)
-        if response is None:
+        try:
+            response = self._makeKVPost(request, server_url)
+        except fetchers.HTTPFetchingError, e:
+            oidutil.log('check_authentication failed: %s' % (e[0],))
             return False
-        return self._processCheckAuthResponse(response, server_url)
+        else:
+            return self._processCheckAuthResponse(response, server_url)
 
     def _createCheckAuthRequest(self, message):
         # Arguments that are always passed to the server and not
@@ -736,9 +751,9 @@
         return check_args
 
     def _processCheckAuthResponse(self, response, server_url):
-        is_valid = response.get('is_valid', 'false')
+        is_valid = response.getArg(OPENID_NS, 'is_valid', 'false')
 
-        invalidate_handle = response.get('invalidate_handle')
+        invalidate_handle = response.getArg(OPENID_NS, 'invalidate_handle')
         if invalidate_handle is not None:
             self.store.removeAssociation(server_url, invalidate_handle)
 
@@ -766,16 +781,10 @@
                     response = self._makeKVPost(args, endpoint.server_url)
                 except fetchers.HTTPFetchingError, why:
                     oidutil.log('openid.associate request failed: %s' %
-                                (str(why),))
+                                (why[0],))
                     assoc = None
                     break
                 else:
-                    if response is None:
-                        oidutil.log('openid.associate request failed: ' +
-                                    'no reason given.')
-                        assoc = None
-                        break
-
                     try:
                         assoc = self._parseAssociation(
                             response, assoc_session, endpoint.server_url)
@@ -830,20 +839,23 @@
         return assoc_session, args
 
     def _parseAssociation(self, results, assoc_session, server_url):
-        error_code = results.get('error_code')
+        error_code = results.getArg(OPENID2_NS, 'error_code')
         if error_code is not None:
             return self._associateError(results)
 
         try:
-            assoc_type = results['assoc_type']
-            assoc_handle = results['assoc_handle']
-            expires_in_str = results['expires_in']
+            assoc_type = results.getArg(
+                OPENID_NS, 'assoc_type', no_default)
+            assoc_handle = results.getArg(
+                OPENID_NS, 'assoc_handle', no_default)
+            expires_in_str = results.getArg(
+                OPENID_NS, 'expires_in', no_default)
         except KeyError, e:
             fmt = 'Getting association: missing key in response from %s: %s'
             oidutil.log(fmt % (server_url, e[0]))
             return None
 
-        session_type = results.get('session_type')
+        session_type = results.getArg(OPENID_NS, 'session_type')
         if session_type != assoc_session.session_type:
             if session_type is None or session_type == 'no-encryption':
                 oidutil.log('Falling back to no-encryption association '

Modified: incubator/heraldry/libraries/python/openid/trunk/openid/test/test_association.py
URL: http://svn.apache.org/viewvc/incubator/heraldry/libraries/python/openid/trunk/openid/test/test_association.py?view=diff&rev=493362&r1=493361&r2=493362
==============================================================================
--- incubator/heraldry/libraries/python/openid/trunk/openid/test/test_association.py (original)
+++ incubator/heraldry/libraries/python/openid/trunk/openid/test/test_association.py Fri Jan
 5 21:25:08 2007
@@ -77,7 +77,7 @@
         csess = self.csess_fact()
         msg = Message.fromPostArgs(csess.getRequest())
         ssess = self.ssess_fact.fromMessage(msg)
-        check_secret = csess.extractSecret(ssess.answer(self.secret))
+        check_secret = csess.extractSecret(Message.fromOpenIDArgs(ssess.answer(self.secret)))
         self.failUnlessEqual(self.secret, check_secret)
 
 

Modified: incubator/heraldry/libraries/python/openid/trunk/openid/test/test_consumer.py
URL: http://svn.apache.org/viewvc/incubator/heraldry/libraries/python/openid/trunk/openid/test/test_consumer.py?view=diff&rev=493362&r1=493361&r2=493362
==============================================================================
--- incubator/heraldry/libraries/python/openid/trunk/openid/test/test_consumer.py (original)
+++ incubator/heraldry/libraries/python/openid/trunk/openid/test/test_consumer.py Fri Jan
 5 21:25:08 2007
@@ -510,34 +510,29 @@
 
     def test_goodResponse(self):
         """successful response to check_authentication"""
-        response = {
-            'is_valid':'true',
-            }
+        response = Message.fromOpenIDArgs({'is_valid':'true',})
         r = self.consumer._processCheckAuthResponse(response, self.server_url)
         self.failUnless(r)
 
     def test_missingAnswer(self):
         """check_authentication returns false when the server sends no answer"""
-        response = {
-            }
+        response = Message.fromOpenIDArgs({})
         r = self.consumer._processCheckAuthResponse(response, self.server_url)
         self.failIf(r)
 
     def test_badResponse(self):
         """check_authentication returns false when is_valid is false"""
-        response = {
-            'is_valid':'false',
-            }
+        response = Message.fromOpenIDArgs({'is_valid':'false',})
         r = self.consumer._processCheckAuthResponse(response, self.server_url)
         self.failIf(r)
 
     def test_badResponseInvalidate(self):
         """Make sure that the handle is invalidated when is_valid is false"""
         self._createAssoc()
-        response = {
+        response = Message.fromOpenIDArgs({
             'is_valid':'false',
             'invalidate_handle':'handle',
-            }
+            })
         r = self.consumer._processCheckAuthResponse(response, self.server_url)
         self.failIf(r)
         self.failUnless(
@@ -545,20 +540,20 @@
 
     def test_invalidateMissing(self):
         """invalidate_handle with a handle that is not present"""
-        response = {
+        response = Message.fromOpenIDArgs({
             'is_valid':'true',
             'invalidate_handle':'missing',
-            }
+            })
         r = self.consumer._processCheckAuthResponse(response, self.server_url)
         self.failUnless(r)
 
     def test_invalidatePresent(self):
         """invalidate_handle with a handle that exists"""
         self._createAssoc()
-        response = {
+        response = Message.fromOpenIDArgs({
             'is_valid':'true',
             'invalidate_handle':'handle',
-            }
+            })
         r = self.consumer._processCheckAuthResponse(response, self.server_url)
         self.failUnless(r)
         self.failUnless(
@@ -825,8 +820,11 @@
         return self.response
 
 class ExceptionRaisingMockFetcher(object):
+    class MyException(Exception):
+        pass
+
     def fetch(self, url, body=None, headers=None):
-        raise HTTPFetchingError('mock fetcher exception')
+        raise self.MyException('mock fetcher exception')
 
 class BadArgCheckingConsumer(GenericConsumer):
     def _makeKVPost(self, args, _):
@@ -851,7 +849,7 @@
 
     def tearDown(self):
         CatchLogs.tearDown(self)
-        fetchers.setDefaultFetcher(self._orig_fetcher)
+        fetchers.setDefaultFetcher(self._orig_fetcher, wrap_exceptions=False)
 
     def test_error(self):
         self.fetcher.response = HTTPResponse(
@@ -904,16 +902,44 @@
         fetchers.setDefaultFetcher(self.fetcher)
         self.consumer = self.consumer_class(self.store)
 
-    def test_error(self):
+    def test_error_404(self):
+        """404 from a kv post raises HTTPFetchingError"""
         self.fetcher.response = HTTPResponse(
             "http://some_url", 404, {'Hea': 'der'}, 'blah:blah\n')
-        r = self.consumer._makeKVPost({'openid.mode':'associate'},
-                                      "http://server_url")
-        self.failUnlessEqual(r, None)
-        self.failUnless(self.messages)
+        self.failUnlessRaises(
+            fetchers.HTTPFetchingError,
+            self.consumer._makeKVPost,
+            {'openid.mode':'associate'},
+            "http://server_url")
+
+    def test_error_exception_unwrapped(self):
+        """Ensure that exceptions are bubbled through from fetchers
+        when making associations
+        """
+        self.fetcher = ExceptionRaisingMockFetcher()
+        fetchers.setDefaultFetcher(self.fetcher, wrap_exceptions=False)
+        self.failUnlessRaises(self.fetcher.MyException,
+                              self.consumer._makeKVPost,
+                              {'openid.mode':'associate'},
+                              "http://server_url")
+
+        # exception fetching returns no association
+        e = OpenIDServiceEndpoint()
+        e.server_url = 'some://url'
+        self.failUnlessRaises(self.fetcher.MyException,
+                              self.consumer._getAssociation, e)
+
+        self.failUnlessRaises(self.fetcher.MyException,
+                              self.consumer._checkAuth,
+                              Message.fromPostArgs({'openid.signed':''}),
+                              'some://url')
 
-    def test_error_exception(self):
+    def test_error_exception_wrapped(self):
+        """Ensure that openid.fetchers.HTTPFetchingError is caught by
+        the association creation stuff.
+        """
         self.fetcher = ExceptionRaisingMockFetcher()
+        # This will wrap exceptions!
         fetchers.setDefaultFetcher(self.fetcher)
         self.failUnlessRaises(fetchers.HTTPFetchingError,
                               self.consumer._makeKVPost,
@@ -925,10 +951,8 @@
         e.server_url = 'some://url'
         self.failUnless(self.consumer._getAssociation(e) is None)
 
-        self.failUnlessRaises(fetchers.HTTPFetchingError,
-                              self.consumer._checkAuth,
-                              Message.fromPostArgs({'openid.signed':''}),
-                              'some://url')
+        msg = Message.fromPostArgs({'openid.signed':''})
+        self.failIf(self.consumer._checkAuth(msg, 'some://url'))
 
 
 class TestAuthRequest(unittest.TestCase):
@@ -1436,6 +1460,13 @@
                               }, args)
 
     # XXX: test the other types
+
+# XXX: NOT TO CHECK IN
+class TestParseAssociation(unittest.TestCase):
+    def setUp(self):
+        self.args = {
+            }
+        self.msg = Message.fromOpenIDArgs()
 
 if __name__ == '__main__':
     unittest.main()



Mime
View raw message