[tor-commits] [translation/torcheck_completed] Update translations for torcheck_completed
commit 32f49b90b7859d22fd95160eb30072ee75a2b286 Author: Translation commit bot Date: Wed Mar 26 06:45:12 2014 + Update translations for torcheck_completed --- id/torcheck.po | 52 +++- 1 file changed, 47 insertions(+), 5 deletions(-) diff --git a/id/torcheck.po b/id/torcheck.po index 96c0f52..6e272b0 100644 --- a/id/torcheck.po +++ b/id/torcheck.po @@ -1,16 +1,20 @@ # TorCheck gettext template -# Copyright (C) 2008-2012 The Tor Project, Inc +# Copyright (C) 2008-2013 The Tor Project, Inc # # Translators: # brain90 , 2012 +# brain90 , 2012 +# Jaya Wijaya , 2012 # Jaya Wijaya , 2012 +# bedouin , 2014 +# Sutamatamasu , 2013 # Sutamatamasu , 2013 msgid "" msgstr "" "Project-Id-Version: The Tor Project\n" "POT-Creation-Date: 2012-02-16 20:28+PDT\n" -"PO-Revision-Date: 2013-11-06 09:10+\n" -"Last-Translator: runasand \n" +"PO-Revision-Date: 2014-03-26 06:43+\n" +"Last-Translator: bedouin \n" "Language-Team: Indonesian (http://www.transifex.com/projects/p/torproject/language/id/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" @@ -19,8 +23,8 @@ msgstr "" "Language: id\n" "Plural-Forms: nplurals=1; plural=0;\n" -msgid "Congratulations. Your browser is configured to use Tor." -msgstr "Selamat. Peramban anda siap menjalankan Tor." +msgid "Congratulations. This browser is configured to use Tor." +msgstr "Selamat. browser ini telah terkonfigurasi untuk menggunakan Tor." msgid "" "Please refer to the https://www.torproject.org/\";>Tor website " @@ -56,3 +60,41 @@ msgstr "Pemadaman layanan sementara mencegah kami untuk menentukan bahwa alamat msgid "Your IP address appears to be: " msgstr "Alamat IP Anda akan tampak sebagai :" + +msgid "Are you using Tor?" +msgstr "Apa anda menggunakan Tor?" + +msgid "This page is also available in the following languages:" +msgstr "Halaman ini juga tersedia dalam bahasa:" + +msgid "For more information about this exit relay, see:" +msgstr "untuk informasi lebih lanjut tentang menyampaikan keluar ini, lihat:" + +msgid "" +"The Tor Project is a US 501(c)(3) non-profit dedicated to the research, " +"development, and education of online anonymity and privacy." +msgstr "Proyek Tor adalah US 501(c)(3) nirlaba didedikasikan untuk riret, pengembangan, dan pendidikan anonim online dan privasi." + +msgid "Learn More »" +msgstr "Pelajari Lebih lanjut »" + +msgid "Go" +msgstr "Pergi" + +msgid "Short User Manual" +msgstr "Manual Pengguna Singkat" + +msgid "Donate to Support Tor" +msgstr "Donasi untuk Mendukung Tor" + +msgid "Tor Q&A Site" +msgstr "Situs Q&A Tor" + +msgid "Volunteer" +msgstr "Sukarelawan" + +msgid "JavaScript is enabled." +msgstr "Javascript aktif." + +msgid "JavaScript is disabled." +msgstr "Javascript Nonaktif" ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [translation/torcheck] Update translations for torcheck
commit 3e098c5227ef870374af72e169e6b5f8dd2b596c Author: Translation commit bot Date: Wed Mar 26 06:45:09 2014 + Update translations for torcheck --- id/torcheck.po | 26 +++--- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/id/torcheck.po b/id/torcheck.po index 5f7f523..6e272b0 100644 --- a/id/torcheck.po +++ b/id/torcheck.po @@ -3,14 +3,18 @@ # # Translators: # brain90 , 2012 +# brain90 , 2012 +# Jaya Wijaya , 2012 # Jaya Wijaya , 2012 +# bedouin , 2014 +# Sutamatamasu , 2013 # Sutamatamasu , 2013 msgid "" msgstr "" "Project-Id-Version: The Tor Project\n" "POT-Creation-Date: 2012-02-16 20:28+PDT\n" -"PO-Revision-Date: 2014-01-02 08:41+\n" -"Last-Translator: runasand \n" +"PO-Revision-Date: 2014-03-26 06:43+\n" +"Last-Translator: bedouin \n" "Language-Team: Indonesian (http://www.transifex.com/projects/p/torproject/language/id/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" @@ -69,28 +73,28 @@ msgstr "untuk informasi lebih lanjut tentang menyampaikan keluar ini, lihat:" msgid "" "The Tor Project is a US 501(c)(3) non-profit dedicated to the research, " "development, and education of online anonymity and privacy." -msgstr "" +msgstr "Proyek Tor adalah US 501(c)(3) nirlaba didedikasikan untuk riret, pengembangan, dan pendidikan anonim online dan privasi." msgid "Learn More »" -msgstr "" +msgstr "Pelajari Lebih lanjut »" msgid "Go" -msgstr "" +msgstr "Pergi" msgid "Short User Manual" -msgstr "" +msgstr "Manual Pengguna Singkat" msgid "Donate to Support Tor" -msgstr "" +msgstr "Donasi untuk Mendukung Tor" msgid "Tor Q&A Site" -msgstr "" +msgstr "Situs Q&A Tor" msgid "Volunteer" -msgstr "" +msgstr "Sukarelawan" msgid "JavaScript is enabled." -msgstr "" +msgstr "Javascript aktif." msgid "JavaScript is disabled." -msgstr "" +msgstr "Javascript Nonaktif" ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Update translations.
commit 43b069d31f32e2596bc4ce014f8b8fb214714059 Author: Isis Lovecruft Date: Wed Mar 26 05:27:58 2014 + Update translations. --- lib/bridgedb/i18n/ca/LC_MESSAGES/bridgedb.po| 102 ++ lib/bridgedb/i18n/cs/LC_MESSAGES/bridgedb.po| 104 +++ lib/bridgedb/i18n/es_CL/LC_MESSAGES/bridgedb.po | 101 ++ lib/bridgedb/i18n/fi/LC_MESSAGES/bridgedb.po| 102 ++ lib/bridgedb/i18n/fr_CA/LC_MESSAGES/bridgedb.po | 104 +++ lib/bridgedb/i18n/id/LC_MESSAGES/bridgedb.po| 101 ++ lib/bridgedb/i18n/km/LC_MESSAGES/bridgedb.po| 102 ++ lib/bridgedb/i18n/mk/LC_MESSAGES/bridgedb.po| 101 ++ lib/bridgedb/i18n/pt/LC_MESSAGES/bridgedb.po| 102 ++ lib/bridgedb/i18n/th/LC_MESSAGES/bridgedb.po|2 +- lib/bridgedb/i18n/uk/LC_MESSAGES/bridgedb.po| 102 ++ lib/bridgedb/i18n/zh_TW/LC_MESSAGES/bridgedb.po | 100 ++ 12 files changed, 1122 insertions(+), 1 deletion(-) diff --git a/lib/bridgedb/i18n/ca/LC_MESSAGES/bridgedb.po b/lib/bridgedb/i18n/ca/LC_MESSAGES/bridgedb.po new file mode 100644 index 000..ee74f59 --- /dev/null +++ b/lib/bridgedb/i18n/ca/LC_MESSAGES/bridgedb.po @@ -0,0 +1,102 @@ +# Translations template for BridgeDB. +# Copyright (C) 2013 ORGANIZATION +# This file is distributed under the same license as the BridgeDB project. +# +# Translators: +# Translators: +# Illenc , 2013 +# Toni Hermoso Pulido , 2012 +msgid "" +msgstr "" +"Project-Id-Version: The Tor Project\n" +"Report-Msgid-Bugs-To: https://trac.torproject.org/projects/tor\n"; +"POT-Creation-Date: 2013-03-27 21:41+\n" +"PO-Revision-Date: 2013-10-27 08:40+\n" +"Last-Translator: Illenc \n" +"Language-Team: Catalan (http://www.transifex.com/projects/p/torproject/language/ca/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 0.9.6\n" +"Language: ca\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: lib/bridgedb/templates/base.html:33 +msgid "What are bridges?" +msgstr "Què són els ponts?" + +#: lib/bridgedb/templates/base.html:34 +#, python-format +msgid "" +"%s Bridge relays %s are Tor relays that help you circumvent censorship." +msgstr "%s mecanismes Pont %s són mecanismes Tor per esquivar la censura." + +#: lib/bridgedb/templates/base.html:39 +msgid "I need an alternative way of getting bridges!" +msgstr "Necessit una manera alternativa d'obtenir ponts" + +#: lib/bridgedb/templates/base.html:40 +#, python-format +msgid "" +"Another way to find public bridge addresses is to send an email (from a %s " +"or a %s address) to %s with the line 'get bridges' by itself in the body of " +"the mail." +msgstr "Una altra manera de trobar adreces de ponts públics és enviant un correu (de %s o %s address) a %s amb el text 'get bridges' al cos del correu." + +#: lib/bridgedb/templates/base.html:48 +msgid "My bridges don't work! I need help!" +msgstr "No em funcionen els ponts! Ajuda!" + +#: lib/bridgedb/templates/base.html:49 +#, python-format +msgid "" +"If your Tor doesn't work, you should email %s. Try including as much info " +"about your case as you can, including the list of bridges you used, the " +"bundle filename/version you used, the messages that Tor gave out, etc." +msgstr "Si no us funciona Tor, envieu un correu %s. Hi heu d'incloure el mà xim d'informació sobre el vostre cas: amb la llista de ponts que teniu, la versió, el missatge que Tor us dóna, etc." + +#: lib/bridgedb/templates/bridges.html:10 +msgid "" +"To use the above lines, go to Vidalia's Network settings page, and click " +"\"My ISP blocks connections to the Tor network\". Then add each bridge " +"address one at a time." +msgstr "Per a usar l'anterior lÃnia, aneu a la configuració de Xarxa Vidalia, clicau a \"El meu proveïdor bloca les connexions Tor\" Després afegiu les adreces de pont una per una." + +#: lib/bridgedb/templates/bridges.html:13 +msgid "No bridges currently available" +msgstr "No hi ha ponts disponibles" + +#: lib/bridgedb/templates/captcha.html:6 +msgid "Upgrade your browser to Firefox" +msgstr "Actualitza el navegador a Firefox" + +#: lib/bridgedb/templates/captcha.html:8 +msgid "Type the two words" +msgstr "Escriviu les dues paraules" + +#: lib/bridgedb/templates/index.html:6 +msgid "Step 1" +msgstr "Passa 1" + +#: lib/bridgedb/templates/index.html:8 +#, python-format +msgid "Get %s Tor Browser Bundle %s" +msgstr "Descarrega %s el navegador Tor Bundle %s" + +#: lib/bridgedb/templates/index.html:13 +msgid "Step 2" +msgstr "Passa 2" + +#: lib/bridgedb/templates/index.html:15 +#, python-format +msgid "Get %s bridges %s" +msgstr "Descarrega %s ponts %s" + +#: lib/bridgedb/templates/index.html:19 +msgid "Step 3" +msgstr "Passa 3" + +#: lib/bridgedb/templates/index.html:21 +#, python-format +msgid "Now %
[tor-commits] [bridgedb/master] Update CHANGELOG with additional changes for 0.1.6.
commit 24dc8dc82033cbd8ee14d1c06db1e2a3fbcfdbd6 Author: Isis Lovecruft Date: Wed Mar 26 05:42:51 2014 + Update CHANGELOG with additional changes for 0.1.6. --- CHANGELOG |7 ++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG b/CHANGELOG index bf895ad..092ce8c 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,10 +1,15 @@ -Changes in version 0.1.6 - 2014-03-17 +Changes in version 0.1.6 - 2014-03-26 BridgeDB 0.1.6 includes fixes for the following bugs: + * FIXES #11196 BridgeDB should use leekspin * FIXES #11218 ReCaptchaProtectedResource.checkSolution() doesn't expect a deferred * FIXES #11219 BridgeDB's twisted version doesn´t have a `t.w.client.HTTPConnectionPool` class + * FIXES #11231 BridgeDB's txrecaptcha returns the "No bridges + available!" page if 'captcha_response_field' is blank +And includes the following general changes: + * ADDS several new translations languages. Changes in version 0.1.5 - 2014-02-27 BridgeDB 0.1.5 includes fixes for the following bugs: ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Merge branch 'release-0.1.6'
commit f266f32c365eb7a16cf156cc02f7e492266a7b51 Merge: 783babc 24dc8dc Author: Isis Lovecruft Date: Wed Mar 26 05:46:11 2014 + Merge branch 'release-0.1.6' .travis.yml |8 +- CHANGELOG | 13 + Makefile|5 +- bridgedb.conf |7 +- lib/bridgedb/Bridges.py | 52 +- lib/bridgedb/Dist.py| 24 +- lib/bridgedb/EmailServer.py | 32 +- lib/bridgedb/HTTPServer.py | 208 -- lib/bridgedb/i18n/ca/LC_MESSAGES/bridgedb.po| 102 +++ lib/bridgedb/i18n/cs/LC_MESSAGES/bridgedb.po| 104 +++ lib/bridgedb/i18n/es_CL/LC_MESSAGES/bridgedb.po | 101 +++ lib/bridgedb/i18n/fi/LC_MESSAGES/bridgedb.po| 102 +++ lib/bridgedb/i18n/fr_CA/LC_MESSAGES/bridgedb.po | 104 +++ lib/bridgedb/i18n/id/LC_MESSAGES/bridgedb.po| 101 +++ lib/bridgedb/i18n/km/LC_MESSAGES/bridgedb.po| 102 +++ lib/bridgedb/i18n/mk/LC_MESSAGES/bridgedb.po| 101 +++ lib/bridgedb/i18n/pt/LC_MESSAGES/bridgedb.po| 102 +++ lib/bridgedb/i18n/th/LC_MESSAGES/bridgedb.po|2 +- lib/bridgedb/i18n/uk/LC_MESSAGES/bridgedb.po| 102 +++ lib/bridgedb/i18n/zh_TW/LC_MESSAGES/bridgedb.po | 100 +++ lib/bridgedb/runner.py |2 +- lib/bridgedb/templates/base.html| 12 +- lib/bridgedb/test/test_HTTPServer.py| 669 + lib/bridgedb/test/test_bridgedb.py | 12 +- lib/bridgedb/test/test_txrecaptcha.py | 21 +- lib/bridgedb/txrecaptcha.py | 52 +- scripts/gen_bridge_descriptors | 870 --- setup.py|8 +- 28 files changed, 2106 insertions(+), 1012 deletions(-) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Merge branch 'hotfix/11218-async-render' into develop
commit 9eca0869ffe25057f0e23bf39115945e70b2e68b Merge: 80a1331 a3bb0ec Author: Isis Lovecruft Date: Wed Mar 26 05:10:08 2014 + Merge branch 'hotfix/11218-async-render' into develop Makefile |4 +- lib/bridgedb/HTTPServer.py | 157 ++ lib/bridgedb/test/test_HTTPServer.py | 76 3 files changed, 167 insertions(+), 70 deletions(-) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add ReCaptchaProtectedResource._renderDeferred() to render deferred resources.
commit db8eef49536f0c18891bdf1f5151733e07ffc8d3 Author: Isis Lovecruft Date: Tue Mar 25 22:28:45 2014 + Add ReCaptchaProtectedResource._renderDeferred() to render deferred resources. --- lib/bridgedb/HTTPServer.py | 33 + 1 file changed, 33 insertions(+) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index e2f1059..4c5d414 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -367,6 +367,39 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): self.recaptchaPubKey = recaptchaPubKey self.recaptchaRemoteIP = remoteip +def _renderDeferred(self, checkedRequest): +"""Render this resource asynchronously. + +:type checkedRequest: tuple +:param checkedRequest: A tuple of ``(bool, request)``, as returned +from :meth:`checkSolution`. +""" +try: +valid, request = checkedRequest +except Exception as err: +logging.error("Error in _renderDeferred(): %s" % err) +return + +logging.debug("Attemping to render %svalid request %r" + % ('' if valid else 'in', request)) +if valid is True: +try: +rendered = self.resource.render(request) +except Exception as err: # pragma: no cover +rendered = replaceErrorPage(err) +else: +logging.info("Client failed a CAPTCHA; redirecting to %s" + % request.uri) +rendered = redirectTo(request.uri, request) + +try: +request.write(rendered) +request.finish() +except Exception as err: # pragma: no cover +logging.exception(err) + +return request + def getCaptchaImage(self, request): """Get a CAPTCHA image from the remote reCaptcha server. ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add a mocked DummyBridge class to test_HTTPServer.py.
commit f0ca59c8d1792d2fcbea54b0eb29feb10ecacdb0 Author: Isis Lovecruft Date: Wed Mar 19 17:46:32 2014 + Add a mocked DummyBridge class to test_HTTPServer.py. This is used to test that bridges are actually returned on 'bridges.html' results pages, and is missing all of the real class's methods except for `getConfigLine()`. The latter method needs to be mocked because is used in `HTTPServer.WebResourceBridges.render()` to get the bridge line to display to a client. --- lib/bridgedb/test/test_HTTPServer.py | 49 -- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 119d2fc..05e041c 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -11,8 +11,11 @@ """Unittests for :mod:`bridgedb.HTTPServer`.""" +from __future__ import print_function + import logging import os +import random import shutil import ipaddr @@ -354,7 +357,6 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): self.request.addArg('captcha_response_field', '') page = self.captchaResource.render_POST(self.request) -print page self.assertEqual(BeautifulSoup(page).find('meta')['http-equiv'], 'refresh') @@ -370,6 +372,49 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): self.request.addArg('captcha_response_field', expectedResponse) page = self.captchaResource.render_POST(self.request) -print page self.assertEqual(BeautifulSoup(page).find('meta')['http-equiv'], 'refresh') + + +class DummyBridge(object): +"""A mock :class:`bridgedb.Bridges.Bridge` which only supports a mocked +``getConfigLine`` method.""" + +def _randORPort(self): return random.randint(9001, ) +def _randPTPort(self): return random.randint(6001, ) +def _returnFour(self): return random.randint(2**24, 2**32-1) +def _returnSix(self): return random.randint(2**24, 2**128-1) + +def __init__(self, transports=[]): +"""Create a mocked bridge suitable for testing distributors and web +resource rendering. +""" +self.nickname = "bridge-{0}".format(self._returnFour()) +self.ip = ipaddr.IPv4Address(self._returnFour()) +self.orport = self._randORPort() +self.transports = transports +self.running = True +self.stable = True +self.blockingCountries = {} +self.desc_digest = None +self.ei_digest = None +self.verified = False +self.fingerprint = "".join(random.choice('abcdef0123456789') + for _ in xrange(40)) +self.or_addresses = {ipaddr.IPv6Address(self._returnSix()): + self._randORPort()} + +def getConfigLine(self, includeFingerprint=True, + addressClass=ipaddr.IPv4Address, + transport=None, + request=None): +"""Get a "torrc" bridge config line to give to a client.""" +line = [] +if transport is not None: +#print("getConfigLine got transport=%r" % transport) +line.append(str(transport)) +line.append("%s:%s" % (self.ip, self.orport)) +if includeFingerprint is True: line.append(self.fingerprint) +bridgeLine = " ".join([item for item in line]) +#print "Created config line: %r" % bridgeLine +return bridgeLine ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add coverage pragma lines to blanket excepts in HTTPServer.
commit 4eb7ef398e2e2c28f19031fca6595c679c613fe9 Author: Isis Lovecruft Date: Wed Mar 26 04:56:31 2014 + Add coverage pragma lines to blanket excepts in HTTPServer. They are gross, but we have to have these general excepts everywhere, otherwise users could be shown a traceback. --- lib/bridgedb/HTTPServer.py | 12 ++-- 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index d7b56b3..f4ab592 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -64,7 +64,7 @@ _geoipdb = '/usr/share/GeoIP/GeoIP.dat' try: # Make sure we have the database before trying to import the module: -if not os.path.isfile(_geoipdb): +if not os.path.isfile(_geoipdb): # pragma: no cover raise EnvironmentError("Could not find %r. On Debian-based systems, "\ "please install the geoip-database package." % _geoipdb) @@ -74,7 +74,7 @@ try: import pygeoip geoip = pygeoip.GeoIP(_geoipdb, flags=pygeoip.MEMORY_CACHE) logging.info("GeoIP database loaded") -except Exception as err: +except Exception as err: # pragma: no cover logging.warn("Error while loading geoip module: %r" % err) geoip = None @@ -162,7 +162,7 @@ class CaptchaProtectedResource(resource.Resource): try: challenge = request.args['captcha_challenge_field'][0] response = request.args['captcha_response_field'][0] -except: +except Exception: # pragma: no cover return redirectTo(request.URLPath(), request) return (challenge, response) @@ -314,7 +314,7 @@ class GimpCaptchaProtectedResource(CaptchaProtectedResource): capt.get() except captcha.GimpCaptchaError as error: logging.error(error) -except Exception as error: +except Exception as error: # pragma: no cover logging.error("Unhandled error while retrieving Gimp captcha!") logging.exception(error) @@ -466,7 +466,7 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): % (Util.logSafely(clientIP), request.args)) def checkResponse(solution, request): -if solution.is_valid: +if solution.is_valid: # pragma: no cover logging.info("Valid CAPTCHA solution from %r." % Util.logSafely(clientIP)) return (True, request) @@ -531,7 +531,7 @@ class WebResourceOptions(resource.Resource): try: rtl = usingRTLLang(request) -except Exception as err: +except Exception as err: # pragma: no cover logging.exception(err) logging.error("The gettext files were not properly installed.") logging.info("To install translations, try doing `python " \ ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Merge branch 'fix/11196-use-leekspin_r1' into develop
commit 715ab6a93636f7616036adcd72cf168ede752b42 Merge: 97e261d c9ba8cf Author: Isis Lovecruft Date: Tue Mar 25 02:28:31 2014 + Merge branch 'fix/11196-use-leekspin_r1' into develop .travis.yml|7 +- lib/bridgedb/runner.py |2 +- lib/bridgedb/test/test_bridgedb.py | 12 +- scripts/gen_bridge_descriptors | 870 setup.py |8 +- 5 files changed, 16 insertions(+), 883 deletions(-) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add --rcfile option to additional coverage lines in Makefile.
commit eabc57bdb24dec6d4693463a7029b1106bf71778 Author: Isis Lovecruft Date: Wed Mar 26 04:59:13 2014 + Add --rcfile option to additional coverage lines in Makefile. --- Makefile |4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index edfc69f..22a231e 100644 --- a/Makefile +++ b/Makefile @@ -45,5 +45,5 @@ clean: coverage: -coverage run --rcfile=".coveragerc" $(TRIAL) ./lib/bridgedb/test/test_*.py - -coverage report - -coverage html + -coverage report --rcfile=".coveragerc" + -coverage html --rcfile=".coveragerc" ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add unittests for _renderDeferred().
commit 3fe40199972595895c05d8760dade246e8134fe4 Author: Isis Lovecruft Date: Wed Mar 26 05:01:04 2014 + Add unittests for _renderDeferred(). --- lib/bridgedb/test/test_HTTPServer.py | 53 ++ 1 file changed, 53 insertions(+) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index ea2f6e4..4e6c86b 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -23,6 +23,7 @@ import ipaddr from BeautifulSoup import BeautifulSoup from twisted.internet import reactor +from twisted.internet import task from twisted.trial import unittest from twisted.web.resource import Resource from twisted.web.test import requesthelper @@ -297,6 +298,58 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): except (AlreadyCalled, AlreadyCancelled): pass +def test_renderDeferred_invalid(self): +""":meth:`_renderDeferred` should redirect a ``Request`` (after the +CAPTCHA was NOT xsuccessfully solved) which results from a +``Deferred``'s callback. +""" +self.request.method = b'POST' + +def testCB(request): +"""Check the ``Request`` returned from ``_renderDeferred``.""" +self.assertIsInstance(request, DummyRequest) +soup = BeautifulSoup(b''.join(request.written)).find('meta')['http-equiv'] +self.assertEqual(soup, 'refresh') + +d = task.deferLater(reactor, 0, lambda x: x, (False, self.request)) +d.addCallback(self.captchaResource._renderDeferred) +d.addCallback(testCB) +return d + +def test_renderDeferred_valid(self): +""":meth:`_renderDeferred` should correctly render a ``Request`` (after +the CAPTCHA has been successfully solved) which results from a +``Deferred``'s callback. +""" +self.request.method = b'POST' + +def testCB(request): +"""Check the ``Request`` returned from ``_renderDeferred``.""" +self.assertIsInstance(request, DummyRequest) +html = b''.join(request.written) +self.assertSubstring('No bridges currently available', html) + +d = task.deferLater(reactor, 0, lambda x: x, (True, self.request)) +d.addCallback(self.captchaResource._renderDeferred) +d.addCallback(testCB) +return d + +def test_renderDeferred_nontuple(self): +""":meth:`_renderDeferred` should correctly render a ``Request`` (after +the CAPTCHA has been successfully solved) which results from a +``Deferred``'s callback. +""" +self.request.method = b'POST' + +def testCB(request): +"""Check the ``Request`` returned from ``_renderDeferred``.""" +self.assertIs(request, None) + +d = task.deferLater(reactor, 0, lambda x: x, (self.request)) +d.addCallback(self.captchaResource._renderDeferred) +d.addCallback(testCB) +return d + def test_checkSolution_blankFields(self): """:meth:`HTTPServer.ReCaptchaProtectedResource.checkSolution` should return a redirect if is the solution field is blank. ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Remove gimp captcha unittest code from recaptcha unittest setUp().
commit 2c41a3f7c1606ccc26812db913e11808ffabc0f8 Author: Isis Lovecruft Date: Wed Mar 26 05:00:20 2014 + Remove gimp captcha unittest code from recaptcha unittest setUp(). --- lib/bridgedb/test/test_HTTPServer.py |5 - 1 file changed, 5 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 57f0d80..ea2f6e4 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -266,11 +266,6 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): """Create a :class:`HTTPServer.WebResourceBridges` and protect it with a :class:`ReCaptchaProtectedResource`. """ -# Create our cached CAPTCHA directory: -self.captchaDir = 'captchas' -if not os.path.isdir(self.captchaDir): -os.makedirs(self.captchaDir) - # Set up our resources to fake a minimal HTTP(S) server: self.pagename = b'captcha.html' self.root = Resource() ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Give the PluggableTransports class a real docstring.
commit 18d8d30bf67c13396516cb980cd9523720aa2b40 Author: Isis Lovecruft Date: Thu Mar 20 12:46:17 2014 + Give the PluggableTransports class a real docstring. --- lib/bridgedb/Bridges.py | 52 +++ 1 file changed, 48 insertions(+), 4 deletions(-) diff --git a/lib/bridgedb/Bridges.py b/lib/bridgedb/Bridges.py index 9dbafdf..2fb784a 100644 --- a/lib/bridgedb/Bridges.py +++ b/lib/bridgedb/Bridges.py @@ -466,12 +466,56 @@ re_ipv4 = re.compile("((?:\d{1,3}\.?){4}):(.*$)") class PluggableTransport(object): -""" -an object that represents a pluggable-transport method -and a reference to the relevant bridge -""" +"""A PT with reference to the parent bridge on which it is running.""" + def __init__(self, bridge, methodname, address, port, argdict=None): +"""Create a ``PluggableTransport`` describing a PT running on a bridge. + +Pluggable transports are described within a bridge's ``@type +bridge-extrainfo`` descriptor, see the ``Specifications: Client +behavior`` section and the ``TOR_PT_SERVER_TRANSPORT_OPTIONS`` +description in pt-spec.txt_ for additional specification. + +:type bridge: :class:`Bridge` +:param bridge: The parent bridge running this pluggable transport +instance, i.e. the main ORPort bridge whose +``@type bridge-server-descriptor`` contains a hash digest for a +``@type bridge-extrainfo-document``, the latter of which contains +the parameter of this pluggable transport in its ``transport`` +line. + +:param str methodname: The canonical "name" for this pluggable +transport, i.e. the one which would be specified in a torrc +file. For example, ``"obfs2"``, ``"obfs3"``, ``"scramblesuit"`` +would all be pluggable transport method names. + +:param str address: The IP address of the transport. Currently (as of +20 March 2014), there are no known, widely-deployed pluggable +transports which support IPv6. Ergo, this is very likely going to +be an IPv4 address. +:param int port: A integer specifying the port which this pluggable +transport is listening on. (This should likely be whatever port the +bridge specified in its ``ServerTransportPlugin`` torrc line, +unless the pluggable transport is running in "managed" mode.) + +:param dict argdict: Some PTs can take additional arguments, which +must be distributed to the client out-of-band. These are present +in the ``@type bridge-extrainfo-document``, in the ``transport`` +line like so:: + +METHOD SP ADDR ":" PORT SP [K=V[,K=V[,K=V[⦠+ +where K is the **argdict** key, and V is the value. For example, +in the case of ``scramblesuit``, for which the client must supply +a shared secret to the ``scramblesuit`` instance running on the +bridge, the **argdict** would be something like:: + +{'password': 'NEQGQYLUMUQGK5TFOJ4XI2DJNZTS4LRO'} + +.. _pt-spec.txt: + https://gitweb.torproject.org/torspec.git/blob/HEAD:/pt-spec.txt +""" #XXX: assert are disabled with python -O assert isinstance(bridge, Bridge) assert type(address) in (ipaddr.IPv4Address, ipaddr.IPv6Address) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Change ReCaptchaProtectedResource.render_POST() to call _renderDeferred().
commit 454e0f7870575a362d1d162918519f1e1fda5179 Author: Isis Lovecruft Date: Tue Mar 25 22:30:19 2014 + Change ReCaptchaProtectedResource.render_POST() to call _renderDeferred(). * FIXES #11218 (again). --- lib/bridgedb/HTTPServer.py | 12 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 4c5d414..d7b56b3 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -503,11 +503,15 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): ``'captcha_challenge_field'``, and the other, ``'captcha_response_field'``. These POST arguments should be obtained from :meth:`render_GET`. -:rtype: str -:returns: A rendered HTML page containing a ReCaptcha challenge image - for the client to solve. +:returns: :api:`twisted.web.server.NOT_DONE_YET`, in order to handle +the ``Deferred`` returned from :meth:`checkSolution`. Eventually, +when the ``Deferred`` request is done being processed, +:meth:`_renderDeferred` will handle rendering and displaying the +HTML to the client. """ -return CaptchaProtectedResource.render_POST(self, request) +d = self.checkSolution(request) +d.addCallback(self._renderDeferred) +return server.NOT_DONE_YET class WebResourceOptions(resource.Resource): ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Merge branch 'fix/11231-additional-bug-fixes' into develop
commit 00eaf9160f65c16c725ed7f05ac0583b9da63dc0 Merge: 7fdde31 b4f88ad Author: Isis Lovecruft Date: Fri Mar 21 22:30:10 2014 + Merge branch 'fix/11231-additional-bug-fixes' into develop lib/bridgedb/HTTPServer.py | 14 +- lib/bridgedb/txrecaptcha.py | 12 ++-- 2 files changed, 19 insertions(+), 7 deletions(-) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Remove 'installed-files.txt' after `make uninstall` completes.
commit 97e261d1ba04d42e948d6f417ebd1878bbce5004 Author: Isis Lovecruft Date: Tue Mar 25 00:43:21 2014 + Remove 'installed-files.txt' after `make uninstall` completes. --- Makefile |1 + 1 file changed, 1 insertion(+) diff --git a/Makefile b/Makefile index abf392e..edfc69f 100644 --- a/Makefile +++ b/Makefile @@ -30,6 +30,7 @@ force-install: uninstall: touch installed-files.txt cat installed-files.txt | xargs rm -rf + rm installed-files.txt reinstall: uninstall force-install ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add class wrapper for requesthelper.DummyRequest to support redirects.
commit ad774181faa5cd367e4173ce14a4449a3164abeb Author: Isis Lovecruft Date: Wed Mar 19 17:57:09 2014 + Add class wrapper for requesthelper.DummyRequest to support redirects. --- lib/bridgedb/test/test_HTTPServer.py | 20 1 file changed, 20 insertions(+) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index e2856c7..73297de 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -445,3 +445,23 @@ class DummyIPBasedDistributor(object): :meth:`WebResourceBridges.getBridgesForIP`. """ return [DummyBridge() for _ in xrange(N)] + + +class DummyRequest(requesthelper.DummyRequest): +"""Wrapper for :api:`twisted.test.requesthelper.DummyRequest` to add +redirect support. +""" + +def __init__(self, *args, **kwargs): +requesthelper.DummyRequest.__init__(self, *args, **kwargs) +self.redirect = self._redirect(self) + +def URLPath(self): +"""Fake the missing Request.URLPath too.""" +return self.uri + +def _redirect(self, request): +"""Stub method to add a redirect() method to DummyResponse.""" +newRequest = type(request) +newRequest.uri = request.uri +return newRequest ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Remove a superfluous error message about gettext files.
commit 31ec211fd62da1d816d3ecf73986f30c021bf097 Author: Isis Lovecruft Date: Wed Mar 26 04:58:31 2014 + Remove a superfluous error message about gettext files. --- lib/bridgedb/HTTPServer.py |3 --- 1 file changed, 3 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 24a970f..3809f2d 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -544,9 +544,6 @@ class WebResourceOptions(resource.Resource): rtl = usingRTLLang(request) except Exception as err: # pragma: no cover logging.exception(err) -logging.error("The gettext files were not properly installed.") -logging.info("To install translations, try doing `python " \ - "setup.py compile_catalog`.") request.setHeader("Content-Type", "text/html; charset=utf-8") return lookup.get_template('options.html').render(rtl=rtl) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Cleanup imports in bridgedb.HTTPServer.
commit dd67a2830d4366f966e780818abc7c94fede16bf Author: Isis Lovecruft Date: Tue Mar 25 22:13:18 2014 + Cleanup imports in bridgedb.HTTPServer. * CHANGE all objects named `resource` to something more specific, otherwise we cannot do `from twisted.web import resource`. --- lib/bridgedb/HTTPServer.py | 61 ++ lib/bridgedb/test/test_HTTPServer.py |6 ++-- 2 files changed, 36 insertions(+), 31 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 0de984b..c55e668 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -16,11 +16,11 @@ import os from twisted.internet import reactor from twisted.internet.error import CannotListenError -import twisted.web.resource from twisted.web.server import Site +from twisted.python import filepath +from twisted.web import resource from twisted.web import static from twisted.web.util import redirectTo -from twisted.python import filepath import bridgedb.Dist import bridgedb.I18n as I18n @@ -28,11 +28,12 @@ import bridgedb.Util as Util from bridgedb import captcha from bridgedb import crypto -from bridgedb.Filters import filterBridgesByIP6, filterBridgesByIP4 +from bridgedb import txrecaptcha +from bridgedb.Filters import filterBridgesByIP4 +from bridgedb.Filters import filterBridgesByIP6 from bridgedb.Filters import filterBridgesByTransport from bridgedb.Filters import filterBridgesByNotBlockedIn from bridgedb.parse import headers -from bridgedb import txrecaptcha from ipaddr import IPv4Address, IPv6Address from random import randint @@ -111,15 +112,15 @@ def replaceErrorPage(error, template_name=None): return rendered -class CaptchaProtectedResource(twisted.web.resource.Resource): +class CaptchaProtectedResource(resource.Resource): """A general resource protected by some form of CAPTCHA.""" isLeaf = True -def __init__(self, useForwardedHeader=False, resource=None): -twisted.web.resource.Resource.__init__(self) +def __init__(self, useForwardedHeader=False, protectedResource=None): +resource.Resource.__init__(self) self.useForwardedHeader = useForwardedHeader -self.resource = resource +self.resource = protectedResource def getClientIP(self, request): ip = None @@ -235,8 +236,9 @@ class GimpCaptchaProtectedResource(CaptchaProtectedResource): """ def __init__(self, secretKey=None, publicKey=None, hmacKey=None, - captchaDir='', useForwardedHeader=False, resource=None): -"""Protect a **resource** via this one, using a local CAPTCHA cache. + captchaDir='', useForwardedHeader=False, + protectedResource=None): +"""Protect a resource via this one, using a local CAPTCHA cache. :param str secretkey: A PKCS#1 OAEP-padded, private RSA key, used for verifying the client's solution to the CAPTCHA. See @@ -253,11 +255,12 @@ class GimpCaptchaProtectedResource(CaptchaProtectedResource): are stored. See the ``GIMP_CAPTCHA_DIR`` config setting. :param bool useForwardedHeader: If ``True``, obtain the client's IP address from the ``X-Forwarded-For`` HTTP header. -:type resource: :api:`twisted.web.resource.Resource` -:param resource: The resource to serve if the client successfully -passes the CAPTCHA challenge. +:type protectedResource: :api:`twisted.web.resource.Resource` +:param protectedResource: The resource to serve if the client +successfully passes the CAPTCHA challenge. """ -CaptchaProtectedResource.__init__(self, useForwardedHeader, resource) +CaptchaProtectedResource.__init__(self, useForwardedHeader, + protectedResource) self.secretKey = secretKey self.publicKey = publicKey self.hmacKey = hmacKey @@ -358,8 +361,9 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): """ def __init__(self, recaptchaPrivKey='', recaptchaPubKey='', remoteip='', - useForwardedHeader=False, resource=None): -CaptchaProtectedResource.__init__(self, useForwardedHeader, resource) + useForwardedHeader=False, protectedResource=None): +CaptchaProtectedResource.__init__(self, useForwardedHeader, + protectedResource) self.recaptchaPrivKey = recaptchaPrivKey self.recaptchaPubKey = recaptchaPubKey self.recaptchaRemoteIP = remoteip @@ -472,7 +476,7 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): return CaptchaProtectedResource.render_POST(self, request) -class WebResourceOptions(twisted.web.resource.Resource): +class WebResourceOptions(resource.Resource): """This resource is used by Twisted Web to give a web page with additi
[tor-commits] [bridgedb/master] Change unittests for reCaptcha render_POST() to check NOT_DONE_YET.
commit a3bb0ec066907bbf3b888b232d6b64a8a3c2f2ca Author: Isis Lovecruft Date: Wed Mar 26 05:03:10 2014 + Change unittests for reCaptcha render_POST() to check NOT_DONE_YET. --- lib/bridgedb/test/test_HTTPServer.py |6 ++ 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 22b9c63..872be3c 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -400,8 +400,7 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): self.request.addArg('captcha_response_field', '') page = self.captchaResource.render_POST(self.request) -self.assertEqual(BeautifulSoup(page).find('meta')['http-equiv'], - 'refresh') +self.assertEqual(page, HTTPServer.server.NOT_DONE_YET) def test_render_POST_wrongSolution(self): """render_POST() with a wrong 'captcha_response_field' should return @@ -415,8 +414,7 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): self.request.addArg('captcha_response_field', expectedResponse) page = self.captchaResource.render_POST(self.request) -self.assertEqual(BeautifulSoup(page).find('meta')['http-equiv'], - 'refresh') +self.assertEqual(page, HTTPServer.server.NOT_DONE_YET) class DummyBridge(object): ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add unittests for HTTPServer.WebResourceOptions.
commit 27280d9fc6aa527eb7a80708df1b25195840567a Author: Isis Lovecruft Date: Wed Mar 26 05:10:26 2014 + Add unittests for HTTPServer.WebResourceOptions. --- lib/bridgedb/test/test_HTTPServer.py | 26 ++ 1 file changed, 26 insertions(+) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 872be3c..c7308a3 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -641,3 +641,29 @@ class WebResourceBridgesTests(unittest.TestCase): self.assertIsInstance(int(port), int) self.assertGreater(int(port), 0) self.assertLessEqual(int(port), 65535) + + +class WebResourceOptionsTests(unittest.TestCase): +"""Tests for :class:`bridgedb.HTTPServer.WebResourceOptions`.""" + +def setUp(self): +"""Create a :class:`HTTPServer.WebResourceOptions`.""" +# Set up our resources to fake a minimal HTTP(S) server: +self.pagename = b'options.html' +self.root = Resource() +self.optionsResource = HTTPServer.WebResourceOptions() +self.root.putChild(self.pagename, self.optionsResource) + +def test_render_GET_RTLlang(self): +"""Test rendering a request for obfs3 bridges in Arabic.""" +request = DummyRequest(["bridges?transport=obfs3"]) +request.method = b'GET' +request.getClientIP = lambda: '3.3.3.3' +request.headers.update({'accept-language': 'he'}) +# We actually have to set the request args manually when using a +# DummyRequest: +request.args.update({'transport': 'obfs2'}) + +page = self.optionsResource.render(request) +self.assertSubstring("direction: rtl", page) +self.assertSubstring("××× ×שר××?", page) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Change checkSolution() unittest to check for tuple.
commit 9ec8802c7b326bfd518d70211e52afc14fc57e4e Author: Isis Lovecruft Date: Wed Mar 26 05:02:03 2014 + Change checkSolution() unittest to check for tuple. --- lib/bridgedb/test/test_HTTPServer.py |6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 4e6c86b..22b9c63 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -358,9 +358,9 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): self.request.addArg('captcha_challenge_field', '') self.request.addArg('captcha_response_field', '') -self.assertIs(False, - self.successResultOf( - self.captchaResource.checkSolution(self.request))) +self.assertEqual((False, self.request), + self.successResultOf( + self.captchaResource.checkSolution(self.request))) def test_getRemoteIP_useRandomIP(self): """Check that removing our remoteip setting produces a random IP.""" ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add a steaming pile of XXXs and FIXMEs to problems in WebResourceBridges.
commit 17f9650dfdcd0a0a00bd245295fa957efe3e7dfc Author: Isis Lovecruft Date: Wed Mar 19 18:27:01 2014 + Add a steaming pile of XXXs and FIXMEs to problems in WebResourceBridges. --- lib/bridgedb/HTTPServer.py | 14 +- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 27dd61e..0de984b 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -426,7 +426,6 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): logging.debug("Captcha from %r. Parameters: %r" % (Util.logSafely(clientIP), request.args)) - def checkResponse(solution, clientIP): if solution.is_valid: logging.info("Valid CAPTCHA solution from %r." @@ -564,10 +563,14 @@ class WebResourceBridges(twisted.web.resource.Resource): :rtype: str :returns: A plaintext or HTML response to serve. """ +# XXX why are we getting the interval if our distributor might be +# using bridgedb.Time.NoSchedule? interval = self.schedule.getInterval(time.time()) bridges = ( ) ip = None countryCode = None + +# XXX this code is duplicated in CaptchaProtectedResource if self.useForwardedHeader: h = request.getHeader("X-Forwarded-For") if h: @@ -578,6 +581,8 @@ class WebResourceBridges(twisted.web.resource.Resource): else: ip = request.getClientIP() +# XXX This can also be a separate function +# XXX if the ip is None, this throws an exception if geoip: countryCode = geoip.country_code_by_addr(ip) if countryCode: @@ -587,6 +592,7 @@ class WebResourceBridges(twisted.web.resource.Resource): if rtl: logging.debug("Rendering RTL response.") +# XXX separate function again format = request.args.get("format", None) if format and len(format): format = format[0] # choose the first arg @@ -596,6 +602,9 @@ class WebResourceBridges(twisted.web.resource.Resource): ipv6 = request.args.get("ipv6", False) if ipv6: ipv6 = True # if anything after ?ipv6= +# XXX oh dear hell. why not check for the '?transport=' arg before +# regex'ing? And why not compile the regex once, somewhere outside +# this function and class? try: # validate method name transport = re.match('[_a-zA-Z][_a-zA-Z0-9]*', @@ -673,6 +682,9 @@ class WebResourceBridges(twisted.web.resource.Resource): else: request.setHeader("Content-Type", "text/html; charset=utf-8") try: +# XXX FIXME the returned page from +# ``WebResourceBridgesTests.test_render_GET_RTLlang`` +# is in Arabic and has ``! Doh. template = lookup.get_template('bridges.html') rendered = template.render(answer=bridgeLines, rtl=rtl) except Exception as err: ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Remove old scripts/gen_bridge_descriptors; use leekspin.
commit c9ba8cffb49e063690c456f97978aaaf279f92df Author: Isis Lovecruft Date: Mon Mar 24 03:27:30 2014 + Remove old scripts/gen_bridge_descriptors; use leekspin. --- scripts/gen_bridge_descriptors | 870 1 file changed, 870 deletions(-) diff --git a/scripts/gen_bridge_descriptors b/scripts/gen_bridge_descriptors deleted file mode 100644 index 362ed3d..000 --- a/scripts/gen_bridge_descriptors +++ /dev/null @@ -1,870 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -"""Generate valid and signed descriptors for mocked Tor relays or bridges. - -.. todo:: Finish enough CFFI_ bindings for the newer PyNaCl_ (or enough of the -SWIG_ bindings for the older pynacl_) to be able to emulate the following -curvecp_ command (the ``curvecp*`` commands require libchloride_): - -$ curvecpmakekey ntor-key -$ curvecpprintkey ntor-key > ntor-key.hex -$ python -c 'import binascii, sys; \ -key_hex=open('./ntor-key.hex','rb').read();\ -key_b64=binascii.b2a_base64(binascii.unhexlify(key_hex));\ -sys.stdout.write(key_b64);' - -.. _CFFI: https://cffi.readthedocs.org -.. _PyNaCl: https://github.com/seanlynch/pynacl -.. _SWIG: https://github.com/swig/swig -.. _pynacl: https://github.com/seanlynch/pynacl -.. _curvecp: http://curvecp.org/ -.. _libchloride: https://github.com/jedisct1/libchloride - -.. authors:: Isis Lovecruft 0xA3ADB67A2CDB8B35 - Matthew Finkel -.. licence:: distributed with BridgeDB, see included LICENSE file -.. copyright:: (c) 2013 Matthew Finkel, Isis Lovecruft, The Tor Project, Inc. -""" - -from __future__ import print_function -from __future__ import absolute_import -from __future__ import unicode_literals - -import argparse -import binascii -import hashlib -import ipaddr -import math -import os -import sys -import random -import re -import time -import traceback - -from datetime import datetime -from codecs import open as open - -try: -import OpenSSL.crypto -except (ImportError, NameError) as error: -print("This script requires pyOpenSSL>=0.13.0") -raise SystemExit(error.message) -try: -from bridgedb.parse import versions -except (ImportError, NameError) as error: -print(error.message) -print("WARNING: Cannot import bridgedb package!", - "Generated descriptor content won't accurately reflect descriptor", - "information created by different Tor versions.", sep='\n\t') -try: -import nacl -import nacl.secret -except (ImportError, NameError, IOError): -nacl = secret = None - - -#: The version of this script -__version__ = '0.2.0' - -#: The ... version numbers for tor, taken from the -#: 'server-versions' line of a consensus file -SERVER_VERSIONS = """0.2.2.39,0.2.3.24-rc,0.2.3.25, -0.2.4.5-alpha,0.2.4.6-alpha,0.2.4.7-alpha,0.2.4.8-alpha,0.2.4.9-alpha, -0.2.4.10-alpha,0.2.4.11-alpha,0.2.4.12-alpha,0.2.4.14-alpha,0.2.4.15-rc, -0.2.4.16-rc,0.2.4.17-rc,0.2.5.1-alpha""".replace('\n', '').split(',') - -#: Strings found in PEM-encoded objects created by Tor -TOR_BEGIN_KEY = "-BEGIN RSA PUBLIC KEY-" -TOR_END_KEY = "-END RSA PUBLIC KEY-" -TOR_BEGIN_SK = "-BEGIN RSA PRIVATE KEY-" -TOR_END_SK= "-END RSA PRIVATE KEY-" -TOR_BEGIN_SIG = "-BEGIN SIGNATURE-" -TOR_END_SIG = "-END SIGNATURE-" - -#: Strings found in PEM-encoded objects created by OpenSSL -OPENSSL_BEGIN_KEY = "-BEGIN PRIVATE KEY-" -OPENSSL_END_KEY= "-END PRIVATE KEY-" -OPENSSL_BEGIN_CERT = "-BEGIN CERTIFICATE-" -OPENSSL_END_CERT = "-END CERTIFICATE-" - -PEM = OpenSSL.crypto.FILETYPE_PEM -ASN1 = OpenSSL.crypto.FILETYPE_ASN1 - - -class OpenSSLKeyGenError(Exception): -"""Raised when there is a problem generating a new key.""" - - -def getArgParser(): -"""Get our :class:`~argparse.ArgumentParser`.""" -parser = argparse.ArgumentParser(add_help=True) -parser.version = __version__ -parser.description = "Generate a signed set of network-status, " -parser.description += "extra-info, and server descriptor documents " -parser.description += "for mock Tor relays or bridges." -infoargs = parser.add_mutually_exclusive_group() -verbargs = parser.add_mutually_exclusive_group() -infoargs.add_argument("-v", "--verbose", action="store_true", - help="print information to stdout") -infoargs.add_argument("-q", "--quiet", action="store_true", - help="don't print anything") -verbargs.add_argument("--version", action="store_true", - help="print the %s version and exit".format( - parser.prog)) -group = parser.add_argument_group() -group.title = "required arguments" -group.add_argument("-n", "--descriptors", default=0, - help="generate descriptor sets", type=int) -return parser - -def ran
[tor-commits] [bridgedb/master] Use the class wrapper DummyRequest in unittests in test_HTTPServer.py.
commit 3d6a4ca6f0aaba53785ab935ddc036549e925a7e Author: Isis Lovecruft Date: Wed Mar 19 17:58:48 2014 + Use the class wrapper DummyRequest in unittests in test_HTTPServer.py. --- lib/bridgedb/test/test_HTTPServer.py | 36 +- 1 file changed, 5 insertions(+), 31 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 73297de..cd55b46 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -65,7 +65,7 @@ class CaptchaProtectedResourceTests(unittest.TestCase): """render_GET() should return a page without a CAPTCHA, which has the image alt text. """ -request = requesthelper.DummyRequest([self.pagename]) +request = DummyRequest([self.pagename]) request.method = b'GET' page = self.captchaResource.render_GET(request) self.assertSubstring( @@ -78,7 +78,7 @@ class CaptchaProtectedResourceTests(unittest.TestCase): oldLookup = HTTPServer.lookup try: HTTPServer.lookup = None -request = requesthelper.DummyRequest([self.pagename]) +request = DummyRequest([self.pagename]) request.method = b'GET' page = self.captchaResource.render_GET(request) errorPage = HTTPServer.replaceErrorPage(Exception('kablam')) @@ -104,18 +104,8 @@ class CaptchaProtectedResourceTests(unittest.TestCase): """render_POST() with a wrong 'captcha_response_field' should return a redirect to the CaptchaProtectedResource page. """ -pagename = 'captcha.html' -self.root.putChild(pagename, self.captchaResource) - -def redirect(request): -newRequest = type(request) -newRequest.uri = pagename -return newRequest - -request = requesthelper.DummyRequest(['captcha.html']) +request = DummyRequest([self.pagename]) request.method = b'POST' -request.redirect = redirect(request) - page = self.captchaResource.render_POST(request) self.assertEqual(BeautifulSoup(page).find('meta')['http-equiv'], 'refresh') @@ -149,15 +139,7 @@ class GimpCaptchaProtectedResourceTests(unittest.TestCase): self.root.putChild(self.pagename, self.captchaResource) # Set up the basic parts of our faked request: -self.request = requesthelper.DummyRequest([self.pagename]) -self.request.URLPath = lambda: request.uri # Fake the URLPath too -self.request.redirect = self.doRedirect(self.request) - -def doRedirect(self, request): -"""Stub method to add a redirect() to DummyResponse.""" -newRequest = type(request) -newRequest.uri = self.pagename -return newRequest +self.request = DummyRequest([self.pagename]) def tearDown(self): """Delete the cached CAPTCHA directory if it still exists.""" @@ -283,15 +265,7 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): self.root.putChild(self.pagename, self.captchaResource) # Set up the basic parts of our faked request: -self.request = requesthelper.DummyRequest([self.pagename]) -self.request.URLPath = lambda: request.uri # Fake the URLPath too -self.request.redirect = self.doRedirect(self.request) - -def doRedirect(self, request): -"""Stub method to add a redirect() to DummyResponse.""" -newRequest = type(request) -newRequest.uri = self.pagename -return newRequest +self.request = DummyRequest([self.pagename]) def tearDown(self): """Cleanup method for removing timed out connections on the reactor. ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Merge branch 'fix/11231-blank-captcha-field' into develop
commit 7fdde318ce5446ff55646ccde44f7586d2d411b6 Merge: 18d8d30 a4dd886 Author: Isis Lovecruft Date: Fri Mar 21 22:27:09 2014 + Merge branch 'fix/11231-blank-captcha-field' into develop lib/bridgedb/HTTPServer.py|8 +- lib/bridgedb/test/test_HTTPServer.py | 597 + lib/bridgedb/test/test_txrecaptcha.py | 21 +- 3 files changed, 616 insertions(+), 10 deletions(-) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] More import cleanups for HTTPServer.
commit 1234ed25027bff7936b5bc32d32233970ed2813e Author: Isis Lovecruft Date: Tue Mar 25 22:21:11 2014 + More import cleanups for HTTPServer. * CHANGE `from twisted.web.server import Site` to import the entire `server` module instead. --- lib/bridgedb/HTTPServer.py |4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index c55e668..7e7df98 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -16,9 +16,9 @@ import os from twisted.internet import reactor from twisted.internet.error import CannotListenError -from twisted.web.server import Site from twisted.python import filepath from twisted.web import resource +from twisted.web import server from twisted.web import static from twisted.web.util import redirectTo @@ -789,7 +789,7 @@ def addWebServer(cfg, dist, sched): else: httpdist.putChild('bridges', bridgesResource) -site = Site(httpdist) +site = server.Site(httpdist) if cfg.HTTP_UNENCRYPTED_PORT: ip = cfg.HTTP_UNENCRYPTED_BIND_IP or "" ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] A couple PEP8 whitespace fixes in docstrings for HTTPServer.
commit 30c63975d03dd2ab26c9ecf35fa190d7e732512b Author: Isis Lovecruft Date: Tue Mar 25 22:23:13 2014 + A couple PEP8 whitespace fixes in docstrings for HTTPServer. --- lib/bridgedb/HTTPServer.py |6 ++ 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 7e7df98..26bfb6d 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -206,7 +206,6 @@ class CaptchaProtectedResource(resource.Resource): request. Otherwise, redirect them back to a new CAPTCHA page. :type request: :api:`twisted.web.http.Request` - :param request: A ``Request`` object, including POST arguments which should include two key/value pairs: one key being ``'captcha_challenge_field'``, and the other, @@ -214,7 +213,7 @@ class CaptchaProtectedResource(resource.Resource): obtained from :meth:`render_GET`. :rtype: str :returns: A rendered HTML page containing a ReCaptcha challenge image - for the client to solve. +for the client to solve. """ if self.checkSolution(request) is True: try: @@ -451,7 +450,7 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): :param request: A ``Request`` object for 'bridges.html'. :rtype: str :returns: A rendered HTML page containing a ReCaptcha challenge image - for the client to solve. +for the client to solve. """ return CaptchaProtectedResource.render_GET(self, request) @@ -463,7 +462,6 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): request. Otherwise, redirect them back to a new CAPTCHA page. :type request: :api:`twisted.web.http.Request` - :param request: A ``Request`` object, including POST arguments which should include two key/value pairs: one key being ``'captcha_challenge_field'``, and the other, ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Remove `cat bridgedb.log` from after tests in .travis.yml.
commit 80a133156db63aff278470f9c9ea3e95473c6f2a Author: Isis Lovecruft Date: Tue Mar 25 03:04:37 2014 + Remove `cat bridgedb.log` from after tests in .travis.yml. --- .travis.yml |1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 902c3b4..5553a81 100644 --- a/.travis.yml +++ b/.travis.yml @@ -37,4 +37,3 @@ script: after_success: - coveralls - - cat bridgedb.log ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add unittests for HTTPServer.WebResourceBridges.
commit a4dd886c34ce6f1c30d752d68f42dd8eefd260fc Author: Isis Lovecruft Date: Wed Mar 19 18:08:26 2014 + Add unittests for HTTPServer.WebResourceBridges. --- lib/bridgedb/test/test_HTTPServer.py | 136 ++ 1 file changed, 136 insertions(+) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 9b5a6e4..9f241d9 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -28,6 +28,7 @@ from twisted.web.resource import Resource from twisted.web.test import requesthelper from bridgedb import HTTPServer +from bridgedb.Time import IntervalSchedule # For additional logger output for debugging, comment out the following: @@ -459,3 +460,138 @@ class DummyRequest(requesthelper.DummyRequest): newRequest = type(request) newRequest.uri = request.uri return newRequest + + +class WebResourceBridgesTests(unittest.TestCase): +"""Tests for :class:`HTTPServer.WebResourceBridges`.""" + +def setUp(self): +"""Set up our resources to fake a minimal HTTP(S) server.""" +self.pagename = b'bridges.html' +self.root = Resource() + +self.dist = DummyIPBasedDistributor() +self.sched = IntervalSchedule('hour', 1) +self.nBridgesPerRequest = 2 +self.bridgesResource = HTTPServer.WebResourceBridges( +self.dist, self.sched, N=2, +#useForwardedHeader=True, +includeFingerprints=True) + +self.root.putChild(self.pagename, self.bridgesResource) + +def parseBridgesFromHTMLPage(self, page): +"""Utility to pull the bridge lines out of an HTML response page. + +:param str page: A rendered HTML page, as a string. +:raises: Any error which might occur. +:rtype: list +:returns: A list of the bridge lines contained on the **page**. +""" +# The bridge lines are contained in a tag: +soup = BeautifulSoup(page).find('pre') +soup = str(soup).replace('', '').strip() +soup = str(soup).replace('', '').strip() +bridges = [b.strip() for b in soup.splitlines()] +return bridges + +def test_render_GET_vanilla(self): +"""Test rendering a request for normal, vanilla bridges.""" +request = DummyRequest([self.pagename]) +request.method = b'GET' +request.getClientIP = lambda: '1.1.1.1' + +page = self.bridgesResource.render(request) + +# The response should explain how to use the bridge lines: +self.assertSubstring("To use the above lines", page) + +for b in self.parseBridgesFromHTMLPage(page): +# Check that each bridge line had the expected number of fields: +fields = b.split(' ') +self.assertEqual(len(fields), 2) + +# Check that the IP and port seem okay: +ip, port = fields[0].rsplit(':') +self.assertIsInstance(ipaddr.IPv4Address(ip), ipaddr.IPv4Address) +self.assertIsInstance(int(port), int) +self.assertGreater(int(port), 0) +self.assertLessEqual(int(port), 65535) + +def test_render_GET_XForwardedFor(self): +"""The client's IP address should be obtainable from the +'X-Forwarded-For' header in the request. +""" +self.bridgesResource.useForwardedHeader = True +request = DummyRequest([self.pagename]) +request.method = b'GET' +# Since we do not set ``request.getClientIP`` here like we do in some +# of the other unittests, an exception would be raised here if +# ``getBridgesForRequest()`` is unable to get the IP address from this +# 'X-Forwarded-For' header (because ``ip`` would get set to ``None``). +request.headers.update({'x-forwarded-for': '2.2.2.2'}) + +page = self.bridgesResource.render(request) +self.bridgesResource.useForwardedHeader = False # Reset it +self.assertSubstring("To use the above lines", page) + +def test_render_GET_RTLlang(self): +"""Test rendering a request for obfs3 bridges in Arabic.""" +request = DummyRequest(["bridges?transport=obfs3"]) +request.method = b'GET' +request.getClientIP = lambda: '3.3.3.3' +request.headers.update({'accept-language': 'ar'}) +# We actually have to set the request args manually when using a +# DummyRequest: +request.args.update({'transport': 'obfs3'}) + +page = self.bridgesResource.render(request) +self.assertSubstring("direction: rtl", page) +self.assertSubstring("Ùاستخدا٠اÙأسطر أعÙاÙ", page) + +for bridgeLine in self.parseBridgesFromHTMLPage(page): +# Check that each bridge line had the expected number of fields: +bridgeLine = bridgeLine.split(' ') +self.assertEqual(len(bridgeLine), 3) + +print(""" +
[tor-commits] [bridgedb/master] Remove superfluous descriptor generation.
commit 3f3ead057007b2dceb0575267b1784c61241f110 Author: Isis Lovecruft Date: Mon Mar 24 03:14:04 2014 + Remove superfluous descriptor generation. --- .travis.yml |3 --- 1 file changed, 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9858edf..8d8bfcf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,9 +31,6 @@ install: - pip install coverage==3.7 coveralls==0.3 sure==1.2.2 --use-mirrors - make install -before_script: - - bridgedb mock -n 250 - script: - coverage run $(which trial) ./lib/bridgedb/test/test_*.py - coverage report ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Fix txrecaptcha.submit() to always return Deferreds.
commit b4f88aded4fd6cc60be0129e1b6d0bd708d392c7 Author: Isis Lovecruft Date: Wed Mar 19 18:30:12 2014 + Fix txrecaptcha.submit() to always return Deferreds. All returned Deferreds callback with RecaptchaResponse objects. This way, we do not need additional code to check if the result was a Deferred (because, in that case, we would need to add a callback function to extract the RecaptchaResponse object from it and check it), or if it directly returned a RecaptchaResponse. This function now *always* returns Deferred. --- lib/bridgedb/txrecaptcha.py | 12 ++-- 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/bridgedb/txrecaptcha.py b/lib/bridgedb/txrecaptcha.py index e1e3234..2185112 100644 --- a/lib/bridgedb/txrecaptcha.py +++ b/lib/bridgedb/txrecaptcha.py @@ -213,12 +213,12 @@ def submit(recaptcha_challenge_field, recaptcha_response_field, :returns: A :api:`~twisted.internet.defer.Deferred` which will callback with a ``recaptcha.RecaptchaResponse`` for the request. """ -if not (recaptcha_response_field and -recaptcha_challenge_field and -len(recaptcha_response_field) and -len(recaptcha_challenge_field)): -return RecaptchaResponse(is_valid=False, - error_code='incorrect-captcha-sol') +if not (recaptcha_response_field and len(recaptcha_response_field) and +recaptcha_challenge_field and len(recaptcha_challenge_field)): +d = defer.Deferred() +d.addBoth(_ebRequest) # We want `is_valid=False` +d.errback(failure.Failure(ValueError('incorrect-captcha-sol'))) +return d params = urllib.urlencode({ 'privatekey': _encodeIfNecessary(private_key), ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add a docstring and comment to checkResponse() in ReCaptchaProtectedResource.
commit 228d7e0856cb88723531cb76db12c3a9b32acd5a Author: Isis Lovecruft Date: Wed Mar 26 04:57:56 2014 + Add a docstring and comment to checkResponse() in ReCaptchaProtectedResource. --- lib/bridgedb/HTTPServer.py | 11 +++ 1 file changed, 11 insertions(+) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index f4ab592..24a970f 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -466,6 +466,17 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): % (Util.logSafely(clientIP), request.args)) def checkResponse(solution, request): +"""Check the :class:`txrecaptcha.RecaptchaResponse`. + +:type solution: :class:`txrecaptcha.RecaptchaResponse`. +:param solution: The client's CAPTCHA solution, after it has been +submitted to the reCaptcha API server. +""" +# This valid CAPTCHA result from this function cannot be reliably +# unittested, because it's callbacked to from the deferred +# returned by ``txrecaptcha.submit``, the latter of which would +# require networking (as well as automated CAPTCHA +# breaking). Hence, the 'no cover' pragma. if solution.is_valid: # pragma: no cover logging.info("Valid CAPTCHA solution from %r." % Util.logSafely(clientIP)) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Change ReCaptchaProtectedResource.checkResponse() to also return request.
commit 1bc823d54b507438972b53cc6774de7c6d626ab4 Author: Isis Lovecruft Date: Tue Mar 25 22:24:10 2014 + Change ReCaptchaProtectedResource.checkResponse() to also return request. We need to return the original request, not just the boolean representing the validity of the CAPTCHA solution, if we want to be able to interact with the original request while rendering it. --- lib/bridgedb/HTTPServer.py | 15 +-- 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 26bfb6d..e2f1059 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -419,8 +419,11 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): ``'captcha_challenge_field'``, and the other, ``'captcha_response_field'``. These POST arguments should be obtained from :meth:`render_GET`. -:rtupe: bool -:returns: True, if the CAPTCHA solution was valid; False otherwise. +:rtupe: :api:`twisted.internet.defer.Deferred` +:returns: the returned deferred will callback with a tuple of +(``bool``, :api:`twisted.web.server.Request`). If the CAPTCHA +solution was valid, a tuple will contain ``(True, request)``; +otherwise, it will contain ``(False, request)``. """ challenge, response = self.extractClientSolution(request) clientIP = self.getClientIP(request) @@ -429,18 +432,18 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): logging.debug("Captcha from %r. Parameters: %r" % (Util.logSafely(clientIP), request.args)) -def checkResponse(solution, clientIP): +def checkResponse(solution, request): if solution.is_valid: logging.info("Valid CAPTCHA solution from %r." % Util.logSafely(clientIP)) -return True +return (True, request) else: logging.info("Invalid CAPTCHA solution from %r: %r" % (Util.logSafely(clientIP), solution.error_code)) -return False +return (False, request) d = txrecaptcha.submit(challenge, response, self.recaptchaPrivKey, - remoteIP).addCallback(checkResponse, clientIP) + remoteIP).addCallback(checkResponse, request) return d def render_GET(self, request): ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add leekspin dependency; modify test_bridgedb and bridgedb.runner apropos.
commit 6d991ba844be61f944b13ca4a7077c03464406a0 Author: Isis Lovecruft Date: Mon Mar 24 03:12:52 2014 + Add leekspin dependency; modify test_bridgedb and bridgedb.runner apropos. --- .travis.yml|4 ++-- lib/bridgedb/runner.py |2 +- lib/bridgedb/test/test_bridgedb.py | 12 +--- setup.py |8 4 files changed, 16 insertions(+), 10 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8d8bfcf..902c3b4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,8 +27,8 @@ python: - "2.7" install: - - pip install -r requirements.txt --use-mirrors - - pip install coverage==3.7 coveralls==0.3 sure==1.2.2 --use-mirrors + - pip install -r requirements.txt + - pip install --no-use-wheel leekspin==0.1.1 coverage==3.7 coveralls==0.3 sure==1.2.2 - make install script: diff --git a/lib/bridgedb/runner.py b/lib/bridgedb/runner.py index 8c641f6..d067bd9 100644 --- a/lib/bridgedb/runner.py +++ b/lib/bridgedb/runner.py @@ -45,7 +45,7 @@ def generateDescriptors(count=None, rundir=None): proc = None statuscode = 0 -script = 'gen_bridge_descriptors' +script = 'leekspin' rundir = rundir if os.path.isdir(rundir) else None count = count if count else 3 try: diff --git a/lib/bridgedb/test/test_bridgedb.py b/lib/bridgedb/test/test_bridgedb.py index 3d21080..5dc890d 100644 --- a/lib/bridgedb/test/test_bridgedb.py +++ b/lib/bridgedb/test/test_bridgedb.py @@ -75,12 +75,18 @@ class BridgeDBCliTest(unittest.TestCase): bridgedbScript = bridgedbScript[0] print("Running bridgedb script %r..." % bridgedbScript) +os.chdir(runDir) # we have to do this to get files to end up there print("Running `bridgedb mock' to generate mock bridge descriptors...") -mockProc = Popen([bridgedbScript, 'mock', - '-n', '50', - '-r', runDir]) +mockProc = Popen([bridgedbScript, 'mock', '-n', '50']) mockProcCode = mockProc.wait() print("`bridgedb mock' exited with status code %d" % int(mockProcCode)) +os.chdir(here) + +# See ticket #11216, cached-extrainfo* files should not be parsed +# cumulatively. +eidesc = pjoin(runDir, 'cached-extrainfo') +eindesc = pjoin(runDir, 'cached-extrainfo.new') +self.doCopyFile(eindesc, eidesc, 'duplicated cached-extrainfo(.new)') print("Running `bridgedb' to test server startups...") bridgedbProc = Popen([bridgedbScript, '-r', runDir]) diff --git a/setup.py b/setup.py index 5ec2d79..d859f87 100644 --- a/setup.py +++ b/setup.py @@ -274,10 +274,10 @@ setuptools.setup( packages=['bridgedb', 'bridgedb.parse', 'bridgedb.test'], -scripts=['scripts/bridgedb', - 'scripts/gen_bridge_descriptors'], -extras_require={'test': ["sure==0.4.5", - "coverage==3.6"]}, +scripts=['scripts/bridgedb'], +extras_require={'test': ["sure==1.2.2", + "coverage==3.7", + "leekspin==0.1.1"]}, zip_safe=False, cmdclass=get_cmdclass(), include_package_data=True, ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Merge branch 'fix/11219-httpconnpool' into develop
commit 984ea10c316d1ce4dbd38339f3157a4f9e5c1190 Merge: f523014 bd50039 Author: Isis Lovecruft Date: Mon Mar 17 01:48:32 2014 + Merge branch 'fix/11219-httpconnpool' into develop lib/bridgedb/txrecaptcha.py | 40 +--- 1 file changed, 29 insertions(+), 11 deletions(-) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Make webserver Tor logo link to torproject.org.
commit bc0f1d1b72a2e34277209ce97b2cbc6ce4d1b103 Author: Isis Lovecruft Date: Mon Mar 17 05:14:09 2014 + Make webserver Tor logo link to torproject.org. --- lib/bridgedb/templates/base.html |3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/bridgedb/templates/base.html b/lib/bridgedb/templates/base.html index 441f3b6..55044e6 100644 --- a/lib/bridgedb/templates/base.html +++ b/lib/bridgedb/templates/base.html @@ -34,7 +34,8 @@ span { BridgeDB - + https://www.torproject.org";> ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add optional debugging logs to test_HTTPServer.py.
commit 619d0a588f0c0fe6cd9a2d1a812258c8042acb30 Author: Isis Lovecruft Date: Wed Mar 19 17:43:28 2014 + Add optional debugging logs to test_HTTPServer.py. --- lib/bridgedb/test/test_HTTPServer.py |6 +- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index da910c6..e0c81f8 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -11,6 +11,7 @@ """Unittests for :mod:`bridgedb.HTTPServer`.""" +import logging import os import shutil @@ -25,8 +26,11 @@ from twisted.web.test import requesthelper from bridgedb import HTTPServer -import logging + +# For additional logger output for debugging, comment out the following: logging.disable(50) +# and then uncomment the following line: +#HTTPServer.logging.getLogger().setLevel(10) class ReplaceErrorPageTests(unittest.TestCase): ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Merge branch 'master' into develop
commit d40b410899b3a5f071ba7f750f2db481800a181f Merge: ac9aa95 783babc Author: Isis Lovecruft Date: Sun Mar 16 19:02:28 2014 + Merge branch 'master' into develop ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Rearrange logging calls during pygeoip import in HTTPServer.py.
commit e2044209095f1a00ae65c998dc93f64796dd9e6e Author: Isis Lovecruft Date: Mon Mar 17 22:56:51 2014 + Rearrange logging calls during pygeoip import in HTTPServer.py. --- lib/bridgedb/HTTPServer.py |6 ++ 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 2744193..96ee029 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -72,12 +72,10 @@ try: # geoip-database packages. import pygeoip geoip = pygeoip.GeoIP(_geoipdb, flags=pygeoip.MEMORY_CACHE) +logging.info("GeoIP database loaded") except Exception as err: -logging.debug("Error while loading geoip module: %r" % err) -logging.warn("GeoIP database not found") +logging.warn("Error while loading geoip module: %r" % err) geoip = None -else: -logging.info("GeoIP database loaded") def replaceErrorPage(error, template_name=None): ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Tweak the log message strings in EmailServer.replyToMail().
commit 5e40f67141201aa9f5561319b32069c130899160 Author: Isis Lovecruft Date: Mon Mar 17 03:01:14 2014 + Tweak the log message strings in EmailServer.replyToMail(). --- lib/bridgedb/EmailServer.py |9 ++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/bridgedb/EmailServer.py b/lib/bridgedb/EmailServer.py index d442ccd..8fb0d8a 100644 --- a/lib/bridgedb/EmailServer.py +++ b/lib/bridgedb/EmailServer.py @@ -249,12 +249,15 @@ def replyToMail(lines, ctx): :type ctx: :class:`MailContext` :param ctx: The configured context for the email server. """ -logging.info("Got a completed email; deciding whether to reply.") +logging.info("Got an email; deciding whether to reply.") sendToUser, response = getMailResponse(lines, ctx) if response is None: -logging.debug("getMailResponse said not to reply, so I won't.") +logging.debug("getMailResponse() said not to reply to %s, so I won't." + % Util.logSafely(sendToUser)) return response.seek(0) +logging.info("Sending reply to %r", Util.logSafely(sendToUser)) + d = Deferred() factory = twisted.mail.smtp.SMTPSenderFactory( ctx.smtpFromAddr, @@ -262,7 +265,7 @@ def replyToMail(lines, ctx): response, d) reactor.connectTCP(ctx.smtpServer, ctx.smtpPort, factory) -logging.info("Sending reply to %r", Util.logSafely(sendToUser)) + return d def getLocaleFromPlusAddr(address): ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add CHANGELOG entry for 0.1.6.
commit d808f7a6de915cbb9a77f04fa6207d388225413a Author: Isis Lovecruft Date: Mon Mar 17 02:04:59 2014 + Add CHANGELOG entry for 0.1.6. --- CHANGELOG |8 1 file changed, 8 insertions(+) diff --git a/CHANGELOG b/CHANGELOG index b8c9d71..bf895ad 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,11 @@ +Changes in version 0.1.6 - 2014-03-17 +BridgeDB 0.1.6 includes fixes for the following bugs: + * FIXES #11218 ReCaptchaProtectedResource.checkSolution() + doesn't expect a deferred + * FIXES #11219 BridgeDB's twisted version doesn´t have a + `t.w.client.HTTPConnectionPool` class + + Changes in version 0.1.5 - 2014-02-27 BridgeDB 0.1.5 includes fixes for the following bugs: * FIXES #9264 Problem with transport lines in BridgeDB's bridge ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add a mocked DummyIPBasedDistributor class to test_HTTPServer.py.
commit 6fcf0121296067f7e47721af315ca5b85021e8b8 Author: Isis Lovecruft Date: Wed Mar 19 17:56:26 2014 + Add a mocked DummyIPBasedDistributor class to test_HTTPServer.py. A distributor is a required parameter to the `HTTPServer.WebResourceBridges` class. This one merely creates N random `DummyBridges`, where N is the number of bridges we're told to return to the client. --- lib/bridgedb/test/test_HTTPServer.py | 27 +++ 1 file changed, 27 insertions(+) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 05e041c..e2856c7 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -418,3 +418,30 @@ class DummyBridge(object): bridgeLine = " ".join([item for item in line]) #print "Created config line: %r" % bridgeLine return bridgeLine + + +class DummyIPBasedDistributor(object): +"""A mocked :class:`bridgedb.Dist.IPBasedDistributor` which is used to test +:class:`bridgedb.HTTPServer.WebResourceBridges. +""" + +def _dumbAreaMapper(ip): return ip + +def __init__(self, areaMapper=None, nClusters=None, key=None, + ipCategories=None, answerParameters=None): +"""None of the parameters are really used, they are just there to retain +an identical method signature. +""" +self.areaMapper = self._dumbAreaMapper +self.nClusters = 3 +self.nBridgesToGive = 3 +self.key = self.__class__.__name__ +self.ipCategories = ipCategories +self.answerParameters = answerParameters + +def getBridgesForIP(self, ip=None, epoch=None, N=1, +countyCode=None, bridgeFilterRules=None): +"""Needed because it's called in +:meth:`WebResourceBridges.getBridgesForIP`. +""" +return [DummyBridge() for _ in xrange(N)] ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Update translations.
commit 43b069d31f32e2596bc4ce014f8b8fb214714059 Author: Isis Lovecruft Date: Wed Mar 26 05:27:58 2014 + Update translations. --- lib/bridgedb/i18n/ca/LC_MESSAGES/bridgedb.po| 102 ++ lib/bridgedb/i18n/cs/LC_MESSAGES/bridgedb.po| 104 +++ lib/bridgedb/i18n/es_CL/LC_MESSAGES/bridgedb.po | 101 ++ lib/bridgedb/i18n/fi/LC_MESSAGES/bridgedb.po| 102 ++ lib/bridgedb/i18n/fr_CA/LC_MESSAGES/bridgedb.po | 104 +++ lib/bridgedb/i18n/id/LC_MESSAGES/bridgedb.po| 101 ++ lib/bridgedb/i18n/km/LC_MESSAGES/bridgedb.po| 102 ++ lib/bridgedb/i18n/mk/LC_MESSAGES/bridgedb.po| 101 ++ lib/bridgedb/i18n/pt/LC_MESSAGES/bridgedb.po| 102 ++ lib/bridgedb/i18n/th/LC_MESSAGES/bridgedb.po|2 +- lib/bridgedb/i18n/uk/LC_MESSAGES/bridgedb.po| 102 ++ lib/bridgedb/i18n/zh_TW/LC_MESSAGES/bridgedb.po | 100 ++ 12 files changed, 1122 insertions(+), 1 deletion(-) diff --git a/lib/bridgedb/i18n/ca/LC_MESSAGES/bridgedb.po b/lib/bridgedb/i18n/ca/LC_MESSAGES/bridgedb.po new file mode 100644 index 000..ee74f59 --- /dev/null +++ b/lib/bridgedb/i18n/ca/LC_MESSAGES/bridgedb.po @@ -0,0 +1,102 @@ +# Translations template for BridgeDB. +# Copyright (C) 2013 ORGANIZATION +# This file is distributed under the same license as the BridgeDB project. +# +# Translators: +# Translators: +# Illenc , 2013 +# Toni Hermoso Pulido , 2012 +msgid "" +msgstr "" +"Project-Id-Version: The Tor Project\n" +"Report-Msgid-Bugs-To: https://trac.torproject.org/projects/tor\n"; +"POT-Creation-Date: 2013-03-27 21:41+\n" +"PO-Revision-Date: 2013-10-27 08:40+\n" +"Last-Translator: Illenc \n" +"Language-Team: Catalan (http://www.transifex.com/projects/p/torproject/language/ca/)\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" +"Generated-By: Babel 0.9.6\n" +"Language: ca\n" +"Plural-Forms: nplurals=2; plural=(n != 1);\n" + +#: lib/bridgedb/templates/base.html:33 +msgid "What are bridges?" +msgstr "Què són els ponts?" + +#: lib/bridgedb/templates/base.html:34 +#, python-format +msgid "" +"%s Bridge relays %s are Tor relays that help you circumvent censorship." +msgstr "%s mecanismes Pont %s són mecanismes Tor per esquivar la censura." + +#: lib/bridgedb/templates/base.html:39 +msgid "I need an alternative way of getting bridges!" +msgstr "Necessit una manera alternativa d'obtenir ponts" + +#: lib/bridgedb/templates/base.html:40 +#, python-format +msgid "" +"Another way to find public bridge addresses is to send an email (from a %s " +"or a %s address) to %s with the line 'get bridges' by itself in the body of " +"the mail." +msgstr "Una altra manera de trobar adreces de ponts públics és enviant un correu (de %s o %s address) a %s amb el text 'get bridges' al cos del correu." + +#: lib/bridgedb/templates/base.html:48 +msgid "My bridges don't work! I need help!" +msgstr "No em funcionen els ponts! Ajuda!" + +#: lib/bridgedb/templates/base.html:49 +#, python-format +msgid "" +"If your Tor doesn't work, you should email %s. Try including as much info " +"about your case as you can, including the list of bridges you used, the " +"bundle filename/version you used, the messages that Tor gave out, etc." +msgstr "Si no us funciona Tor, envieu un correu %s. Hi heu d'incloure el mà xim d'informació sobre el vostre cas: amb la llista de ponts que teniu, la versió, el missatge que Tor us dóna, etc." + +#: lib/bridgedb/templates/bridges.html:10 +msgid "" +"To use the above lines, go to Vidalia's Network settings page, and click " +"\"My ISP blocks connections to the Tor network\". Then add each bridge " +"address one at a time." +msgstr "Per a usar l'anterior lÃnia, aneu a la configuració de Xarxa Vidalia, clicau a \"El meu proveïdor bloca les connexions Tor\" Després afegiu les adreces de pont una per una." + +#: lib/bridgedb/templates/bridges.html:13 +msgid "No bridges currently available" +msgstr "No hi ha ponts disponibles" + +#: lib/bridgedb/templates/captcha.html:6 +msgid "Upgrade your browser to Firefox" +msgstr "Actualitza el navegador a Firefox" + +#: lib/bridgedb/templates/captcha.html:8 +msgid "Type the two words" +msgstr "Escriviu les dues paraules" + +#: lib/bridgedb/templates/index.html:6 +msgid "Step 1" +msgstr "Passa 1" + +#: lib/bridgedb/templates/index.html:8 +#, python-format +msgid "Get %s Tor Browser Bundle %s" +msgstr "Descarrega %s el navegador Tor Bundle %s" + +#: lib/bridgedb/templates/index.html:13 +msgid "Step 2" +msgstr "Passa 2" + +#: lib/bridgedb/templates/index.html:15 +#, python-format +msgid "Get %s bridges %s" +msgstr "Descarrega %s ponts %s" + +#: lib/bridgedb/templates/index.html:19 +msgid "Step 3" +msgstr "Passa 3" + +#: lib/bridgedb/templates/index.html:21 +#, python-format +msgid "Now %
[tor-commits] [bridgedb/master] Always expect a Deferred from ReCaptcha.checkSolution().
commit 738101ac291235cc1415f4db5c9c023b6521e34f Author: Isis Lovecruft Date: Wed Mar 19 18:03:15 2014 + Always expect a Deferred from ReCaptcha.checkSolution(). Currently, we `checkSolution()` will return a RecaptchaResponse if the HTTP POST argument fields are blank. Otherwise, it returns a deferred. This is bad. It means we have to do all kinds of checks to see if we can add callbacks on the returned object. It should always return a deferred which callbacks with a RecaptchaResponse, and so we should test for that and fail if that is not what is happening. --- lib/bridgedb/test/test_HTTPServer.py |6 +++--- lib/bridgedb/test/test_txrecaptcha.py | 21 +++-- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 507b1f0..9b5a6e4 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -309,9 +309,9 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): self.request.addArg('captcha_challenge_field', '') self.request.addArg('captcha_response_field', '') -self.assertIsInstance( -self.captchaResource.checkSolution(self.request), -HTTPServer.txrecaptcha.RecaptchaResponse) +self.assertIs(False, + self.successResultOf( + self.captchaResource.checkSolution(self.request))) def test_getRemoteIP_useRandomIP(self): """Check that removing our remoteip setting produces a random IP.""" diff --git a/lib/bridgedb/test/test_txrecaptcha.py b/lib/bridgedb/test/test_txrecaptcha.py index c7dcbb1..81484dc 100644 --- a/lib/bridgedb/test/test_txrecaptcha.py +++ b/lib/bridgedb/test/test_txrecaptcha.py @@ -181,12 +181,21 @@ class SubmitTests(unittest.TestCase): self.ip = "1.2.3.4" def test_submit_emptyResponseField(self): -"""An empty 'recaptcha_response_field' should immediately return a -RecaptchaResponse whose error_code is 'incorrect-captcha-sol'.""" -response = txrecaptcha.submit(self.challenge, '', self.key, self.ip) -self.assertIsInstance(response, txrecaptcha.RecaptchaResponse) -self.assertIs(response.is_valid, False) -self.assertEqual(response.error_code, 'incorrect-captcha-sol') +"""An empty 'recaptcha_response_field' should return a deferred which +callbacks with a RecaptchaResponse whose error_code is +'incorrect-captcha-sol'. +""" +def checkResponse(response): +"""Check that the response is a +:class:`txcaptcha.RecaptchaResponse`. +""" +self.assertIsInstance(response, txrecaptcha.RecaptchaResponse) +self.assertIs(response.is_valid, False) +self.assertEqual(response.error_code, 'incorrect-captcha-sol') + +d = txrecaptcha.submit(self.challenge, '', self.key, self.ip) +d.addCallback(checkResponse) +return d def test_submit_returnsDeferred(self): """:func:`txrecaptcha.submit` should return a deferred.""" ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Fix class and __init__ docstrings for EmailBasedDistributor.
commit ce8604c52f4b9f1488a9676794116addccb0b78a Author: Isis Lovecruft Date: Mon Mar 17 03:04:19 2014 + Fix class and __init__ docstrings for EmailBasedDistributor. --- lib/bridgedb/Dist.py | 24 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/lib/bridgedb/Dist.py b/lib/bridgedb/Dist.py index 9d3b06e..dddc84b 100644 --- a/lib/bridgedb/Dist.py +++ b/lib/bridgedb/Dist.py @@ -413,17 +413,25 @@ def normalizeEmail(addr, domainmap, domainrules): class EmailBasedDistributor(Distributor): """Object that hands out bridges based on the email address of an incoming - request and the current time period. +request and the current time period. + +:type splitter: :class:`~bridgedb.Bridges.BridgeRing` +:ivar splitter: A hashring to hold all the bridges we hand out. """ -## Fields: -## emailHmac -- an hmac function used to order email addresses within -## a ring. -## ring -- a BridgeRing object to hold all the bridges we hand out. -## store -- a database object to remember what we've given to whom. -## domainmap -- a map from lowercase domains that we support mail from -## to their canonical forms. + def __init__(self, key, domainmap, domainrules, answerParameters=None): +"""Create a bridge distributor which uses email. + +:type emailHmac: callable +:param emailHmac: An hmac function used to order email addresses +within a ring. See :func:`~bridgedb.crypto.getHMACFunc`. +:param dict domainmap: A map from lowercase domains that we support +mail from to their canonical forms. See `EMAIL_DOMAIN_MAP` option +in `bridgedb.conf`. +:param domainrules: DOCDOC +:param answerParameters: DOCDOC +""" key1 = getHMAC(key, "Map-Addresses-To-Ring") self.emailHmac = getHMACFunc(key1, hex=False) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Explicitly require CaptchaProtectedResource.checkSolution() to be True.
commit acf37dc00b4d9e2b8e3619a56f1711bb503d9e5b Author: Isis Lovecruft Date: Tue Mar 18 04:50:04 2014 + Explicitly require CaptchaProtectedResource.checkSolution() to be True. * FIXES #11231. --- lib/bridgedb/HTTPServer.py |2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 47009df..27dd61e 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -215,7 +215,7 @@ class CaptchaProtectedResource(twisted.web.resource.Resource): :returns: A rendered HTML page containing a ReCaptcha challenge image for the client to solve. """ -if self.checkSolution(request): +if self.checkSolution(request) is True: try: rendered = self.resource.render(request) except Exception as err: ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Update bridgedb.conf with changes from bridgedb-admin.git repo.
commit bd1b9cafe102fc6a12aa420ce3b3cb37f53c8ad0 Author: Isis Lovecruft Date: Mon Mar 17 01:59:46 2014 + Update bridgedb.conf with changes from bridgedb-admin.git repo. --- bridgedb.conf |7 ++- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/bridgedb.conf b/bridgedb.conf index 0607533..1eb3037 100644 --- a/bridgedb.conf +++ b/bridgedb.conf @@ -23,6 +23,7 @@ # Changes in version 0.0.5 - 2014-02-27 # * ADD GIMP_CAPTCHA_ENABLED, GIMP_CAPTCHA_DIR, GIMP_CAPTCHA_HMAC_KEYFILE, # and GIMP_CAPTCHA_RSA_KEYFILE settings (see #10809). +# * Decrease email share. # # Changes in version 0.0.4 - 2014-01-24 # * ADD COLLECT_TIMESTAMPS option (see #10724). Set it to False for the @@ -64,10 +65,6 @@ # can read it. #-- -# We chdir to this directory when we start; all files with relative pathnames -# are created under this directory -#RUN_IN_DIR = "/srv/bridges.torproject.org/run" - # List of filenames from which we read ``@type bridge-server-descriptor``s, on # startup and on SIGHUP. BRIDGE_FILES = ["bridge-descriptors"] @@ -329,7 +326,7 @@ EMAIL_GPG_SIGNING_KEY = 'gnupghome/TESTING.subkeys.sec' HTTPS_SHARE = 10 # The proportion of bridges to allocate to Email distribution. -EMAIL_SHARE = 10 +EMAIL_SHARE = 5 # An integer specifying the proportion of bridges which should remain # unallocated, for backup usage and manual distribution. ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Change Contact link on webserver to go to support desk.
commit 2912ffc17f262cedb37452effee59eb48c31fdd8 Author: Isis Lovecruft Date: Mon Mar 17 05:15:55 2014 + Change Contact link on webserver to go to support desk. --- lib/bridgedb/templates/base.html |2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/bridgedb/templates/base.html b/lib/bridgedb/templates/base.html index 4eea5a5..228078e 100644 --- a/lib/bridgedb/templates/base.html +++ b/lib/bridgedb/templates/base.html @@ -112,7 +112,7 @@ ${self.body()} · https://gitweb.torproject.org/bridgedb.git";>${_("Source Code")} · -mailto:i...@torproject.org";>${_("Contact")} +mailto:h...@rt.torproject.org";>${_("Contact")} ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] PEP8 whitespace fixes for EmailServer.replyToMail().
commit cae8198956404771b3467581a5db5758df89ce59 Author: Isis Lovecruft Date: Mon Mar 17 03:02:24 2014 + PEP8 whitespace fixes for EmailServer.replyToMail(). --- lib/bridgedb/EmailServer.py |9 - 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/bridgedb/EmailServer.py b/lib/bridgedb/EmailServer.py index 8fb0d8a..79239c7 100644 --- a/lib/bridgedb/EmailServer.py +++ b/lib/bridgedb/EmailServer.py @@ -251,19 +251,18 @@ def replyToMail(lines, ctx): """ logging.info("Got an email; deciding whether to reply.") sendToUser, response = getMailResponse(lines, ctx) + if response is None: logging.debug("getMailResponse() said not to reply to %s, so I won't." % Util.logSafely(sendToUser)) return + response.seek(0) logging.info("Sending reply to %r", Util.logSafely(sendToUser)) d = Deferred() -factory = twisted.mail.smtp.SMTPSenderFactory( -ctx.smtpFromAddr, -sendToUser, -response, -d) +factory = twisted.mail.smtp.SMTPSenderFactory(ctx.smtpFromAddr, sendToUser, + response, d) reactor.connectTCP(ctx.smtpServer, ctx.smtpPort, factory) return d ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Change the requested pagename in CaptchaProtectedResourceTests unittests.
commit 25eb893487855f7449610c60895b7bd79f6458e3 Author: Isis Lovecruft Date: Wed Mar 19 17:44:36 2014 + Change the requested pagename in CaptchaProtectedResourceTests unittests. --- lib/bridgedb/test/test_HTTPServer.py |2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index e0c81f8..119d2fc 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -50,7 +50,7 @@ class CaptchaProtectedResourceTests(unittest.TestCase): def setUp(self): self.dist = None self.sched = None -self.pagename = b'somepage.html' +self.pagename = b'bridges.html' self.root = Resource() self.protectedResource = HTTPServer.WebResourceBridges(self.dist, self.sched) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Fix ReCaptchaProtectedResource.checkSolution() to pull response from deferred.
commit 45876ea43d4aa570d5801aed244d753624af9543 Author: Isis Lovecruft Date: Mon Mar 17 00:05:34 2014 + Fix ReCaptchaProtectedResource.checkSolution() to pull response from deferred. * FIXES a bug introduced in #11127 where checkSolution() was expecting the boolean response from the reCaptcha API server, not a deferred as is now returned. --- lib/bridgedb/HTTPServer.py | 25 +++-- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 49700c5..e9abc78 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -424,19 +424,24 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): challenge, response = self.extractClientSolution(request) clientIP = self.getClientIP(request) remoteIP = self.getRemoteIP() -solution = txrecaptcha.submit(challenge, response, - self.recaptchaPrivKey, remoteIP) + logging.debug("Captcha from %r. Parameters: %r" % (Util.logSafely(clientIP), request.args)) -if solution.is_valid: -logging.info("Valid CAPTCHA solution from %r." - % Util.logSafely(clientIP)) -return True -else: -logging.info("Invalid CAPTCHA solution from %r: %r" - % (Util.logSafely(clientIP), solution.error_code)) -return False + +def checkResponse(solution, clientIP): +if solution.is_valid: +logging.info("Valid CAPTCHA solution from %r." + % Util.logSafely(clientIP)) +return True +else: +logging.info("Invalid CAPTCHA solution from %r: %r" + % (Util.logSafely(clientIP), solution.error_code)) +return False + +d = txrecaptcha.submit(challenge, response, self.recaptchaPrivKey, + remoteIP).addCallback(checkResponse, clientIP) +return d def render_GET(self, request): """Retrieve a ReCaptcha from the API server and serve it to the client. ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Merge branch 'master' into develop
commit eb5abdcb75e94f87013a8a865a3f5978dd30c660 Merge: 24dc8dc f266f32 Author: Isis Lovecruft Date: Wed Mar 26 05:46:59 2014 + Merge branch 'master' into develop ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Move HTTPServer.geoipdb to _geoipdb and outside try function.
commit e6e7552e8c8207ea04c42d209ec735a3c12b2238 Author: Isis Lovecruft Date: Mon Mar 17 22:53:30 2014 + Move HTTPServer.geoipdb to _geoipdb and outside try function. * If it's outside the try function, it's easier to change from other modules (as well as for unittests). --- lib/bridgedb/HTTPServer.py | 10 +- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index e9abc78..89989eb 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -59,19 +59,19 @@ lookup = TemplateLookup(directories=[template_root], collection_size=500) +_geoipdb = '/usr/share/GeoIP/GeoIP.dat' + try: # Make sure we have the database before trying to import the module: -geoipdb = '/usr/share/GeoIP/GeoIP.dat' -if not os.path.isfile(geoipdb): +if not os.path.isfile(_geoipdb): raise EnvironmentError("Could not find %r. On Debian-based systems, "\ "please install the geoip-database package." - % geoipdb) + % _geoipdb) # This is a "pure" python version which interacts with the Maxmind GeoIP # API (version 1). It require, in Debian, the libgeoip-dev and # geoip-database packages. import pygeoip -geoip = pygeoip.GeoIP(geoipdb, flags=pygeoip.MEMORY_CACHE) - +geoip = pygeoip.GeoIP(_geoipdb, flags=pygeoip.MEMORY_CACHE) except Exception as err: logging.debug("Error while loading geoip module: %r" % err) logging.warn("GeoIP database not found") ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Start writing unittests for the bridgedb.HTTPServer module.
commit 9a4bd295a89f2be7f700bfa68d34bcba03954e40 Author: Isis Lovecruft Date: Tue Mar 18 04:12:46 2014 + Start writing unittests for the bridgedb.HTTPServer module. The ReCaptchaProtectedResourceTests.test_render_POST_* unittests expose the bug in #11231. --- lib/bridgedb/test/test_HTTPServer.py | 371 ++ 1 file changed, 371 insertions(+) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py new file mode 100644 index 000..da910c6 --- /dev/null +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -0,0 +1,371 @@ +# -*- encoding: utf-8 -*- +#_ +# +# This file is part of BridgeDB, a Tor bridge distribution system. +# +# :authors: Isis Lovecruft 0xA3ADB67A2CDB8B35 +# :copyright: (c) 2014, Isis Lovecruft +# (c) 2014, The Tor Project, Inc. +# :license: see LICENSE for licensing information +#_ + +"""Unittests for :mod:`bridgedb.HTTPServer`.""" + +import os +import shutil + +import ipaddr + +from BeautifulSoup import BeautifulSoup + +from twisted.internet import reactor +from twisted.trial import unittest +from twisted.web.resource import Resource +from twisted.web.test import requesthelper + +from bridgedb import HTTPServer + +import logging +logging.disable(50) + + +class ReplaceErrorPageTests(unittest.TestCase): +"""Tests for :func:`bridgedb.HTTPServer.replaceErrorPage`.""" + +def test_replaceErrorPage(self): +"""``replaceErrorPage`` should return the expected html.""" +exc = Exception("vegan gümmibären") +errorPage = HTTPServer.replaceErrorPage(exc) +self.assertSubstring("Something went wrong", errorPage) +self.assertNotSubstring("vegan gümmibären", errorPage) + + +class CaptchaProtectedResourceTests(unittest.TestCase): +"""Tests for :mod:`bridgedb.HTTPServer.CaptchaProtectedResource`.""" + +def setUp(self): +self.dist = None +self.sched = None +self.pagename = b'somepage.html' +self.root = Resource() +self.protectedResource = HTTPServer.WebResourceBridges(self.dist, + self.sched) +self.captchaResource = HTTPServer.CaptchaProtectedResource( +useForwardedHeader=True, resource=self.protectedResource) +self.root.putChild(self.pagename, self.captchaResource) + +def test_render_GET_noCaptcha(self): +"""render_GET() should return a page without a CAPTCHA, which has the +image alt text. +""" +request = requesthelper.DummyRequest([self.pagename]) +request.method = b'GET' +page = self.captchaResource.render_GET(request) +self.assertSubstring( +"Your browser is not displaying images properly", page) + +def test_render_GET_missingTemplate(self): +"""render_GET() with a missing template should raise an error and +return the result of replaceErrorPage(). +""" +oldLookup = HTTPServer.lookup +try: +HTTPServer.lookup = None +request = requesthelper.DummyRequest([self.pagename]) +request.method = b'GET' +page = self.captchaResource.render_GET(request) +errorPage = HTTPServer.replaceErrorPage(Exception('kablam')) +self.assertEqual(page, errorPage) +finally: +HTTPServer.lookup = oldLookup + +def test_getClientIP_XForwardedFor(self): +"""CaptchaProtectedResource.getClientIP() should return the IP address +from the 'X-Forwarded-For' header when ``useForwardedHeader=True``. +""" +requestIP = b'6.6.6.6' +request = requesthelper.DummyRequest([self.pagename]) +request.setHeader(b'X-Forwarded-For', requestIP) +request.method = b'GET' + +#child = root.getChild(pagename, request) +page = self.captchaResource.render_GET(request) +clientIP = self.captchaResource.getClientIP(request) +#self.assertEquals(requestIP, clientIP) + +def test_render_POST(self): +"""render_POST() with a wrong 'captcha_response_field' should return +a redirect to the CaptchaProtectedResource page. +""" +pagename = 'captcha.html' +self.root.putChild(pagename, self.captchaResource) + +def redirect(request): +newRequest = type(request) +newRequest.uri = pagename +return newRequest + +request = requesthelper.DummyRequest(['captcha.html']) +request.method = b'POST' +request.redirect = redirect(request) + +page = self.captchaResource.render_POST(request) +self.assertEqual(BeautifulSoup(page).find('meta')['http-equiv'], + 'refresh') + + +class GimpCaptchaProtectedResourceTests(unittest.Test
[tor-commits] [bridgedb/develop] Update CHANGELOG with additional changes for 0.1.6.
commit 24dc8dc82033cbd8ee14d1c06db1e2a3fbcfdbd6 Author: Isis Lovecruft Date: Wed Mar 26 05:42:51 2014 + Update CHANGELOG with additional changes for 0.1.6. --- CHANGELOG |7 ++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG b/CHANGELOG index bf895ad..092ce8c 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,10 +1,15 @@ -Changes in version 0.1.6 - 2014-03-17 +Changes in version 0.1.6 - 2014-03-26 BridgeDB 0.1.6 includes fixes for the following bugs: + * FIXES #11196 BridgeDB should use leekspin * FIXES #11218 ReCaptchaProtectedResource.checkSolution() doesn't expect a deferred * FIXES #11219 BridgeDB's twisted version doesn´t have a `t.w.client.HTTPConnectionPool` class + * FIXES #11231 BridgeDB's txrecaptcha returns the "No bridges + available!" page if 'captcha_response_field' is blank +And includes the following general changes: + * ADDS several new translations languages. Changes in version 0.1.5 - 2014-02-27 BridgeDB 0.1.5 includes fixes for the following bugs: ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add link to CHANGELOG from webserver.
commit f30cc6d2f2eabc5129a2e572707f6fc53c005e75 Author: Isis Lovecruft Date: Mon Mar 17 05:15:29 2014 + Add link to CHANGELOG from webserver. --- lib/bridgedb/templates/base.html |7 +-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/bridgedb/templates/base.html b/lib/bridgedb/templates/base.html index 55044e6..4eea5a5 100644 --- a/lib/bridgedb/templates/base.html +++ b/lib/bridgedb/templates/base.html @@ -105,10 +105,13 @@ ${self.body()} © The Tor Project -https://gitweb.torproject.org/bridgedb.git";>${_("Source Code")} -· https://trac.torproject.org/projects/tor/newticket?component=BridgeDB&keywords=bridgedb-reportbug&cc=isis&owner=isis";>${_("Report a Bug")} · +https://gitweb.torproject.org/bridgedb.git/blob_plain/HEAD:/CHANGELOG";> +${_("Change Log")} +· +https://gitweb.torproject.org/bridgedb.git";>${_("Source Code")} +· mailto:i...@torproject.org";>${_("Contact")} ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Fix X-Forwarded-For unittests in CaptchaProtectedResourceTests.
commit bbfa41304d0b4a7ec30bceadfc6bc5b3b923a7d7 Author: Isis Lovecruft Date: Wed Mar 19 18:00:49 2014 + Fix X-Forwarded-For unittests in CaptchaProtectedResourceTests. Apparently, we can't do: request.setHeader('X-Forwarded-For', '1.1.1.1') because then BridgeDB never finds the header. Instead, we must do: request.headers.update({'X-Forwarded-For': '1.1.1.1'}) --- lib/bridgedb/test/test_HTTPServer.py | 34 +++--- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index cd55b46..507b1f0 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -86,19 +86,39 @@ class CaptchaProtectedResourceTests(unittest.TestCase): finally: HTTPServer.lookup = oldLookup +def createRequestWithIPs(self): +"""Set the IP address returned from ``request.getClientIP()`` to +'3.3.3.3', and the IP address reported in the 'X-Forwarded-For' header +to '2.2.2.2'. +""" +request = DummyRequest([self.pagename]) +# Since we do not set ``request.getClientIP`` here like we do in some +# of the other unittests, an exception would be raised here if +# ``getBridgesForRequest()`` is unable to get the IP address from this +# 'X-Forwarded-For' header (because ``ip`` would get set to ``None``). +request.headers.update({'x-forwarded-for': '2.2.2.2'}) +# See :api:`twisted.test.requesthelper.DummyRequest.getClientIP` +request.client = requesthelper.IPv4Address('TCP', '3.3.3.3', 443) +request.method = b'GET' +return request + def test_getClientIP_XForwardedFor(self): """CaptchaProtectedResource.getClientIP() should return the IP address from the 'X-Forwarded-For' header when ``useForwardedHeader=True``. """ -requestIP = b'6.6.6.6' -request = requesthelper.DummyRequest([self.pagename]) -request.setHeader(b'X-Forwarded-For', requestIP) -request.method = b'GET' +self.captchaResource.useForwardedHeader = True +request = self.createRequestWithIPs() +clientIP = self.captchaResource.getClientIP(request) +self.assertEqual(clientIP, '2.2.2.2') -#child = root.getChild(pagename, request) -page = self.captchaResource.render_GET(request) +def test_getClientIP_fromRequest(self): +"""CaptchaProtectedResource.getClientIP() should return the IP address +from the request instance when ``useForwardedHeader=False``. +""" +self.captchaResource.useForwardedHeader = False +request = self.createRequestWithIPs() clientIP = self.captchaResource.getClientIP(request) -#self.assertEquals(requestIP, clientIP) +self.assertEqual(clientIP, '3.3.3.3') def test_render_POST(self): """render_POST() with a wrong 'captcha_response_field' should return ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Update documentation for CaptchaProtectedResource.getCaptchaImage().
commit 573996bd57420ccf5d009a95f20fdc6367edd24a Author: Isis Lovecruft Date: Tue Mar 18 04:48:06 2014 + Update documentation for CaptchaProtectedResource.getCaptchaImage(). --- lib/bridgedb/HTTPServer.py |4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index a67d5ae..47009df 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -139,8 +139,8 @@ class CaptchaProtectedResource(twisted.web.resource.Resource): :returns: A 2-tuple of ``(image, challenge)``, where ``image`` is a binary, JPEG-encoded image, and ``challenge`` is a unique - string. If unable to retrieve a CAPTCHA, returns - ``(None, None)``. + string. If unable to retrieve a CAPTCHA, returns a tuple + containing two empty strings. """ return ('', '') ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Add a real docstring to EmailServer.replyToMail().
commit 1e330cb61bce46f49b29474f8a031d46726ac213 Author: Isis Lovecruft Date: Mon Mar 17 02:59:08 2014 + Add a real docstring to EmailServer.replyToMail(). --- lib/bridgedb/EmailServer.py | 14 -- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/lib/bridgedb/EmailServer.py b/lib/bridgedb/EmailServer.py index f301eb8..d442ccd 100644 --- a/lib/bridgedb/EmailServer.py +++ b/lib/bridgedb/EmailServer.py @@ -236,8 +236,18 @@ def buildSpamWarningTemplate(t): return msg_template def replyToMail(lines, ctx): -"""Given a list of lines from an incoming email message, and a - MailContext object, possibly send a reply. +"""Reply to an incoming email. Maybe. + +If no `response` is returned from :func:`getMailResponse`, then the +incoming email will not be responded to at all. This can happen for +several reasons, for example: if the DKIM signature was invalid or +missing, or if the incoming email came from an unacceptable domain, or if +there have been too many emails from this client in the allotted time +period. + +:param list lines: A list of lines from an incoming email message. +:type ctx: :class:`MailContext` +:param ctx: The configured context for the email server. """ logging.info("Got a completed email; deciding whether to reply.") sendToUser, response = getMailResponse(lines, ctx) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Merge branch 'fix/11218-deferred-solution-isvalid' into develop
commit f5230149ea962a652512440f29ccd1d2fbf233a4 Merge: d40b410 45876ea Author: Isis Lovecruft Date: Mon Mar 17 00:36:44 2014 + Merge branch 'fix/11218-deferred-solution-isvalid' into develop lib/bridgedb/HTTPServer.py | 25 +++-- 1 file changed, 15 insertions(+), 10 deletions(-) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Fix CaptchaProtectedResourceTests.test_render_GET_noCaptcha unittest.
commit 7753289270a992dd51326164803ff4c7076e4da8 Author: Isis Lovecruft Date: Tue Mar 18 04:39:38 2014 + Fix CaptchaProtectedResourceTests.test_render_GET_noCaptcha unittest. We shouldn't return ``(None, None)`` in a stub method when all the other methods and child classes expect ``(str, str)``. --- lib/bridgedb/HTTPServer.py |2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 96ee029..a67d5ae 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -142,7 +142,7 @@ class CaptchaProtectedResource(twisted.web.resource.Resource): string. If unable to retrieve a CAPTCHA, returns ``(None, None)``. """ -return (None, None) +return ('', '') def extractClientSolution(self, request): """Extract the client's CAPTCHA solution from a POST request. ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Fix typo in inline comment in HTTPServer.
commit fa1a5612592b72da5630a6c7d00cb4c51602ab61 Author: Isis Lovecruft Date: Mon Mar 17 22:55:17 2014 + Fix typo in inline comment in HTTPServer. --- lib/bridgedb/HTTPServer.py |2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 89989eb..2744193 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -68,7 +68,7 @@ try: "please install the geoip-database package." % _geoipdb) # This is a "pure" python version which interacts with the Maxmind GeoIP -# API (version 1). It require, in Debian, the libgeoip-dev and +# API (version 1). It requires, in Debian, the libgeoip-dev and # geoip-database packages. import pygeoip geoip = pygeoip.GeoIP(_geoipdb, flags=pygeoip.MEMORY_CACHE) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/master] Only use `t.w.client.HTTPConnectionPool` if available.
commit bd5003961479b047477124e969f9e51850249c38 Author: Isis Lovecruft Date: Mon Mar 17 00:58:20 2014 + Only use `t.w.client.HTTPConnectionPool` if available. * CHANGES bridgedb.txrecaptcha to create agents using the HTTPConnectionPool, only if our Twisted version is high enough. * FIXES #11219. --- lib/bridgedb/txrecaptcha.py | 40 +--- 1 file changed, 29 insertions(+), 11 deletions(-) diff --git a/lib/bridgedb/txrecaptcha.py b/lib/bridgedb/txrecaptcha.py index 96c813b..e1e3234 100644 --- a/lib/bridgedb/txrecaptcha.py +++ b/lib/bridgedb/txrecaptcha.py @@ -15,10 +15,12 @@ from recaptcha.client.captcha import API_SSL_SERVER from recaptcha.client.captcha import RecaptchaResponse from recaptcha.client.captcha import displayhtml +from twisted import version as _twistedversion from twisted.internet import defer from twisted.internet import protocol from twisted.internet import reactor from twisted.python import failure +from twisted.python.util import Version from twisted.web import client from twisted.web.http_headers import Headers from twisted.web.iweb import IBodyProducer @@ -31,10 +33,20 @@ from bridgedb.crypto import SSLVerifyingContextFactory API_SERVER = API_SSL_SERVER API_SSL_VERIFY_URL = "%s/verify" % API_SSL_SERVER -_pool = client.HTTPConnectionPool(reactor, persistent=False) -_pool.maxPersistentPerHost = 5 -_pool.cachedConnectionTimeout = 30 -_agent = client.Agent(reactor, pool=_pool) +# `t.w.client.HTTPConnectionPool` isn't available in Twisted-12.0.0 (see +# ticket #11219): +_connectionPoolAvailable = _twistedversion >= Version('twisted', 12, 1, 0) +if _connectionPoolAvailable: +logging.info("Using HTTPConnectionPool for reCaptcha API server.") +_pool = client.HTTPConnectionPool(reactor, persistent=False) +_pool.maxPersistentPerHost = 5 +_pool.cachedConnectionTimeout = 30 +_agent = client.Agent(reactor, pool=_pool) +else: +logging.warn("Twisted-%s is too old for HTTPConnectionPool! Disabling..." + % _twistedversion.short()) +_pool = None +_agent = client.Agent(reactor) def _setAgent(agent): @@ -45,8 +57,8 @@ def _setAgent(agent): global _agent _agent = agent -def _getAgent(reactor=reactor, url=API_SSL_VERIFY_URL, pool=_pool, - connectTimeout=30, **kwargs): +def _getAgent(reactor=reactor, url=API_SSL_VERIFY_URL, connectTimeout=30, + **kwargs): """Create a :api:`twisted.web.client.Agent` which will verify the certificate chain and hostname for the given **url**. @@ -62,11 +74,17 @@ def _getAgent(reactor=reactor, url=API_SSL_VERIFY_URL, pool=_pool, :api:`twisted.internet.reactor.connectSSL` for specifying the connection timeout. (default: ``30``) """ -return client.Agent(reactor, -contextFactory=SSLVerifyingContextFactory(url), -connectTimeout=connectTimeout, -pool=pool, -**kwargs) +if _connectionPoolAvailable: +return client.Agent(reactor, +contextFactory=SSLVerifyingContextFactory(url), +connectTimeout=connectTimeout, +pool=_pool, +**kwargs) +else: +return client.Agent(reactor, +contextFactory=SSLVerifyingContextFactory(url), +connectTimeout=connectTimeout, +**kwargs) _setAgent(_getAgent()) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Remove a superfluous error message about gettext files.
commit 31ec211fd62da1d816d3ecf73986f30c021bf097 Author: Isis Lovecruft Date: Wed Mar 26 04:58:31 2014 + Remove a superfluous error message about gettext files. --- lib/bridgedb/HTTPServer.py |3 --- 1 file changed, 3 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 24a970f..3809f2d 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -544,9 +544,6 @@ class WebResourceOptions(resource.Resource): rtl = usingRTLLang(request) except Exception as err: # pragma: no cover logging.exception(err) -logging.error("The gettext files were not properly installed.") -logging.info("To install translations, try doing `python " \ - "setup.py compile_catalog`.") request.setHeader("Content-Type", "text/html; charset=utf-8") return lookup.get_template('options.html').render(rtl=rtl) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Remove gimp captcha unittest code from recaptcha unittest setUp().
commit 2c41a3f7c1606ccc26812db913e11808ffabc0f8 Author: Isis Lovecruft Date: Wed Mar 26 05:00:20 2014 + Remove gimp captcha unittest code from recaptcha unittest setUp(). --- lib/bridgedb/test/test_HTTPServer.py |5 - 1 file changed, 5 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 57f0d80..ea2f6e4 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -266,11 +266,6 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): """Create a :class:`HTTPServer.WebResourceBridges` and protect it with a :class:`ReCaptchaProtectedResource`. """ -# Create our cached CAPTCHA directory: -self.captchaDir = 'captchas' -if not os.path.isdir(self.captchaDir): -os.makedirs(self.captchaDir) - # Set up our resources to fake a minimal HTTP(S) server: self.pagename = b'captcha.html' self.root = Resource() ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Merge branch 'release-0.1.6'
commit f266f32c365eb7a16cf156cc02f7e492266a7b51 Merge: 783babc 24dc8dc Author: Isis Lovecruft Date: Wed Mar 26 05:46:11 2014 + Merge branch 'release-0.1.6' .travis.yml |8 +- CHANGELOG | 13 + Makefile|5 +- bridgedb.conf |7 +- lib/bridgedb/Bridges.py | 52 +- lib/bridgedb/Dist.py| 24 +- lib/bridgedb/EmailServer.py | 32 +- lib/bridgedb/HTTPServer.py | 208 -- lib/bridgedb/i18n/ca/LC_MESSAGES/bridgedb.po| 102 +++ lib/bridgedb/i18n/cs/LC_MESSAGES/bridgedb.po| 104 +++ lib/bridgedb/i18n/es_CL/LC_MESSAGES/bridgedb.po | 101 +++ lib/bridgedb/i18n/fi/LC_MESSAGES/bridgedb.po| 102 +++ lib/bridgedb/i18n/fr_CA/LC_MESSAGES/bridgedb.po | 104 +++ lib/bridgedb/i18n/id/LC_MESSAGES/bridgedb.po| 101 +++ lib/bridgedb/i18n/km/LC_MESSAGES/bridgedb.po| 102 +++ lib/bridgedb/i18n/mk/LC_MESSAGES/bridgedb.po| 101 +++ lib/bridgedb/i18n/pt/LC_MESSAGES/bridgedb.po| 102 +++ lib/bridgedb/i18n/th/LC_MESSAGES/bridgedb.po|2 +- lib/bridgedb/i18n/uk/LC_MESSAGES/bridgedb.po| 102 +++ lib/bridgedb/i18n/zh_TW/LC_MESSAGES/bridgedb.po | 100 +++ lib/bridgedb/runner.py |2 +- lib/bridgedb/templates/base.html| 12 +- lib/bridgedb/test/test_HTTPServer.py| 669 + lib/bridgedb/test/test_bridgedb.py | 12 +- lib/bridgedb/test/test_txrecaptcha.py | 21 +- lib/bridgedb/txrecaptcha.py | 52 +- scripts/gen_bridge_descriptors | 870 --- setup.py|8 +- 28 files changed, 2106 insertions(+), 1012 deletions(-) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Change checkSolution() unittest to check for tuple.
commit 9ec8802c7b326bfd518d70211e52afc14fc57e4e Author: Isis Lovecruft Date: Wed Mar 26 05:02:03 2014 + Change checkSolution() unittest to check for tuple. --- lib/bridgedb/test/test_HTTPServer.py |6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 4e6c86b..22b9c63 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -358,9 +358,9 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): self.request.addArg('captcha_challenge_field', '') self.request.addArg('captcha_response_field', '') -self.assertIs(False, - self.successResultOf( - self.captchaResource.checkSolution(self.request))) +self.assertEqual((False, self.request), + self.successResultOf( + self.captchaResource.checkSolution(self.request))) def test_getRemoteIP_useRandomIP(self): """Check that removing our remoteip setting produces a random IP.""" ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Add unittests for HTTPServer.WebResourceOptions.
commit 27280d9fc6aa527eb7a80708df1b25195840567a Author: Isis Lovecruft Date: Wed Mar 26 05:10:26 2014 + Add unittests for HTTPServer.WebResourceOptions. --- lib/bridgedb/test/test_HTTPServer.py | 26 ++ 1 file changed, 26 insertions(+) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 872be3c..c7308a3 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -641,3 +641,29 @@ class WebResourceBridgesTests(unittest.TestCase): self.assertIsInstance(int(port), int) self.assertGreater(int(port), 0) self.assertLessEqual(int(port), 65535) + + +class WebResourceOptionsTests(unittest.TestCase): +"""Tests for :class:`bridgedb.HTTPServer.WebResourceOptions`.""" + +def setUp(self): +"""Create a :class:`HTTPServer.WebResourceOptions`.""" +# Set up our resources to fake a minimal HTTP(S) server: +self.pagename = b'options.html' +self.root = Resource() +self.optionsResource = HTTPServer.WebResourceOptions() +self.root.putChild(self.pagename, self.optionsResource) + +def test_render_GET_RTLlang(self): +"""Test rendering a request for obfs3 bridges in Arabic.""" +request = DummyRequest(["bridges?transport=obfs3"]) +request.method = b'GET' +request.getClientIP = lambda: '3.3.3.3' +request.headers.update({'accept-language': 'he'}) +# We actually have to set the request args manually when using a +# DummyRequest: +request.args.update({'transport': 'obfs2'}) + +page = self.optionsResource.render(request) +self.assertSubstring("direction: rtl", page) +self.assertSubstring("××× ×שר××?", page) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Merge branch 'hotfix/11218-async-render' into develop
commit 9eca0869ffe25057f0e23bf39115945e70b2e68b Merge: 80a1331 a3bb0ec Author: Isis Lovecruft Date: Wed Mar 26 05:10:08 2014 + Merge branch 'hotfix/11218-async-render' into develop Makefile |4 +- lib/bridgedb/HTTPServer.py | 157 ++ lib/bridgedb/test/test_HTTPServer.py | 76 3 files changed, 167 insertions(+), 70 deletions(-) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Add a docstring and comment to checkResponse() in ReCaptchaProtectedResource.
commit 228d7e0856cb88723531cb76db12c3a9b32acd5a Author: Isis Lovecruft Date: Wed Mar 26 04:57:56 2014 + Add a docstring and comment to checkResponse() in ReCaptchaProtectedResource. --- lib/bridgedb/HTTPServer.py | 11 +++ 1 file changed, 11 insertions(+) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index f4ab592..24a970f 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -466,6 +466,17 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): % (Util.logSafely(clientIP), request.args)) def checkResponse(solution, request): +"""Check the :class:`txrecaptcha.RecaptchaResponse`. + +:type solution: :class:`txrecaptcha.RecaptchaResponse`. +:param solution: The client's CAPTCHA solution, after it has been +submitted to the reCaptcha API server. +""" +# This valid CAPTCHA result from this function cannot be reliably +# unittested, because it's callbacked to from the deferred +# returned by ``txrecaptcha.submit``, the latter of which would +# require networking (as well as automated CAPTCHA +# breaking). Hence, the 'no cover' pragma. if solution.is_valid: # pragma: no cover logging.info("Valid CAPTCHA solution from %r." % Util.logSafely(clientIP)) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Change unittests for reCaptcha render_POST() to check NOT_DONE_YET.
commit a3bb0ec066907bbf3b888b232d6b64a8a3c2f2ca Author: Isis Lovecruft Date: Wed Mar 26 05:03:10 2014 + Change unittests for reCaptcha render_POST() to check NOT_DONE_YET. --- lib/bridgedb/test/test_HTTPServer.py |6 ++ 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 22b9c63..872be3c 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -400,8 +400,7 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): self.request.addArg('captcha_response_field', '') page = self.captchaResource.render_POST(self.request) -self.assertEqual(BeautifulSoup(page).find('meta')['http-equiv'], - 'refresh') +self.assertEqual(page, HTTPServer.server.NOT_DONE_YET) def test_render_POST_wrongSolution(self): """render_POST() with a wrong 'captcha_response_field' should return @@ -415,8 +414,7 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): self.request.addArg('captcha_response_field', expectedResponse) page = self.captchaResource.render_POST(self.request) -self.assertEqual(BeautifulSoup(page).find('meta')['http-equiv'], - 'refresh') +self.assertEqual(page, HTTPServer.server.NOT_DONE_YET) class DummyBridge(object): ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Add leekspin dependency; modify test_bridgedb and bridgedb.runner apropos.
commit 6d991ba844be61f944b13ca4a7077c03464406a0 Author: Isis Lovecruft Date: Mon Mar 24 03:12:52 2014 + Add leekspin dependency; modify test_bridgedb and bridgedb.runner apropos. --- .travis.yml|4 ++-- lib/bridgedb/runner.py |2 +- lib/bridgedb/test/test_bridgedb.py | 12 +--- setup.py |8 4 files changed, 16 insertions(+), 10 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8d8bfcf..902c3b4 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,8 +27,8 @@ python: - "2.7" install: - - pip install -r requirements.txt --use-mirrors - - pip install coverage==3.7 coveralls==0.3 sure==1.2.2 --use-mirrors + - pip install -r requirements.txt + - pip install --no-use-wheel leekspin==0.1.1 coverage==3.7 coveralls==0.3 sure==1.2.2 - make install script: diff --git a/lib/bridgedb/runner.py b/lib/bridgedb/runner.py index 8c641f6..d067bd9 100644 --- a/lib/bridgedb/runner.py +++ b/lib/bridgedb/runner.py @@ -45,7 +45,7 @@ def generateDescriptors(count=None, rundir=None): proc = None statuscode = 0 -script = 'gen_bridge_descriptors' +script = 'leekspin' rundir = rundir if os.path.isdir(rundir) else None count = count if count else 3 try: diff --git a/lib/bridgedb/test/test_bridgedb.py b/lib/bridgedb/test/test_bridgedb.py index 3d21080..5dc890d 100644 --- a/lib/bridgedb/test/test_bridgedb.py +++ b/lib/bridgedb/test/test_bridgedb.py @@ -75,12 +75,18 @@ class BridgeDBCliTest(unittest.TestCase): bridgedbScript = bridgedbScript[0] print("Running bridgedb script %r..." % bridgedbScript) +os.chdir(runDir) # we have to do this to get files to end up there print("Running `bridgedb mock' to generate mock bridge descriptors...") -mockProc = Popen([bridgedbScript, 'mock', - '-n', '50', - '-r', runDir]) +mockProc = Popen([bridgedbScript, 'mock', '-n', '50']) mockProcCode = mockProc.wait() print("`bridgedb mock' exited with status code %d" % int(mockProcCode)) +os.chdir(here) + +# See ticket #11216, cached-extrainfo* files should not be parsed +# cumulatively. +eidesc = pjoin(runDir, 'cached-extrainfo') +eindesc = pjoin(runDir, 'cached-extrainfo.new') +self.doCopyFile(eindesc, eidesc, 'duplicated cached-extrainfo(.new)') print("Running `bridgedb' to test server startups...") bridgedbProc = Popen([bridgedbScript, '-r', runDir]) diff --git a/setup.py b/setup.py index 5ec2d79..d859f87 100644 --- a/setup.py +++ b/setup.py @@ -274,10 +274,10 @@ setuptools.setup( packages=['bridgedb', 'bridgedb.parse', 'bridgedb.test'], -scripts=['scripts/bridgedb', - 'scripts/gen_bridge_descriptors'], -extras_require={'test': ["sure==0.4.5", - "coverage==3.6"]}, +scripts=['scripts/bridgedb'], +extras_require={'test': ["sure==1.2.2", + "coverage==3.7", + "leekspin==0.1.1"]}, zip_safe=False, cmdclass=get_cmdclass(), include_package_data=True, ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Add unittests for _renderDeferred().
commit 3fe40199972595895c05d8760dade246e8134fe4 Author: Isis Lovecruft Date: Wed Mar 26 05:01:04 2014 + Add unittests for _renderDeferred(). --- lib/bridgedb/test/test_HTTPServer.py | 53 ++ 1 file changed, 53 insertions(+) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index ea2f6e4..4e6c86b 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -23,6 +23,7 @@ import ipaddr from BeautifulSoup import BeautifulSoup from twisted.internet import reactor +from twisted.internet import task from twisted.trial import unittest from twisted.web.resource import Resource from twisted.web.test import requesthelper @@ -297,6 +298,58 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): except (AlreadyCalled, AlreadyCancelled): pass +def test_renderDeferred_invalid(self): +""":meth:`_renderDeferred` should redirect a ``Request`` (after the +CAPTCHA was NOT xsuccessfully solved) which results from a +``Deferred``'s callback. +""" +self.request.method = b'POST' + +def testCB(request): +"""Check the ``Request`` returned from ``_renderDeferred``.""" +self.assertIsInstance(request, DummyRequest) +soup = BeautifulSoup(b''.join(request.written)).find('meta')['http-equiv'] +self.assertEqual(soup, 'refresh') + +d = task.deferLater(reactor, 0, lambda x: x, (False, self.request)) +d.addCallback(self.captchaResource._renderDeferred) +d.addCallback(testCB) +return d + +def test_renderDeferred_valid(self): +""":meth:`_renderDeferred` should correctly render a ``Request`` (after +the CAPTCHA has been successfully solved) which results from a +``Deferred``'s callback. +""" +self.request.method = b'POST' + +def testCB(request): +"""Check the ``Request`` returned from ``_renderDeferred``.""" +self.assertIsInstance(request, DummyRequest) +html = b''.join(request.written) +self.assertSubstring('No bridges currently available', html) + +d = task.deferLater(reactor, 0, lambda x: x, (True, self.request)) +d.addCallback(self.captchaResource._renderDeferred) +d.addCallback(testCB) +return d + +def test_renderDeferred_nontuple(self): +""":meth:`_renderDeferred` should correctly render a ``Request`` (after +the CAPTCHA has been successfully solved) which results from a +``Deferred``'s callback. +""" +self.request.method = b'POST' + +def testCB(request): +"""Check the ``Request`` returned from ``_renderDeferred``.""" +self.assertIs(request, None) + +d = task.deferLater(reactor, 0, lambda x: x, (self.request)) +d.addCallback(self.captchaResource._renderDeferred) +d.addCallback(testCB) +return d + def test_checkSolution_blankFields(self): """:meth:`HTTPServer.ReCaptchaProtectedResource.checkSolution` should return a redirect if is the solution field is blank. ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Add a steaming pile of XXXs and FIXMEs to problems in WebResourceBridges.
commit 17f9650dfdcd0a0a00bd245295fa957efe3e7dfc Author: Isis Lovecruft Date: Wed Mar 19 18:27:01 2014 + Add a steaming pile of XXXs and FIXMEs to problems in WebResourceBridges. --- lib/bridgedb/HTTPServer.py | 14 +- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 27dd61e..0de984b 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -426,7 +426,6 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): logging.debug("Captcha from %r. Parameters: %r" % (Util.logSafely(clientIP), request.args)) - def checkResponse(solution, clientIP): if solution.is_valid: logging.info("Valid CAPTCHA solution from %r." @@ -564,10 +563,14 @@ class WebResourceBridges(twisted.web.resource.Resource): :rtype: str :returns: A plaintext or HTML response to serve. """ +# XXX why are we getting the interval if our distributor might be +# using bridgedb.Time.NoSchedule? interval = self.schedule.getInterval(time.time()) bridges = ( ) ip = None countryCode = None + +# XXX this code is duplicated in CaptchaProtectedResource if self.useForwardedHeader: h = request.getHeader("X-Forwarded-For") if h: @@ -578,6 +581,8 @@ class WebResourceBridges(twisted.web.resource.Resource): else: ip = request.getClientIP() +# XXX This can also be a separate function +# XXX if the ip is None, this throws an exception if geoip: countryCode = geoip.country_code_by_addr(ip) if countryCode: @@ -587,6 +592,7 @@ class WebResourceBridges(twisted.web.resource.Resource): if rtl: logging.debug("Rendering RTL response.") +# XXX separate function again format = request.args.get("format", None) if format and len(format): format = format[0] # choose the first arg @@ -596,6 +602,9 @@ class WebResourceBridges(twisted.web.resource.Resource): ipv6 = request.args.get("ipv6", False) if ipv6: ipv6 = True # if anything after ?ipv6= +# XXX oh dear hell. why not check for the '?transport=' arg before +# regex'ing? And why not compile the regex once, somewhere outside +# this function and class? try: # validate method name transport = re.match('[_a-zA-Z][_a-zA-Z0-9]*', @@ -673,6 +682,9 @@ class WebResourceBridges(twisted.web.resource.Resource): else: request.setHeader("Content-Type", "text/html; charset=utf-8") try: +# XXX FIXME the returned page from +# ``WebResourceBridgesTests.test_render_GET_RTLlang`` +# is in Arabic and has ``! Doh. template = lookup.get_template('bridges.html') rendered = template.render(answer=bridgeLines, rtl=rtl) except Exception as err: ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Add coverage pragma lines to blanket excepts in HTTPServer.
commit 4eb7ef398e2e2c28f19031fca6595c679c613fe9 Author: Isis Lovecruft Date: Wed Mar 26 04:56:31 2014 + Add coverage pragma lines to blanket excepts in HTTPServer. They are gross, but we have to have these general excepts everywhere, otherwise users could be shown a traceback. --- lib/bridgedb/HTTPServer.py | 12 ++-- 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index d7b56b3..f4ab592 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -64,7 +64,7 @@ _geoipdb = '/usr/share/GeoIP/GeoIP.dat' try: # Make sure we have the database before trying to import the module: -if not os.path.isfile(_geoipdb): +if not os.path.isfile(_geoipdb): # pragma: no cover raise EnvironmentError("Could not find %r. On Debian-based systems, "\ "please install the geoip-database package." % _geoipdb) @@ -74,7 +74,7 @@ try: import pygeoip geoip = pygeoip.GeoIP(_geoipdb, flags=pygeoip.MEMORY_CACHE) logging.info("GeoIP database loaded") -except Exception as err: +except Exception as err: # pragma: no cover logging.warn("Error while loading geoip module: %r" % err) geoip = None @@ -162,7 +162,7 @@ class CaptchaProtectedResource(resource.Resource): try: challenge = request.args['captcha_challenge_field'][0] response = request.args['captcha_response_field'][0] -except: +except Exception: # pragma: no cover return redirectTo(request.URLPath(), request) return (challenge, response) @@ -314,7 +314,7 @@ class GimpCaptchaProtectedResource(CaptchaProtectedResource): capt.get() except captcha.GimpCaptchaError as error: logging.error(error) -except Exception as error: +except Exception as error: # pragma: no cover logging.error("Unhandled error while retrieving Gimp captcha!") logging.exception(error) @@ -466,7 +466,7 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): % (Util.logSafely(clientIP), request.args)) def checkResponse(solution, request): -if solution.is_valid: +if solution.is_valid: # pragma: no cover logging.info("Valid CAPTCHA solution from %r." % Util.logSafely(clientIP)) return (True, request) @@ -531,7 +531,7 @@ class WebResourceOptions(resource.Resource): try: rtl = usingRTLLang(request) -except Exception as err: +except Exception as err: # pragma: no cover logging.exception(err) logging.error("The gettext files were not properly installed.") logging.info("To install translations, try doing `python " \ ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Merge branch 'fix/11196-use-leekspin_r1' into develop
commit 715ab6a93636f7616036adcd72cf168ede752b42 Merge: 97e261d c9ba8cf Author: Isis Lovecruft Date: Tue Mar 25 02:28:31 2014 + Merge branch 'fix/11196-use-leekspin_r1' into develop .travis.yml|7 +- lib/bridgedb/runner.py |2 +- lib/bridgedb/test/test_bridgedb.py | 12 +- scripts/gen_bridge_descriptors | 870 setup.py |8 +- 5 files changed, 16 insertions(+), 883 deletions(-) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Add --rcfile option to additional coverage lines in Makefile.
commit eabc57bdb24dec6d4693463a7029b1106bf71778 Author: Isis Lovecruft Date: Wed Mar 26 04:59:13 2014 + Add --rcfile option to additional coverage lines in Makefile. --- Makefile |4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index edfc69f..22a231e 100644 --- a/Makefile +++ b/Makefile @@ -45,5 +45,5 @@ clean: coverage: -coverage run --rcfile=".coveragerc" $(TRIAL) ./lib/bridgedb/test/test_*.py - -coverage report - -coverage html + -coverage report --rcfile=".coveragerc" + -coverage html --rcfile=".coveragerc" ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Change ReCaptchaProtectedResource.checkResponse() to also return request.
commit 1bc823d54b507438972b53cc6774de7c6d626ab4 Author: Isis Lovecruft Date: Tue Mar 25 22:24:10 2014 + Change ReCaptchaProtectedResource.checkResponse() to also return request. We need to return the original request, not just the boolean representing the validity of the CAPTCHA solution, if we want to be able to interact with the original request while rendering it. --- lib/bridgedb/HTTPServer.py | 15 +-- 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 26bfb6d..e2f1059 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -419,8 +419,11 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): ``'captcha_challenge_field'``, and the other, ``'captcha_response_field'``. These POST arguments should be obtained from :meth:`render_GET`. -:rtupe: bool -:returns: True, if the CAPTCHA solution was valid; False otherwise. +:rtupe: :api:`twisted.internet.defer.Deferred` +:returns: the returned deferred will callback with a tuple of +(``bool``, :api:`twisted.web.server.Request`). If the CAPTCHA +solution was valid, a tuple will contain ``(True, request)``; +otherwise, it will contain ``(False, request)``. """ challenge, response = self.extractClientSolution(request) clientIP = self.getClientIP(request) @@ -429,18 +432,18 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): logging.debug("Captcha from %r. Parameters: %r" % (Util.logSafely(clientIP), request.args)) -def checkResponse(solution, clientIP): +def checkResponse(solution, request): if solution.is_valid: logging.info("Valid CAPTCHA solution from %r." % Util.logSafely(clientIP)) -return True +return (True, request) else: logging.info("Invalid CAPTCHA solution from %r: %r" % (Util.logSafely(clientIP), solution.error_code)) -return False +return (False, request) d = txrecaptcha.submit(challenge, response, self.recaptchaPrivKey, - remoteIP).addCallback(checkResponse, clientIP) + remoteIP).addCallback(checkResponse, request) return d def render_GET(self, request): ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Add ReCaptchaProtectedResource._renderDeferred() to render deferred resources.
commit db8eef49536f0c18891bdf1f5151733e07ffc8d3 Author: Isis Lovecruft Date: Tue Mar 25 22:28:45 2014 + Add ReCaptchaProtectedResource._renderDeferred() to render deferred resources. --- lib/bridgedb/HTTPServer.py | 33 + 1 file changed, 33 insertions(+) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index e2f1059..4c5d414 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -367,6 +367,39 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): self.recaptchaPubKey = recaptchaPubKey self.recaptchaRemoteIP = remoteip +def _renderDeferred(self, checkedRequest): +"""Render this resource asynchronously. + +:type checkedRequest: tuple +:param checkedRequest: A tuple of ``(bool, request)``, as returned +from :meth:`checkSolution`. +""" +try: +valid, request = checkedRequest +except Exception as err: +logging.error("Error in _renderDeferred(): %s" % err) +return + +logging.debug("Attemping to render %svalid request %r" + % ('' if valid else 'in', request)) +if valid is True: +try: +rendered = self.resource.render(request) +except Exception as err: # pragma: no cover +rendered = replaceErrorPage(err) +else: +logging.info("Client failed a CAPTCHA; redirecting to %s" + % request.uri) +rendered = redirectTo(request.uri, request) + +try: +request.write(rendered) +request.finish() +except Exception as err: # pragma: no cover +logging.exception(err) + +return request + def getCaptchaImage(self, request): """Get a CAPTCHA image from the remote reCaptcha server. ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] More import cleanups for HTTPServer.
commit 1234ed25027bff7936b5bc32d32233970ed2813e Author: Isis Lovecruft Date: Tue Mar 25 22:21:11 2014 + More import cleanups for HTTPServer. * CHANGE `from twisted.web.server import Site` to import the entire `server` module instead. --- lib/bridgedb/HTTPServer.py |4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index c55e668..7e7df98 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -16,9 +16,9 @@ import os from twisted.internet import reactor from twisted.internet.error import CannotListenError -from twisted.web.server import Site from twisted.python import filepath from twisted.web import resource +from twisted.web import server from twisted.web import static from twisted.web.util import redirectTo @@ -789,7 +789,7 @@ def addWebServer(cfg, dist, sched): else: httpdist.putChild('bridges', bridgesResource) -site = Site(httpdist) +site = server.Site(httpdist) if cfg.HTTP_UNENCRYPTED_PORT: ip = cfg.HTTP_UNENCRYPTED_BIND_IP or "" ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Fix txrecaptcha.submit() to always return Deferreds.
commit b4f88aded4fd6cc60be0129e1b6d0bd708d392c7 Author: Isis Lovecruft Date: Wed Mar 19 18:30:12 2014 + Fix txrecaptcha.submit() to always return Deferreds. All returned Deferreds callback with RecaptchaResponse objects. This way, we do not need additional code to check if the result was a Deferred (because, in that case, we would need to add a callback function to extract the RecaptchaResponse object from it and check it), or if it directly returned a RecaptchaResponse. This function now *always* returns Deferred. --- lib/bridgedb/txrecaptcha.py | 12 ++-- 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/bridgedb/txrecaptcha.py b/lib/bridgedb/txrecaptcha.py index e1e3234..2185112 100644 --- a/lib/bridgedb/txrecaptcha.py +++ b/lib/bridgedb/txrecaptcha.py @@ -213,12 +213,12 @@ def submit(recaptcha_challenge_field, recaptcha_response_field, :returns: A :api:`~twisted.internet.defer.Deferred` which will callback with a ``recaptcha.RecaptchaResponse`` for the request. """ -if not (recaptcha_response_field and -recaptcha_challenge_field and -len(recaptcha_response_field) and -len(recaptcha_challenge_field)): -return RecaptchaResponse(is_valid=False, - error_code='incorrect-captcha-sol') +if not (recaptcha_response_field and len(recaptcha_response_field) and +recaptcha_challenge_field and len(recaptcha_challenge_field)): +d = defer.Deferred() +d.addBoth(_ebRequest) # We want `is_valid=False` +d.errback(failure.Failure(ValueError('incorrect-captcha-sol'))) +return d params = urllib.urlencode({ 'privatekey': _encodeIfNecessary(private_key), ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Remove `cat bridgedb.log` from after tests in .travis.yml.
commit 80a133156db63aff278470f9c9ea3e95473c6f2a Author: Isis Lovecruft Date: Tue Mar 25 03:04:37 2014 + Remove `cat bridgedb.log` from after tests in .travis.yml. --- .travis.yml |1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 902c3b4..5553a81 100644 --- a/.travis.yml +++ b/.travis.yml @@ -37,4 +37,3 @@ script: after_success: - coveralls - - cat bridgedb.log ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] A couple PEP8 whitespace fixes in docstrings for HTTPServer.
commit 30c63975d03dd2ab26c9ecf35fa190d7e732512b Author: Isis Lovecruft Date: Tue Mar 25 22:23:13 2014 + A couple PEP8 whitespace fixes in docstrings for HTTPServer. --- lib/bridgedb/HTTPServer.py |6 ++ 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 7e7df98..26bfb6d 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -206,7 +206,6 @@ class CaptchaProtectedResource(resource.Resource): request. Otherwise, redirect them back to a new CAPTCHA page. :type request: :api:`twisted.web.http.Request` - :param request: A ``Request`` object, including POST arguments which should include two key/value pairs: one key being ``'captcha_challenge_field'``, and the other, @@ -214,7 +213,7 @@ class CaptchaProtectedResource(resource.Resource): obtained from :meth:`render_GET`. :rtype: str :returns: A rendered HTML page containing a ReCaptcha challenge image - for the client to solve. +for the client to solve. """ if self.checkSolution(request) is True: try: @@ -451,7 +450,7 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): :param request: A ``Request`` object for 'bridges.html'. :rtype: str :returns: A rendered HTML page containing a ReCaptcha challenge image - for the client to solve. +for the client to solve. """ return CaptchaProtectedResource.render_GET(self, request) @@ -463,7 +462,6 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): request. Otherwise, redirect them back to a new CAPTCHA page. :type request: :api:`twisted.web.http.Request` - :param request: A ``Request`` object, including POST arguments which should include two key/value pairs: one key being ``'captcha_challenge_field'``, and the other, ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Merge branch 'fix/11231-blank-captcha-field' into develop
commit 7fdde318ce5446ff55646ccde44f7586d2d411b6 Merge: 18d8d30 a4dd886 Author: Isis Lovecruft Date: Fri Mar 21 22:27:09 2014 + Merge branch 'fix/11231-blank-captcha-field' into develop lib/bridgedb/HTTPServer.py|8 +- lib/bridgedb/test/test_HTTPServer.py | 597 + lib/bridgedb/test/test_txrecaptcha.py | 21 +- 3 files changed, 616 insertions(+), 10 deletions(-) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Change ReCaptchaProtectedResource.render_POST() to call _renderDeferred().
commit 454e0f7870575a362d1d162918519f1e1fda5179 Author: Isis Lovecruft Date: Tue Mar 25 22:30:19 2014 + Change ReCaptchaProtectedResource.render_POST() to call _renderDeferred(). * FIXES #11218 (again). --- lib/bridgedb/HTTPServer.py | 12 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 4c5d414..d7b56b3 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -503,11 +503,15 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): ``'captcha_challenge_field'``, and the other, ``'captcha_response_field'``. These POST arguments should be obtained from :meth:`render_GET`. -:rtype: str -:returns: A rendered HTML page containing a ReCaptcha challenge image - for the client to solve. +:returns: :api:`twisted.web.server.NOT_DONE_YET`, in order to handle +the ``Deferred`` returned from :meth:`checkSolution`. Eventually, +when the ``Deferred`` request is done being processed, +:meth:`_renderDeferred` will handle rendering and displaying the +HTML to the client. """ -return CaptchaProtectedResource.render_POST(self, request) +d = self.checkSolution(request) +d.addCallback(self._renderDeferred) +return server.NOT_DONE_YET class WebResourceOptions(resource.Resource): ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Remove old scripts/gen_bridge_descriptors; use leekspin.
commit c9ba8cffb49e063690c456f97978aaaf279f92df Author: Isis Lovecruft Date: Mon Mar 24 03:27:30 2014 + Remove old scripts/gen_bridge_descriptors; use leekspin. --- scripts/gen_bridge_descriptors | 870 1 file changed, 870 deletions(-) diff --git a/scripts/gen_bridge_descriptors b/scripts/gen_bridge_descriptors deleted file mode 100644 index 362ed3d..000 --- a/scripts/gen_bridge_descriptors +++ /dev/null @@ -1,870 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -"""Generate valid and signed descriptors for mocked Tor relays or bridges. - -.. todo:: Finish enough CFFI_ bindings for the newer PyNaCl_ (or enough of the -SWIG_ bindings for the older pynacl_) to be able to emulate the following -curvecp_ command (the ``curvecp*`` commands require libchloride_): - -$ curvecpmakekey ntor-key -$ curvecpprintkey ntor-key > ntor-key.hex -$ python -c 'import binascii, sys; \ -key_hex=open('./ntor-key.hex','rb').read();\ -key_b64=binascii.b2a_base64(binascii.unhexlify(key_hex));\ -sys.stdout.write(key_b64);' - -.. _CFFI: https://cffi.readthedocs.org -.. _PyNaCl: https://github.com/seanlynch/pynacl -.. _SWIG: https://github.com/swig/swig -.. _pynacl: https://github.com/seanlynch/pynacl -.. _curvecp: http://curvecp.org/ -.. _libchloride: https://github.com/jedisct1/libchloride - -.. authors:: Isis Lovecruft 0xA3ADB67A2CDB8B35 - Matthew Finkel -.. licence:: distributed with BridgeDB, see included LICENSE file -.. copyright:: (c) 2013 Matthew Finkel, Isis Lovecruft, The Tor Project, Inc. -""" - -from __future__ import print_function -from __future__ import absolute_import -from __future__ import unicode_literals - -import argparse -import binascii -import hashlib -import ipaddr -import math -import os -import sys -import random -import re -import time -import traceback - -from datetime import datetime -from codecs import open as open - -try: -import OpenSSL.crypto -except (ImportError, NameError) as error: -print("This script requires pyOpenSSL>=0.13.0") -raise SystemExit(error.message) -try: -from bridgedb.parse import versions -except (ImportError, NameError) as error: -print(error.message) -print("WARNING: Cannot import bridgedb package!", - "Generated descriptor content won't accurately reflect descriptor", - "information created by different Tor versions.", sep='\n\t') -try: -import nacl -import nacl.secret -except (ImportError, NameError, IOError): -nacl = secret = None - - -#: The version of this script -__version__ = '0.2.0' - -#: The ... version numbers for tor, taken from the -#: 'server-versions' line of a consensus file -SERVER_VERSIONS = """0.2.2.39,0.2.3.24-rc,0.2.3.25, -0.2.4.5-alpha,0.2.4.6-alpha,0.2.4.7-alpha,0.2.4.8-alpha,0.2.4.9-alpha, -0.2.4.10-alpha,0.2.4.11-alpha,0.2.4.12-alpha,0.2.4.14-alpha,0.2.4.15-rc, -0.2.4.16-rc,0.2.4.17-rc,0.2.5.1-alpha""".replace('\n', '').split(',') - -#: Strings found in PEM-encoded objects created by Tor -TOR_BEGIN_KEY = "-BEGIN RSA PUBLIC KEY-" -TOR_END_KEY = "-END RSA PUBLIC KEY-" -TOR_BEGIN_SK = "-BEGIN RSA PRIVATE KEY-" -TOR_END_SK= "-END RSA PRIVATE KEY-" -TOR_BEGIN_SIG = "-BEGIN SIGNATURE-" -TOR_END_SIG = "-END SIGNATURE-" - -#: Strings found in PEM-encoded objects created by OpenSSL -OPENSSL_BEGIN_KEY = "-BEGIN PRIVATE KEY-" -OPENSSL_END_KEY= "-END PRIVATE KEY-" -OPENSSL_BEGIN_CERT = "-BEGIN CERTIFICATE-" -OPENSSL_END_CERT = "-END CERTIFICATE-" - -PEM = OpenSSL.crypto.FILETYPE_PEM -ASN1 = OpenSSL.crypto.FILETYPE_ASN1 - - -class OpenSSLKeyGenError(Exception): -"""Raised when there is a problem generating a new key.""" - - -def getArgParser(): -"""Get our :class:`~argparse.ArgumentParser`.""" -parser = argparse.ArgumentParser(add_help=True) -parser.version = __version__ -parser.description = "Generate a signed set of network-status, " -parser.description += "extra-info, and server descriptor documents " -parser.description += "for mock Tor relays or bridges." -infoargs = parser.add_mutually_exclusive_group() -verbargs = parser.add_mutually_exclusive_group() -infoargs.add_argument("-v", "--verbose", action="store_true", - help="print information to stdout") -infoargs.add_argument("-q", "--quiet", action="store_true", - help="don't print anything") -verbargs.add_argument("--version", action="store_true", - help="print the %s version and exit".format( - parser.prog)) -group = parser.add_argument_group() -group.title = "required arguments" -group.add_argument("-n", "--descriptors", default=0, - help="generate descriptor sets", type=int) -return parser - -def ran
[tor-commits] [bridgedb/develop] Merge branch 'fix/11231-additional-bug-fixes' into develop
commit 00eaf9160f65c16c725ed7f05ac0583b9da63dc0 Merge: 7fdde31 b4f88ad Author: Isis Lovecruft Date: Fri Mar 21 22:30:10 2014 + Merge branch 'fix/11231-additional-bug-fixes' into develop lib/bridgedb/HTTPServer.py | 14 +- lib/bridgedb/txrecaptcha.py | 12 ++-- 2 files changed, 19 insertions(+), 7 deletions(-) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Remove superfluous descriptor generation.
commit 3f3ead057007b2dceb0575267b1784c61241f110 Author: Isis Lovecruft Date: Mon Mar 24 03:14:04 2014 + Remove superfluous descriptor generation. --- .travis.yml |3 --- 1 file changed, 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 9858edf..8d8bfcf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,9 +31,6 @@ install: - pip install coverage==3.7 coveralls==0.3 sure==1.2.2 --use-mirrors - make install -before_script: - - bridgedb mock -n 250 - script: - coverage run $(which trial) ./lib/bridgedb/test/test_*.py - coverage report ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Remove 'installed-files.txt' after `make uninstall` completes.
commit 97e261d1ba04d42e948d6f417ebd1878bbce5004 Author: Isis Lovecruft Date: Tue Mar 25 00:43:21 2014 + Remove 'installed-files.txt' after `make uninstall` completes. --- Makefile |1 + 1 file changed, 1 insertion(+) diff --git a/Makefile b/Makefile index abf392e..edfc69f 100644 --- a/Makefile +++ b/Makefile @@ -30,6 +30,7 @@ force-install: uninstall: touch installed-files.txt cat installed-files.txt | xargs rm -rf + rm installed-files.txt reinstall: uninstall force-install ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Cleanup imports in bridgedb.HTTPServer.
commit dd67a2830d4366f966e780818abc7c94fede16bf Author: Isis Lovecruft Date: Tue Mar 25 22:13:18 2014 + Cleanup imports in bridgedb.HTTPServer. * CHANGE all objects named `resource` to something more specific, otherwise we cannot do `from twisted.web import resource`. --- lib/bridgedb/HTTPServer.py | 61 ++ lib/bridgedb/test/test_HTTPServer.py |6 ++-- 2 files changed, 36 insertions(+), 31 deletions(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 0de984b..c55e668 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -16,11 +16,11 @@ import os from twisted.internet import reactor from twisted.internet.error import CannotListenError -import twisted.web.resource from twisted.web.server import Site +from twisted.python import filepath +from twisted.web import resource from twisted.web import static from twisted.web.util import redirectTo -from twisted.python import filepath import bridgedb.Dist import bridgedb.I18n as I18n @@ -28,11 +28,12 @@ import bridgedb.Util as Util from bridgedb import captcha from bridgedb import crypto -from bridgedb.Filters import filterBridgesByIP6, filterBridgesByIP4 +from bridgedb import txrecaptcha +from bridgedb.Filters import filterBridgesByIP4 +from bridgedb.Filters import filterBridgesByIP6 from bridgedb.Filters import filterBridgesByTransport from bridgedb.Filters import filterBridgesByNotBlockedIn from bridgedb.parse import headers -from bridgedb import txrecaptcha from ipaddr import IPv4Address, IPv6Address from random import randint @@ -111,15 +112,15 @@ def replaceErrorPage(error, template_name=None): return rendered -class CaptchaProtectedResource(twisted.web.resource.Resource): +class CaptchaProtectedResource(resource.Resource): """A general resource protected by some form of CAPTCHA.""" isLeaf = True -def __init__(self, useForwardedHeader=False, resource=None): -twisted.web.resource.Resource.__init__(self) +def __init__(self, useForwardedHeader=False, protectedResource=None): +resource.Resource.__init__(self) self.useForwardedHeader = useForwardedHeader -self.resource = resource +self.resource = protectedResource def getClientIP(self, request): ip = None @@ -235,8 +236,9 @@ class GimpCaptchaProtectedResource(CaptchaProtectedResource): """ def __init__(self, secretKey=None, publicKey=None, hmacKey=None, - captchaDir='', useForwardedHeader=False, resource=None): -"""Protect a **resource** via this one, using a local CAPTCHA cache. + captchaDir='', useForwardedHeader=False, + protectedResource=None): +"""Protect a resource via this one, using a local CAPTCHA cache. :param str secretkey: A PKCS#1 OAEP-padded, private RSA key, used for verifying the client's solution to the CAPTCHA. See @@ -253,11 +255,12 @@ class GimpCaptchaProtectedResource(CaptchaProtectedResource): are stored. See the ``GIMP_CAPTCHA_DIR`` config setting. :param bool useForwardedHeader: If ``True``, obtain the client's IP address from the ``X-Forwarded-For`` HTTP header. -:type resource: :api:`twisted.web.resource.Resource` -:param resource: The resource to serve if the client successfully -passes the CAPTCHA challenge. +:type protectedResource: :api:`twisted.web.resource.Resource` +:param protectedResource: The resource to serve if the client +successfully passes the CAPTCHA challenge. """ -CaptchaProtectedResource.__init__(self, useForwardedHeader, resource) +CaptchaProtectedResource.__init__(self, useForwardedHeader, + protectedResource) self.secretKey = secretKey self.publicKey = publicKey self.hmacKey = hmacKey @@ -358,8 +361,9 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): """ def __init__(self, recaptchaPrivKey='', recaptchaPubKey='', remoteip='', - useForwardedHeader=False, resource=None): -CaptchaProtectedResource.__init__(self, useForwardedHeader, resource) + useForwardedHeader=False, protectedResource=None): +CaptchaProtectedResource.__init__(self, useForwardedHeader, + protectedResource) self.recaptchaPrivKey = recaptchaPrivKey self.recaptchaPubKey = recaptchaPubKey self.recaptchaRemoteIP = remoteip @@ -472,7 +476,7 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource): return CaptchaProtectedResource.render_POST(self, request) -class WebResourceOptions(twisted.web.resource.Resource): +class WebResourceOptions(resource.Resource): """This resource is used by Twisted Web to give a web page with additi
[tor-commits] [bridgedb/develop] Use the class wrapper DummyRequest in unittests in test_HTTPServer.py.
commit 3d6a4ca6f0aaba53785ab935ddc036549e925a7e Author: Isis Lovecruft Date: Wed Mar 19 17:58:48 2014 + Use the class wrapper DummyRequest in unittests in test_HTTPServer.py. --- lib/bridgedb/test/test_HTTPServer.py | 36 +- 1 file changed, 5 insertions(+), 31 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 73297de..cd55b46 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -65,7 +65,7 @@ class CaptchaProtectedResourceTests(unittest.TestCase): """render_GET() should return a page without a CAPTCHA, which has the image alt text. """ -request = requesthelper.DummyRequest([self.pagename]) +request = DummyRequest([self.pagename]) request.method = b'GET' page = self.captchaResource.render_GET(request) self.assertSubstring( @@ -78,7 +78,7 @@ class CaptchaProtectedResourceTests(unittest.TestCase): oldLookup = HTTPServer.lookup try: HTTPServer.lookup = None -request = requesthelper.DummyRequest([self.pagename]) +request = DummyRequest([self.pagename]) request.method = b'GET' page = self.captchaResource.render_GET(request) errorPage = HTTPServer.replaceErrorPage(Exception('kablam')) @@ -104,18 +104,8 @@ class CaptchaProtectedResourceTests(unittest.TestCase): """render_POST() with a wrong 'captcha_response_field' should return a redirect to the CaptchaProtectedResource page. """ -pagename = 'captcha.html' -self.root.putChild(pagename, self.captchaResource) - -def redirect(request): -newRequest = type(request) -newRequest.uri = pagename -return newRequest - -request = requesthelper.DummyRequest(['captcha.html']) +request = DummyRequest([self.pagename]) request.method = b'POST' -request.redirect = redirect(request) - page = self.captchaResource.render_POST(request) self.assertEqual(BeautifulSoup(page).find('meta')['http-equiv'], 'refresh') @@ -149,15 +139,7 @@ class GimpCaptchaProtectedResourceTests(unittest.TestCase): self.root.putChild(self.pagename, self.captchaResource) # Set up the basic parts of our faked request: -self.request = requesthelper.DummyRequest([self.pagename]) -self.request.URLPath = lambda: request.uri # Fake the URLPath too -self.request.redirect = self.doRedirect(self.request) - -def doRedirect(self, request): -"""Stub method to add a redirect() to DummyResponse.""" -newRequest = type(request) -newRequest.uri = self.pagename -return newRequest +self.request = DummyRequest([self.pagename]) def tearDown(self): """Delete the cached CAPTCHA directory if it still exists.""" @@ -283,15 +265,7 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): self.root.putChild(self.pagename, self.captchaResource) # Set up the basic parts of our faked request: -self.request = requesthelper.DummyRequest([self.pagename]) -self.request.URLPath = lambda: request.uri # Fake the URLPath too -self.request.redirect = self.doRedirect(self.request) - -def doRedirect(self, request): -"""Stub method to add a redirect() to DummyResponse.""" -newRequest = type(request) -newRequest.uri = self.pagename -return newRequest +self.request = DummyRequest([self.pagename]) def tearDown(self): """Cleanup method for removing timed out connections on the reactor. ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Add unittests for HTTPServer.WebResourceBridges.
commit a4dd886c34ce6f1c30d752d68f42dd8eefd260fc Author: Isis Lovecruft Date: Wed Mar 19 18:08:26 2014 + Add unittests for HTTPServer.WebResourceBridges. --- lib/bridgedb/test/test_HTTPServer.py | 136 ++ 1 file changed, 136 insertions(+) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 9b5a6e4..9f241d9 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -28,6 +28,7 @@ from twisted.web.resource import Resource from twisted.web.test import requesthelper from bridgedb import HTTPServer +from bridgedb.Time import IntervalSchedule # For additional logger output for debugging, comment out the following: @@ -459,3 +460,138 @@ class DummyRequest(requesthelper.DummyRequest): newRequest = type(request) newRequest.uri = request.uri return newRequest + + +class WebResourceBridgesTests(unittest.TestCase): +"""Tests for :class:`HTTPServer.WebResourceBridges`.""" + +def setUp(self): +"""Set up our resources to fake a minimal HTTP(S) server.""" +self.pagename = b'bridges.html' +self.root = Resource() + +self.dist = DummyIPBasedDistributor() +self.sched = IntervalSchedule('hour', 1) +self.nBridgesPerRequest = 2 +self.bridgesResource = HTTPServer.WebResourceBridges( +self.dist, self.sched, N=2, +#useForwardedHeader=True, +includeFingerprints=True) + +self.root.putChild(self.pagename, self.bridgesResource) + +def parseBridgesFromHTMLPage(self, page): +"""Utility to pull the bridge lines out of an HTML response page. + +:param str page: A rendered HTML page, as a string. +:raises: Any error which might occur. +:rtype: list +:returns: A list of the bridge lines contained on the **page**. +""" +# The bridge lines are contained in a tag: +soup = BeautifulSoup(page).find('pre') +soup = str(soup).replace('', '').strip() +soup = str(soup).replace('', '').strip() +bridges = [b.strip() for b in soup.splitlines()] +return bridges + +def test_render_GET_vanilla(self): +"""Test rendering a request for normal, vanilla bridges.""" +request = DummyRequest([self.pagename]) +request.method = b'GET' +request.getClientIP = lambda: '1.1.1.1' + +page = self.bridgesResource.render(request) + +# The response should explain how to use the bridge lines: +self.assertSubstring("To use the above lines", page) + +for b in self.parseBridgesFromHTMLPage(page): +# Check that each bridge line had the expected number of fields: +fields = b.split(' ') +self.assertEqual(len(fields), 2) + +# Check that the IP and port seem okay: +ip, port = fields[0].rsplit(':') +self.assertIsInstance(ipaddr.IPv4Address(ip), ipaddr.IPv4Address) +self.assertIsInstance(int(port), int) +self.assertGreater(int(port), 0) +self.assertLessEqual(int(port), 65535) + +def test_render_GET_XForwardedFor(self): +"""The client's IP address should be obtainable from the +'X-Forwarded-For' header in the request. +""" +self.bridgesResource.useForwardedHeader = True +request = DummyRequest([self.pagename]) +request.method = b'GET' +# Since we do not set ``request.getClientIP`` here like we do in some +# of the other unittests, an exception would be raised here if +# ``getBridgesForRequest()`` is unable to get the IP address from this +# 'X-Forwarded-For' header (because ``ip`` would get set to ``None``). +request.headers.update({'x-forwarded-for': '2.2.2.2'}) + +page = self.bridgesResource.render(request) +self.bridgesResource.useForwardedHeader = False # Reset it +self.assertSubstring("To use the above lines", page) + +def test_render_GET_RTLlang(self): +"""Test rendering a request for obfs3 bridges in Arabic.""" +request = DummyRequest(["bridges?transport=obfs3"]) +request.method = b'GET' +request.getClientIP = lambda: '3.3.3.3' +request.headers.update({'accept-language': 'ar'}) +# We actually have to set the request args manually when using a +# DummyRequest: +request.args.update({'transport': 'obfs3'}) + +page = self.bridgesResource.render(request) +self.assertSubstring("direction: rtl", page) +self.assertSubstring("Ùاستخدا٠اÙأسطر أعÙاÙ", page) + +for bridgeLine in self.parseBridgesFromHTMLPage(page): +# Check that each bridge line had the expected number of fields: +bridgeLine = bridgeLine.split(' ') +self.assertEqual(len(bridgeLine), 3) + +print(""" +
[tor-commits] [bridgedb/develop] Always expect a Deferred from ReCaptcha.checkSolution().
commit 738101ac291235cc1415f4db5c9c023b6521e34f Author: Isis Lovecruft Date: Wed Mar 19 18:03:15 2014 + Always expect a Deferred from ReCaptcha.checkSolution(). Currently, we `checkSolution()` will return a RecaptchaResponse if the HTTP POST argument fields are blank. Otherwise, it returns a deferred. This is bad. It means we have to do all kinds of checks to see if we can add callbacks on the returned object. It should always return a deferred which callbacks with a RecaptchaResponse, and so we should test for that and fail if that is not what is happening. --- lib/bridgedb/test/test_HTTPServer.py |6 +++--- lib/bridgedb/test/test_txrecaptcha.py | 21 +++-- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 507b1f0..9b5a6e4 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -309,9 +309,9 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase): self.request.addArg('captcha_challenge_field', '') self.request.addArg('captcha_response_field', '') -self.assertIsInstance( -self.captchaResource.checkSolution(self.request), -HTTPServer.txrecaptcha.RecaptchaResponse) +self.assertIs(False, + self.successResultOf( + self.captchaResource.checkSolution(self.request))) def test_getRemoteIP_useRandomIP(self): """Check that removing our remoteip setting produces a random IP.""" diff --git a/lib/bridgedb/test/test_txrecaptcha.py b/lib/bridgedb/test/test_txrecaptcha.py index c7dcbb1..81484dc 100644 --- a/lib/bridgedb/test/test_txrecaptcha.py +++ b/lib/bridgedb/test/test_txrecaptcha.py @@ -181,12 +181,21 @@ class SubmitTests(unittest.TestCase): self.ip = "1.2.3.4" def test_submit_emptyResponseField(self): -"""An empty 'recaptcha_response_field' should immediately return a -RecaptchaResponse whose error_code is 'incorrect-captcha-sol'.""" -response = txrecaptcha.submit(self.challenge, '', self.key, self.ip) -self.assertIsInstance(response, txrecaptcha.RecaptchaResponse) -self.assertIs(response.is_valid, False) -self.assertEqual(response.error_code, 'incorrect-captcha-sol') +"""An empty 'recaptcha_response_field' should return a deferred which +callbacks with a RecaptchaResponse whose error_code is +'incorrect-captcha-sol'. +""" +def checkResponse(response): +"""Check that the response is a +:class:`txcaptcha.RecaptchaResponse`. +""" +self.assertIsInstance(response, txrecaptcha.RecaptchaResponse) +self.assertIs(response.is_valid, False) +self.assertEqual(response.error_code, 'incorrect-captcha-sol') + +d = txrecaptcha.submit(self.challenge, '', self.key, self.ip) +d.addCallback(checkResponse) +return d def test_submit_returnsDeferred(self): """:func:`txrecaptcha.submit` should return a deferred.""" ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Change the requested pagename in CaptchaProtectedResourceTests unittests.
commit 25eb893487855f7449610c60895b7bd79f6458e3 Author: Isis Lovecruft Date: Wed Mar 19 17:44:36 2014 + Change the requested pagename in CaptchaProtectedResourceTests unittests. --- lib/bridgedb/test/test_HTTPServer.py |2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index e0c81f8..119d2fc 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -50,7 +50,7 @@ class CaptchaProtectedResourceTests(unittest.TestCase): def setUp(self): self.dist = None self.sched = None -self.pagename = b'somepage.html' +self.pagename = b'bridges.html' self.root = Resource() self.protectedResource = HTTPServer.WebResourceBridges(self.dist, self.sched) ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Fix X-Forwarded-For unittests in CaptchaProtectedResourceTests.
commit bbfa41304d0b4a7ec30bceadfc6bc5b3b923a7d7 Author: Isis Lovecruft Date: Wed Mar 19 18:00:49 2014 + Fix X-Forwarded-For unittests in CaptchaProtectedResourceTests. Apparently, we can't do: request.setHeader('X-Forwarded-For', '1.1.1.1') because then BridgeDB never finds the header. Instead, we must do: request.headers.update({'X-Forwarded-For': '1.1.1.1'}) --- lib/bridgedb/test/test_HTTPServer.py | 34 +++--- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index cd55b46..507b1f0 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -86,19 +86,39 @@ class CaptchaProtectedResourceTests(unittest.TestCase): finally: HTTPServer.lookup = oldLookup +def createRequestWithIPs(self): +"""Set the IP address returned from ``request.getClientIP()`` to +'3.3.3.3', and the IP address reported in the 'X-Forwarded-For' header +to '2.2.2.2'. +""" +request = DummyRequest([self.pagename]) +# Since we do not set ``request.getClientIP`` here like we do in some +# of the other unittests, an exception would be raised here if +# ``getBridgesForRequest()`` is unable to get the IP address from this +# 'X-Forwarded-For' header (because ``ip`` would get set to ``None``). +request.headers.update({'x-forwarded-for': '2.2.2.2'}) +# See :api:`twisted.test.requesthelper.DummyRequest.getClientIP` +request.client = requesthelper.IPv4Address('TCP', '3.3.3.3', 443) +request.method = b'GET' +return request + def test_getClientIP_XForwardedFor(self): """CaptchaProtectedResource.getClientIP() should return the IP address from the 'X-Forwarded-For' header when ``useForwardedHeader=True``. """ -requestIP = b'6.6.6.6' -request = requesthelper.DummyRequest([self.pagename]) -request.setHeader(b'X-Forwarded-For', requestIP) -request.method = b'GET' +self.captchaResource.useForwardedHeader = True +request = self.createRequestWithIPs() +clientIP = self.captchaResource.getClientIP(request) +self.assertEqual(clientIP, '2.2.2.2') -#child = root.getChild(pagename, request) -page = self.captchaResource.render_GET(request) +def test_getClientIP_fromRequest(self): +"""CaptchaProtectedResource.getClientIP() should return the IP address +from the request instance when ``useForwardedHeader=False``. +""" +self.captchaResource.useForwardedHeader = False +request = self.createRequestWithIPs() clientIP = self.captchaResource.getClientIP(request) -#self.assertEquals(requestIP, clientIP) +self.assertEqual(clientIP, '3.3.3.3') def test_render_POST(self): """render_POST() with a wrong 'captcha_response_field' should return ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Add a mocked DummyIPBasedDistributor class to test_HTTPServer.py.
commit 6fcf0121296067f7e47721af315ca5b85021e8b8 Author: Isis Lovecruft Date: Wed Mar 19 17:56:26 2014 + Add a mocked DummyIPBasedDistributor class to test_HTTPServer.py. A distributor is a required parameter to the `HTTPServer.WebResourceBridges` class. This one merely creates N random `DummyBridges`, where N is the number of bridges we're told to return to the client. --- lib/bridgedb/test/test_HTTPServer.py | 27 +++ 1 file changed, 27 insertions(+) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index 05e041c..e2856c7 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -418,3 +418,30 @@ class DummyBridge(object): bridgeLine = " ".join([item for item in line]) #print "Created config line: %r" % bridgeLine return bridgeLine + + +class DummyIPBasedDistributor(object): +"""A mocked :class:`bridgedb.Dist.IPBasedDistributor` which is used to test +:class:`bridgedb.HTTPServer.WebResourceBridges. +""" + +def _dumbAreaMapper(ip): return ip + +def __init__(self, areaMapper=None, nClusters=None, key=None, + ipCategories=None, answerParameters=None): +"""None of the parameters are really used, they are just there to retain +an identical method signature. +""" +self.areaMapper = self._dumbAreaMapper +self.nClusters = 3 +self.nBridgesToGive = 3 +self.key = self.__class__.__name__ +self.ipCategories = ipCategories +self.answerParameters = answerParameters + +def getBridgesForIP(self, ip=None, epoch=None, N=1, +countyCode=None, bridgeFilterRules=None): +"""Needed because it's called in +:meth:`WebResourceBridges.getBridgesForIP`. +""" +return [DummyBridge() for _ in xrange(N)] ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Add class wrapper for requesthelper.DummyRequest to support redirects.
commit ad774181faa5cd367e4173ce14a4449a3164abeb Author: Isis Lovecruft Date: Wed Mar 19 17:57:09 2014 + Add class wrapper for requesthelper.DummyRequest to support redirects. --- lib/bridgedb/test/test_HTTPServer.py | 20 1 file changed, 20 insertions(+) diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py index e2856c7..73297de 100644 --- a/lib/bridgedb/test/test_HTTPServer.py +++ b/lib/bridgedb/test/test_HTTPServer.py @@ -445,3 +445,23 @@ class DummyIPBasedDistributor(object): :meth:`WebResourceBridges.getBridgesForIP`. """ return [DummyBridge() for _ in xrange(N)] + + +class DummyRequest(requesthelper.DummyRequest): +"""Wrapper for :api:`twisted.test.requesthelper.DummyRequest` to add +redirect support. +""" + +def __init__(self, *args, **kwargs): +requesthelper.DummyRequest.__init__(self, *args, **kwargs) +self.redirect = self._redirect(self) + +def URLPath(self): +"""Fake the missing Request.URLPath too.""" +return self.uri + +def _redirect(self, request): +"""Stub method to add a redirect() method to DummyResponse.""" +newRequest = type(request) +newRequest.uri = request.uri +return newRequest ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits
[tor-commits] [bridgedb/develop] Fix CaptchaProtectedResourceTests.test_render_GET_noCaptcha unittest.
commit 7753289270a992dd51326164803ff4c7076e4da8 Author: Isis Lovecruft Date: Tue Mar 18 04:39:38 2014 + Fix CaptchaProtectedResourceTests.test_render_GET_noCaptcha unittest. We shouldn't return ``(None, None)`` in a stub method when all the other methods and child classes expect ``(str, str)``. --- lib/bridgedb/HTTPServer.py |2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py index 96ee029..a67d5ae 100644 --- a/lib/bridgedb/HTTPServer.py +++ b/lib/bridgedb/HTTPServer.py @@ -142,7 +142,7 @@ class CaptchaProtectedResource(twisted.web.resource.Resource): string. If unable to retrieve a CAPTCHA, returns ``(None, None)``. """ -return (None, None) +return ('', '') def extractClientSolution(self, request): """Extract the client's CAPTCHA solution from a POST request. ___ tor-commits mailing list tor-commits@lists.torproject.org https://lists.torproject.org/cgi-bin/mailman/listinfo/tor-commits