tor-commits
Threads by month
- ----- 2026 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- 1 participants
- 216258 discussions
[bridgedb/master] Simplify Captcha and CaptchaProtectedResource keypair attributes.
by isis@torproject.org 16 May '14
by isis@torproject.org 16 May '14
16 May '14
commit f0b9885eabb832e6d0ba688c7723266e9f6b0117
Author: Isis Lovecruft <isis(a)torproject.org>
Date: Wed May 14 21:24:21 2014 +0000
Simplify Captcha and CaptchaProtectedResource keypair attributes.
All *Captcha and *CaptchaProtectedResource classes and subclasses (as
well as their interface specifications) now have `publicKey` and
`secretKey` attributes.
For the GimpCaptcha class, this involved switching the ordering of the
parameters for the initialisation method from:
GimpCaptcha(secretKey, publicKey, ...)
to:
GimpCaptcha(publicKey, secretKey, ...)
Make sure that the intialisations of all of these classes take the
public key *first*. YOU HAVE BEEN WARNED.
---
lib/bridgedb/HTTPServer.py | 103 ++++++++++++++--------------
lib/bridgedb/captcha.py | 125 ++++++++++++++++++++++++----------
lib/bridgedb/test/test_HTTPServer.py | 8 +--
lib/bridgedb/test/test_captcha.py | 54 +++++++--------
4 files changed, 172 insertions(+), 118 deletions(-)
diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py
index 7598755..ead6d60 100644
--- a/lib/bridgedb/HTTPServer.py
+++ b/lib/bridgedb/HTTPServer.py
@@ -20,6 +20,8 @@ import textwrap
import time
import os
+from functools import partial
+
from ipaddr import IPv4Address
from ipaddr import IPv6Address
@@ -138,8 +140,11 @@ class CaptchaProtectedResource(resource.Resource):
isLeaf = True
- def __init__(self, useForwardedHeader=False, protectedResource=None):
+ def __init__(self, publicKey=None, secretKey=None,
+ useForwardedHeader=False, protectedResource=None):
resource.Resource.__init__(self)
+ self.publicKey = publicKey
+ self.secretKey = secretKey
self.useForwardedHeader = useForwardedHeader
self.resource = protectedResource
@@ -270,9 +275,7 @@ class GimpCaptchaProtectedResource(CaptchaProtectedResource):
.. _gimp-captcha: https://github.com/isislovecruft/gimp-captcha
"""
- def __init__(self, secretKey=None, publicKey=None, hmacKey=None,
- captchaDir='', useForwardedHeader=False,
- protectedResource=None):
+ def __init__(self, hmacKey=None, captchaDir='', **kwargs):
"""Protect a resource via this one, using a local CAPTCHA cache.
:param str secretkey: A PKCS#1 OAEP-padded, private RSA key, used for
@@ -294,10 +297,7 @@ class GimpCaptchaProtectedResource(CaptchaProtectedResource):
:param protectedResource: The resource to serve if the client
successfully passes the CAPTCHA challenge.
"""
- CaptchaProtectedResource.__init__(self, useForwardedHeader,
- protectedResource)
- self.secretKey = secretKey
- self.publicKey = publicKey
+ CaptchaProtectedResource.__init__(self, **kwargs)
self.hmacKey = hmacKey
self.captchaDir = captchaDir
@@ -340,7 +340,7 @@ class GimpCaptchaProtectedResource(CaptchaProtectedResource):
# Create a new HMAC key, specific to requests from this client:
clientIP = self.getClientIP(request)
clientHMACKey = crypto.getHMAC(self.hmacKey, clientIP)
- capt = captcha.GimpCaptcha(self.secretKey, self.publicKey,
+ capt = captcha.GimpCaptcha(self.publicKey, self.secretKey,
clientHMACKey, self.captchaDir)
try:
capt.get()
@@ -391,13 +391,9 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource):
.. _reCaptcha: http://www.google.com/recaptcha
"""
- def __init__(self, recaptchaPrivKey='', recaptchaPubKey='', remoteip='',
- useForwardedHeader=False, protectedResource=None):
- CaptchaProtectedResource.__init__(self, useForwardedHeader,
- protectedResource)
- self.recaptchaPrivKey = recaptchaPrivKey
- self.recaptchaPubKey = recaptchaPubKey
- self.recaptchaRemoteIP = remoteip
+ def __init__(self, remoteIP=None, **kwargs):
+ CaptchaProtectedResource.__init__(self, **kwargs)
+ self.remoteIP = remoteIP
def _renderDeferred(self, checkedRequest):
"""Render this resource asynchronously.
@@ -442,7 +438,7 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource):
- ``image`` is a string holding a binary, JPEG-encoded image.
- ``challenge`` is a unique string associated with the request.
"""
- capt = captcha.ReCaptcha(self.recaptchaPubKey, self.recaptchaPrivKey)
+ capt = captcha.ReCaptcha(self.publicKey, self.secretKey)
try:
capt.get()
@@ -464,8 +460,8 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource):
:rtype: str
:returns: A fake IP address to report to the reCaptcha API server.
"""
- if self.recaptchaRemoteIP:
- remoteIP = self.recaptchaRemoteIP
+ if self.remoteIP:
+ remoteIP = self.remoteIP
else:
# generate a random IP for the captcha submission
remoteIP = IPv4Address(random.randint(0, 2**32-1)).compressed
@@ -520,7 +516,7 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource):
% (clientIP, solution.error_code))
return (False, request)
- d = txrecaptcha.submit(challenge, response, self.recaptchaPrivKey,
+ d = txrecaptcha.submit(challenge, response, self.secretKey,
remoteIP).addCallback(checkResponse, request)
return d
@@ -862,6 +858,13 @@ def addWebServer(cfg, dist, sched):
:rtype: :api:`twisted.web.server.Site`
:returns: A webserver.
"""
+ captcha = None
+ fwdHeaders = cfg.HTTP_USE_IP_FROM_FORWARDED_HEADER
+ numBridges = cfg.HTTPS_N_BRIDGES_PER_ANSWER
+ fprInclude = cfg.HTTPS_INCLUDE_FINGERPRINTS
+
+ logging.info("Starting web servers...")
+
httpdist = resource.Resource()
httpdist.putChild('', WebRoot())
httpdist.putChild('robots.txt',
@@ -873,58 +876,56 @@ def addWebServer(cfg, dist, sched):
httpdist.putChild('options', WebResourceOptions())
httpdist.putChild('howto', WebResourceHowto())
- bridgesResource = WebResourceBridges(
- dist, sched, cfg.HTTPS_N_BRIDGES_PER_ANSWER,
- cfg.HTTP_USE_IP_FROM_FORWARDED_HEADER,
- includeFingerprints=cfg.HTTPS_INCLUDE_FINGERPRINTS)
-
if cfg.RECAPTCHA_ENABLED:
- protected = ReCaptchaProtectedResource(
- recaptchaPrivKey=cfg.RECAPTCHA_SEC_KEY,
- recaptchaPubKey=cfg.RECAPTCHA_PUB_KEY,
- remoteip=cfg.RECAPTCHA_REMOTEIP,
- useForwardedHeader=cfg.HTTP_USE_IP_FROM_FORWARDED_HEADER,
- protectedResource=bridgesResource)
- httpdist.putChild('bridges', protected)
-
+ publicKey = cfg.RECAPTCHA_PUB_KEY
+ secretKey = cfg.RECAPTCHA_SEC_KEY
+ captcha = partial(ReCaptchaProtectedResource,
+ remoteIP=cfg.RECAPTCHA_REMOTEIP)
elif cfg.GIMP_CAPTCHA_ENABLED:
- # Get the HMAC secret key for CAPTCHA challenges and create a new key
- # from it for use on the server:
+ # Get the master HMAC secret key for CAPTCHA challenges, and then
+ # create a new HMAC key from it for use on the server.
captchaKey = crypto.getKey(cfg.GIMP_CAPTCHA_HMAC_KEYFILE)
hmacKey = crypto.getHMAC(captchaKey, "Captcha-Key")
-
# Load or create our encryption keys:
secretKey, publicKey = crypto.getRSAKey(cfg.GIMP_CAPTCHA_RSA_KEYFILE)
-
- protected = GimpCaptchaProtectedResource(
- secretKey=secretKey,
- publicKey=publicKey,
- hmacKey=hmacKey,
- captchaDir=cfg.GIMP_CAPTCHA_DIR,
- useForwardedHeader=cfg.HTTP_USE_IP_FROM_FORWARDED_HEADER,
- protectedResource=bridgesResource)
+ captcha = partial(GimpCaptchaProtectedResource,
+ hmacKey=hmacKey,
+ captchaDir=cfg.GIMP_CAPTCHA_DIR)
+
+ bridges = WebResourceBridges(dist, sched, numBridges,
+ fwdHeaders, includeFingerprints=fprInclude)
+ if captcha:
+ # Protect the 'bridges' page with a CAPTCHA, if configured to do so:
+ protected = captcha(publicKey=publicKey,
+ secretKey=secretKey,
+ useForwardedHeader=fwdHeaders,
+ protectedResource=bridges)
httpdist.putChild('bridges', protected)
+ logging.info("Protecting resources with %s." % captcha.func.__name__)
else:
- httpdist.putChild('bridges', bridgesResource)
+ httpdist.putChild('bridges', bridges)
site = server.Site(httpdist)
if cfg.HTTP_UNENCRYPTED_PORT:
ip = cfg.HTTP_UNENCRYPTED_BIND_IP or ""
+ port = cfg.HTTP_UNENCRYPTED_PORT or 80
try:
- reactor.listenTCP(cfg.HTTP_UNENCRYPTED_PORT, site, interface=ip)
+ reactor.listenTCP(port, site, interface=ip)
except CannotListenError as error:
raise SystemExit(error)
+ logging.info("Started HTTP server on %s:%d" % (str(ip), int(port)))
if cfg.HTTPS_PORT:
- from twisted.internet.ssl import DefaultOpenSSLContextFactory
- #from OpenSSL.SSL import SSLv3_METHOD
ip = cfg.HTTPS_BIND_IP or ""
- factory = DefaultOpenSSLContextFactory(cfg.HTTPS_KEY_FILE,
- cfg.HTTPS_CERT_FILE)
+ port = cfg.HTTPS_PORT or 443
try:
- reactor.listenSSL(cfg.HTTPS_PORT, site, factory, interface=ip)
+ from twisted.internet.ssl import DefaultOpenSSLContextFactory
+ factory = DefaultOpenSSLContextFactory(cfg.HTTPS_KEY_FILE,
+ cfg.HTTPS_CERT_FILE)
+ reactor.listenSSL(port, site, factory, interface=ip)
except CannotListenError as error:
raise SystemExit(error)
+ logging.info("Started HTTPS server on %s:%d" % (str(ip), int(port)))
return site
diff --git a/lib/bridgedb/captcha.py b/lib/bridgedb/captcha.py
index ca2575c..e10bc81 100644
--- a/lib/bridgedb/captcha.py
+++ b/lib/bridgedb/captcha.py
@@ -124,22 +124,28 @@ class Captcha(object):
class ReCaptcha(Captcha):
- """A reCaptcha CAPTCHA.
+ """A CAPTCHA obtained from a remote reCaptcha_ API server.
:ivar str image: The CAPTCHA image.
:ivar str challenge: The ``'recaptcha_challenge_response'`` HTTP form
- field to pass to the client along with the CAPTCHA image.
+ field to pass to the client, along with the CAPTCHA image. See
+ :doc:`BridgeDB's captcha.html <templates/captcha.html>` Mako_ template
+ for an example usage.
+ :ivar str publicKey: The public reCaptcha API key.
+ :ivar str secretKey: The private reCaptcha API key.
+
+ .. _reCaptcha: https://code.google.com/p/recaptcha/
+ .. _Mako: http://docs.makotemplates.org/en/latest/syntax.html#page
"""
- def __init__(self, pubkey=None, privkey=None):
+ def __init__(self, publicKey=None, secretKey=None):
"""Create a new ReCaptcha CAPTCHA.
- :param str pubkey: The public reCaptcha API key.
- :param str privkey: The private reCaptcha API key.
+ :param str publicKey: The public reCaptcha API key.
+ :param str secretKey: The private reCaptcha API key.
"""
- super(ReCaptcha, self).__init__()
- self.pubkey = pubkey
- self.privkey = privkey
+ super(ReCaptcha, self).__init__(publicKey=publicKey,
+ secretKey=secretKey)
def get(self):
"""Retrieve a CAPTCHA from the reCaptcha API server.
@@ -154,11 +160,11 @@ class ReCaptcha(Captcha):
:ivar:`secretKey` are missing.
:raises HTTPError: If the server returned any HTTP error status code.
"""
- if not self.pubkey or not self.privkey:
+ if not self.publicKey or not self.secretKey:
raise CaptchaKeyError('You must supply recaptcha API keys')
urlbase = API_SSL_SERVER
- form = "/noscript?k=%s" % self.pubkey
+ form = "/noscript?k=%s" % self.publicKey
# Extract and store image from recaptcha
html = urllib2.urlopen(urlbase + form).read()
@@ -172,27 +178,45 @@ class ReCaptcha(Captcha):
class GimpCaptcha(Captcha):
- """A cached CAPTCHA image which was created with Gimp."""
+ """A locally cached CAPTCHA image which was created with gimp-captcha_.
+
+ :ivar str secretKey: A PKCS#1 OAEP-padded, private RSA key, used for
+ verifying the client's solution to the CAPTCHA.
+ :ivar str publickey: A PKCS#1 OAEP-padded, public RSA key. This is used to
+ hide the correct CAPTCHA solution within the
+ ``captcha_challenge_field`` HTML form field. That form field is given
+ to the a client along with the :ivar:`image` during the initial
+ CAPTCHA request, and the client *should* give it back to us later
+ during the CAPTCHA solution verification step.
+ :ivar bytes hmacKey: A client-specific HMAC secret key.
+ :ivar str cacheDir: The local directory which pre-generated CAPTCHA images
+ have been stored in. This can be set via the ``GIMP_CAPTCHA_DIR``
+ setting in the config file.
+ :type sched: :class:`bridgedb.schedule.ScheduledInterval`
+ :ivar sched: An time interval. After this much time has passed, the
+ CAPTCHA is considered stale, and all solutions are considered invalid
+ regardless of their correctness.
+
+ .. _gimp-captcha: https://github.com/isislovecruft/gimp-captcha
+ """
- def __init__(self, secretKey=None, publicKey=None, hmacKey=None,
+ def __init__(self, publicKey=None, secretKey=None, hmacKey=None,
cacheDir=None):
"""Create a ``GimpCaptcha`` which retrieves images from **cacheDir**.
- :param str secretkey: A PKCS#1 OAEP-padded, private RSA key, used for
- verifying the client's solution to the CAPTCHA.
:param str publickey: A PKCS#1 OAEP-padded, public RSA key, used for
creating the ``captcha_challenge_field`` string to give to a
client.
+ :param str secretKey: A PKCS#1 OAEP-padded, private RSA key, used for
+ verifying the client's solution to the CAPTCHA.
:param bytes hmacKey: A client-specific HMAC secret key.
:param str cacheDir: The local directory which pre-generated CAPTCHA
images have been stored in. This can be set via the
``GIMP_CAPTCHA_DIR`` setting in the config file.
- :raises GimpCaptchaError: if **cacheDir** is not a directory.
- :raises CaptchaKeyError: if any of **secretKey**, **publicKey**,
- or **hmacKey** is invalid, or missing.
+ :raises GimpCaptchaError: if :ivar:`cacheDir` is not a directory.
+ :raises CaptchaKeyError: if any of :ivar:`secretKey`,
+ :ivar:`publicKey`, or :ivar:`hmacKey` are invalid or missing.
"""
- super(GimpCaptcha, self).__init__()
-
if not cacheDir or not os.path.isdir(cacheDir):
raise GimpCaptchaError("Gimp captcha cache isn't a directory: %r"
% cacheDir)
@@ -201,10 +225,10 @@ class GimpCaptcha(Captcha):
"Invalid key supplied to GimpCaptcha: SK=%r PK=%r HMAC=%r"
% (secretKey, publicKey, hmacKey))
- self.secretKey = secretKey
- self.publicKey = publicKey
- self.cacheDir = cacheDir
+ super(GimpCaptcha, self).__init__(publicKey=publicKey,
+ secretKey=secretKey)
self.hmacKey = hmacKey
+ self.cacheDir = cacheDir
self.answer = None
@classmethod
@@ -215,7 +239,7 @@ class GimpCaptcha(Captcha):
``'captcha_challenge_field'`` HTTP form field.
:param str solution: The client's proposed solution to the CAPTCHA
that they were presented with.
- :param str secretkey: A PKCS#1 OAEP-padded, private RSA key, used for
+ :param str secretKey: A PKCS#1 OAEP-padded, private RSA key, used for
verifying the client's solution to the CAPTCHA.
:param bytes hmacKey: A private key for generating HMACs.
:rtype: bool
@@ -248,22 +272,51 @@ class GimpCaptcha(Captcha):
return False
def createChallenge(self, answer):
- """Encrypt the CAPTCHA **answer** and HMAC the encrypted data.
-
- Take a string containing the answer to a CAPTCHA and encrypts it to
- :attr:`publicKey`. The resulting encrypted blob is then HMACed with a
- client-specific :attr:`hmacKey`. These two strings are then joined
- together in the form:
-
- HMAC ";" ENCRYPTED_ANSWER
-
- where the HMAC MUST be the first 20 bytes. Lastly base64-encoded (in a
- URL safe manner).
+ """Encrypt-then-HMAC the CAPTCHA **answer**.
+
+ A challenge string consists of a URL-safe, base64-encoded string which
+ contains an ``HMAC`` concatenated with an ``ENC_BLOB``, in the
+ following form::
+
+ CHALLENGE := B64( HMAC | ENC_BLOB )
+ ENC_BLOB := RSA_ENC( ANSWER_BLOB )
+ ANSWER_BLOB := ( TIMESTAMP | ANSWER )
+
+ where
+ * ``B64`` is a URL-safe base64-encode function,
+ * ``RSA_ENC`` is the PKCS#1 RSA-OAEP encryption function,
+ * and the remaining feilds are specified as follows:
+
+ +-------------+--------------------------------------------+----------+
+ | Field | Description | Length |
+ +=============+============================================+==========+
+ | HMAC | An HMAC of the ``ENC_BLOB``, created with | 20 bytes |
+ | | the client-specific :ivar:`hmacKey`, by | |
+ | | applying :func:`~crypto.getHMAC` to the | |
+ | | ``ENC_BLOB``. | |
+ +-------------+--------------------------------------------+----------+
+ | ENC_BLOB | An encrypted ``ANSWER``, created with | varies |
+ | | a PKCS#1 OAEP-padded RSA :ivar:`publicKey`.| |
+ +-------------+--------------------------------------------+----------+
+ | ANSWER | A string containing answer to this | 8 bytes |
+ | | CAPTCHA :ivar:`image`. | |
+ +-------------+--------------------------------------------+----------+
+
+ The steps taken to produce a ``CHALLENGE`` are then:
+
+ 1. Encrypt the ``ANSWER`` to :ivar:`publicKey` to create
+ the ``ENC_BLOB``.
+
+ 2. Use the client-specific :ivar:`hmacKey` to apply the
+ :func:`~crypto.getHMAC` function to the ``ENC_BLOB``, obtaining
+ an ``HMAC``.
+
+ 3. Create the final ``CHALLENGE`` string by concatenating the
+ ``HMAC`` and ``ENC_BLOB``, then base64-encoding the result.
:param str answer: The answer to a CAPTCHA.
:rtype: str
- :returns: An HMAC of, as well as a string containing the URL-safe,
- base64-encoded encrypted **answer**.
+ :returns: A challenge string.
"""
encrypted = self.publicKey.encrypt(answer)
hmac = crypto.getHMAC(self.hmacKey, encrypted)
diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py
index 570fe9c..8bc1da7 100644
--- a/lib/bridgedb/test/test_HTTPServer.py
+++ b/lib/bridgedb/test/test_HTTPServer.py
@@ -274,9 +274,9 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase):
# (None, None) is the (distributor, scheduleInterval):
self.protectedResource = HTTPServer.WebResourceBridges(None, None)
self.captchaResource = HTTPServer.ReCaptchaProtectedResource(
- recaptchaPrivKey='42',
- recaptchaPubKey='23',
- remoteip='111.111.111.111',
+ publicKey='23',
+ secretKey='42',
+ remoteIP='111.111.111.111',
useForwardedHeader=True,
protectedResource=self.protectedResource)
@@ -365,7 +365,7 @@ class ReCaptchaProtectedResourceTests(unittest.TestCase):
def test_getRemoteIP_useRandomIP(self):
"""Check that removing our remoteip setting produces a random IP."""
- self.captchaResource.recaptchaRemoteIP = None
+ self.captchaResource.remoteIP = None
ip = self.captchaResource.getRemoteIP()
realishIP = ipaddr.IPv4Address(ip).compressed
self.assertTrue(realishIP)
diff --git a/lib/bridgedb/test/test_captcha.py b/lib/bridgedb/test/test_captcha.py
index a383545..536f29e 100644
--- a/lib/bridgedb/test/test_captcha.py
+++ b/lib/bridgedb/test/test_captcha.py
@@ -50,8 +50,8 @@ class ReCaptchaTests(unittest.TestCase):
def test_init(self):
"""Check the ReCaptcha class stored the private and public keys."""
- self.assertEquals(self.c.privkey, 'sekrit')
- self.assertEquals(self.c.pubkey, 'publik')
+ self.assertEquals(self.c.secretKey, 'sekrit')
+ self.assertEquals(self.c.publicKey, 'publik')
def test_get(self):
"""Test get() method."""
@@ -109,32 +109,32 @@ class GimpCaptchaTests(unittest.TestCase):
a CaptchaKeyError.
"""
self.assertRaises(captcha.CaptchaKeyError, captcha.GimpCaptcha,
- None, self.publik, self.hmacKey, self.cacheDir)
+ self.publik, None, self.hmacKey, self.cacheDir)
def test_init_noPublicKey(self):
"""__init__() without publicKey should raise a CaptchaKeyError."""
self.assertRaises(captcha.CaptchaKeyError, captcha.GimpCaptcha,
- self.sekrit, None, self.hmacKey, self.cacheDir)
+ None, self.sekrit, self.hmacKey, self.cacheDir)
def test_init_noHMACKey(self):
"""__init__() without hmacKey should raise a CaptchaKeyError."""
self.assertRaises(captcha.CaptchaKeyError, captcha.GimpCaptcha,
- self.sekrit, self.publik, None, self.cacheDir)
+ self.publik, self.sekrit, None, self.cacheDir)
def test_init_noCacheDir(self):
"""__init__() without cacheDir should raise a CaptchaKeyError."""
self.assertRaises(captcha.GimpCaptchaError, captcha.GimpCaptcha,
- self.sekrit, self.publik, self.hmacKey, None)
+ self.publik, self.sekrit, self.hmacKey, None)
def test_init_badCacheDir(self):
"""GimpCaptcha with bad cacheDir should raise GimpCaptchaError."""
self.assertRaises(captcha.GimpCaptchaError, captcha.GimpCaptcha,
- self.sekrit, self.publik, self.hmacKey,
+ self.publik, self.sekrit, self.hmacKey,
self.cacheDir.rstrip('chas'))
def test_init(self):
"""Test that __init__ correctly initialised all the values."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
self.assertIsNone(c.answer)
self.assertIsNone(c.image)
@@ -142,14 +142,14 @@ class GimpCaptchaTests(unittest.TestCase):
def test_createChallenge(self):
"""createChallenge() should return the encrypted CAPTCHA answer."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
challenge = c.createChallenge('w00t')
self.assertIsInstance(challenge, basestring)
def test_createChallenge_base64(self):
"""createChallenge() return value should be urlsafe base64-encoded."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
challenge = c.createChallenge('w00t')
decoded = urlsafe_b64decode(challenge)
@@ -157,7 +157,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_createChallenge_hmacValid(self):
"""The HMAC in createChallenge() return value should be valid."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
challenge = c.createChallenge('ShouldHaveAValidHMAC')
decoded = urlsafe_b64decode(challenge)
@@ -168,7 +168,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_createChallenge_decryptedAnswerMatches(self):
"""The HMAC in createChallenge() return value should be valid."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
answer = 'ThisAnswerShouldDecryptToThis'
challenge = c.createChallenge(answer)
@@ -182,7 +182,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_get(self):
"""GimpCaptcha.get() should return image and challenge strings."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
self.assertIsInstance(image, basestring)
@@ -191,7 +191,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_get_emptyCacheDir(self):
"""An empty cacheDir should raise GimpCaptchaError."""
os.makedirs(self.badCacheDir)
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.badCacheDir)
self.assertRaises(captcha.GimpCaptchaError, c.get)
shutil.rmtree(self.badCacheDir)
@@ -205,7 +205,7 @@ class GimpCaptchaTests(unittest.TestCase):
fh.flush()
os.chmod(badFile, 0266)
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.badCacheDir)
# This should hit the second `except:` clause in get():
self.assertRaises(captcha.GimpCaptchaError, c.get)
@@ -213,7 +213,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_check(self):
"""A correct answer and valid challenge should return True."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
self.assertEquals(
@@ -222,7 +222,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_check_blankAnswer(self):
"""A blank answer and valid challenge should return False."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
self.assertEquals(
@@ -231,7 +231,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_check_nonBase64(self):
"""Valid answer and challenge with invalid base64 returns False."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
challengeBadB64 = challenge.rstrip('==') + "\x42\x42\x42"
@@ -244,7 +244,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_check_caseInsensitive_lowercase(self):
"""A correct answer in lowercase characters should return True."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
solution = c.answer.lower()
@@ -254,7 +254,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_check_caseInsensitive_uppercase(self):
"""A correct answer in uppercase characters should return True."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
solution = c.answer.upper()
@@ -264,7 +264,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_check_encoding_utf8(self):
"""A correct answer in utf-8 lowercase should return True."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
solution = c.answer.encode('utf8')
@@ -274,7 +274,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_check_encoding_ascii(self):
"""A correct answer in utf-8 lowercase should return True."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
solution = c.answer.encode('ascii')
@@ -284,7 +284,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_check_encoding_unicode(self):
"""A correct answer in utf-8 lowercase should return True."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
solution = unicode(c.answer)
@@ -294,7 +294,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_check_missingHMACbytes(self):
"""A challenge that is missing part of the HMAC should return False."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
challengeBadHMAC = challenge[:10] + challenge[20:]
@@ -304,7 +304,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_check_missingAnswerbytes(self):
"""Partial encrypted answers in challenges should return False."""
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
challengeBadOrig = challenge[:20] + challenge[30:]
@@ -315,7 +315,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_check_badHMACkey(self):
"""A challenge with a bad HMAC key should return False."""
hmacKeyBad = crypto.getKey('test_gimpCaptcha_badHMACkey')
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
self.assertEquals(
@@ -325,7 +325,7 @@ class GimpCaptchaTests(unittest.TestCase):
def test_check_badRSAkey(self):
"""A challenge with a bad RSA secret key should return False."""
secretKeyBad, publicKeyBad = crypto.getRSAKey('test_gimpCaptcha_badRSAkey')
- c = captcha.GimpCaptcha(self.sekrit, self.publik, self.hmacKey,
+ c = captcha.GimpCaptcha(self.publik, self.sekrit, self.hmacKey,
self.cacheDir)
image, challenge = c.get()
self.assertEquals(
1
0
[bridgedb/master] Make publicKey and secretKey attributes of the ICaptcha interface.
by isis@torproject.org 16 May '14
by isis@torproject.org 16 May '14
16 May '14
commit a8f35253e47bc47f0f3ca763f29a51224da47d55
Author: Isis Lovecruft <isis(a)torproject.org>
Date: Wed May 14 20:45:09 2014 +0000
Make publicKey and secretKey attributes of the ICaptcha interface.
Both the reCaptcha and GimpCaptcha subclasses of the generic base
implementation, bridgedb.captcha.Captcha, of the ICaptcha interface have
publicKey and secretKey attributes. In fact, it would be hard to
generate a secret CAPTCHA challenge_string which was retrievable later
if there weren't any keypairs involved. Ergo, the keypair should be part
of the interface specification.
---
lib/bridgedb/captcha.py | 17 ++++++++++++++---
1 file changed, 14 insertions(+), 3 deletions(-)
diff --git a/lib/bridgedb/captcha.py b/lib/bridgedb/captcha.py
index 8a76198..f5674c4 100644
--- a/lib/bridgedb/captcha.py
+++ b/lib/bridgedb/captcha.py
@@ -82,6 +82,11 @@ class ICaptcha(Interface):
"A string containing the contents of a CAPTCHA image file.")
challenge = Attribute(
"A unique string associated with the dispursal of this CAPTCHA.")
+ publicKey = Attribute(
+ "A public key used for encrypting CAPTCHA challenge strings.")
+ secretKey = Attribute(
+ "A private key used for decrypting challenge strings during CAPTCHA"
+ "solution verification.")
def get():
"""Retrieve a new CAPTCHA image."""
@@ -92,15 +97,21 @@ class Captcha(object):
:ivar str image: The CAPTCHA image.
:ivar str challenge: A challenge string which should permit checking of
- the client's CAPTCHA solution in some manner. This should be passed
- along to the client with the CAPTCHA image.
+ the client's CAPTCHA solution in some manner. In stateless protocols
+ such as HTTP, this should be passed along to the client with the
+ CAPTCHA image.
+ :ivar publicKey: A public key used for encrypting CAPTCHA challenge strings.
+ :ivar secretKey: A private key used for decrypting challenge strings during
+ CAPTCHA solution verification.
"""
implements(ICaptcha)
- def __init__(self):
+ def __init__(self, publicKey=None, secretKey=None):
"""Obtain a new CAPTCHA for a client."""
self.image = None
self.challenge = None
+ self.publicKey = publicKey
+ self.secretKey = secretKey
def get(self):
return self.image
1
0
[bridgedb/master] Revise bridgedb.Time.Schedule to use a zope.interface.
by isis@torproject.org 16 May '14
by isis@torproject.org 16 May '14
16 May '14
commit fb7492d021e6037e8ef7452ac248bed84314d8f9
Author: Isis Lovecruft <isis(a)torproject.org>
Date: Mon May 12 21:23:29 2014 +0000
Revise bridgedb.Time.Schedule to use a zope.interface.
* REMOVE old-style class bridgedb.Time.Schedule.
* ADD zope.interface.Interface specification, bridgedb.Time.ISchedule.
* ADD bridgedb.Time.ScheduleBase class that implements the ISchedule
interface and does what the original bridgedb.Time.Schedule class was
supposed to do.
---
lib/bridgedb/Time.py | 40 ++++++++++++++++++++++++++++++++--------
1 file changed, 32 insertions(+), 8 deletions(-)
diff --git a/lib/bridgedb/Time.py b/lib/bridgedb/Time.py
index 2b7b02b..6062b98 100644
--- a/lib/bridgedb/Time.py
+++ b/lib/bridgedb/Time.py
@@ -12,17 +12,41 @@
import calendar
import time
+from zope import interface
+from zope.interface import implements
+
KNOWN_INTERVALS = [ "hour", "day", "week", "month" ]
-class Schedule:
+
+class ISchedule(interface.Interface):
+ """A ``Interface`` specification for a Schedule."""
+
+ def intervalStart(when):
+ """Set the start time of the current interval to **when**."""
+
+ def getInterval(when=None):
+ """Get the interval which includes an arbitrary **when**."""
+
+ def nextIntervalStarts():
+ """Get the start time for the next interval."""
+
+
+class ScheduleBase(object):
+ """Base class for all ``Schedule`` classes."""
+
+ implements(ISchedule)
+
def intervalStart(self, when):
- raise NotImplementedError
- def getInterval(self, when):
- raise NotImplementedError
- def nextIntervalStarts(self, when):
- raise NotImplementedError
+ pass
+
+ def getInterval(self, when=None):
+ pass
+
+ def nextIntervalStarts(self):
+ pass
+
-class IntervalSchedule(Schedule):
+class IntervalSchedule(ScheduleBase):
"""An IntervalSchedule splits time into somewhat natural periods,
based on hours, days, weeks, or months.
"""
@@ -118,7 +142,7 @@ class IntervalSchedule(Schedule):
elif self.itype == 'hour':
return self.intervalStart(when) + 3600 * self.count
-class NoSchedule(Schedule):
+class NoSchedule(ScheduleBase):
"""A stub-implementation of Schedule that has only one period for
all time."""
def __init__(self):
1
0
[bridgedb/master] Tell twisted.web.server.Site not to display tracebacks.
by isis@torproject.org 16 May '14
by isis@torproject.org 16 May '14
16 May '14
commit 5ccdda5c5ba6b4dd3462ef4038a8d4e809d630cd
Author: Isis Lovecruft <isis(a)torproject.org>
Date: Wed May 14 21:35:55 2014 +0000
Tell twisted.web.server.Site not to display tracebacks.
---
lib/bridgedb/HTTPServer.py | 1 +
1 file changed, 1 insertion(+)
diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py
index ead6d60..b436df2 100644
--- a/lib/bridgedb/HTTPServer.py
+++ b/lib/bridgedb/HTTPServer.py
@@ -906,6 +906,7 @@ def addWebServer(cfg, dist, sched):
httpdist.putChild('bridges', bridges)
site = server.Site(httpdist)
+ site.displayTracebacks = False
if cfg.HTTP_UNENCRYPTED_PORT:
ip = cfg.HTTP_UNENCRYPTED_BIND_IP or ""
1
0
16 May '14
commit 9068b5c430f95f448239b8e604925309bb9afd3e
Author: Isis Lovecruft <isis(a)torproject.org>
Date: Mon May 12 22:03:37 2014 +0000
Sphinxify docstrings in bridgedb.Time.
---
lib/bridgedb/Time.py | 42 ++++++++++++++++++++++++++----------------
1 file changed, 26 insertions(+), 16 deletions(-)
diff --git a/lib/bridgedb/Time.py b/lib/bridgedb/Time.py
index 6062b98..707bf9b 100644
--- a/lib/bridgedb/Time.py
+++ b/lib/bridgedb/Time.py
@@ -47,17 +47,21 @@ class ScheduleBase(object):
class IntervalSchedule(ScheduleBase):
- """An IntervalSchedule splits time into somewhat natural periods,
- based on hours, days, weeks, or months.
+ """An IntervalSchedule splits time into somewhat natural periods, based on
+ hours, days, weeks, or months.
+
+ :ivar str itype: One of "month", "day", "hour".
+ :ivar int count: How many of the units in :ivar:`itype` belong to each period.
"""
- ## Fields:
- ## itype -- one of "month", "day", "hour".
- ## count -- how many of the units in itype belong to each period.
+
def __init__(self, intervaltype, count):
- """Create a new IntervalSchedule.
- intervaltype -- one of month, week, day, hour.
- count -- how many of the units in intervaltype belong to each
- period.
+ """Divide time into intervals of **count** number of **intervaltype**.
+
+ :param str intervaltype: One of ``'month'``, ``'week'``, ``'day'``,
+ or ``'hour'``.
+
+ :param int count: How many of the units in **intervaltype** belong to
+ each period.
"""
it = intervaltype.lower()
if it.endswith("s"): it = it[:-1]
@@ -71,8 +75,12 @@ class IntervalSchedule(ScheduleBase):
self.count = count
def intervalStart(self, when):
- """Return the time (as an int) of the start of the interval containing
- 'when'."""
+ """Get the start time of the interval that contains **when**.
+
+ :rtype: int
+ :returns: The Unix epoch timestamp for the start time of the interval
+ that contains **when**.
+ """
if self.itype == 'month':
# For months, we always start at the beginning of the month.
tm = time.gmtime(when)
@@ -92,8 +100,7 @@ class IntervalSchedule(ScheduleBase):
assert False
def getInterval(self, when):
- """Return a string representing the interval that contains the time
- **when**.
+ """Get the interval that contains the time **when**.
>>> import calendar
>>> from bridgedb.Time import IntervalSchedule
@@ -142,15 +149,18 @@ class IntervalSchedule(ScheduleBase):
elif self.itype == 'hour':
return self.intervalStart(when) + 3600 * self.count
+
class NoSchedule(ScheduleBase):
- """A stub-implementation of Schedule that has only one period for
- all time."""
+ """A Schedule that has only one period for all time."""
+
def __init__(self):
pass
+
def intervalStart(self, when):
return 0
+
def getInterval(self, when):
return "1970"
+
def nextIntervalStarts(self, when):
return 2147483647L # INT32_MAX
-
1
0
[bridgedb/master] Move lib/bridgedb/Time.py → lib/bridgedb/schedule.py.
by isis@torproject.org 16 May '14
by isis@torproject.org 16 May '14
16 May '14
commit e35194ecc67f40e69635fa70adee7331471de337
Author: Isis Lovecruft <isis(a)torproject.org>
Date: Tue May 13 23:19:06 2014 +0000
Move lib/bridgedb/Time.py → lib/bridgedb/schedule.py.
---
lib/bridgedb/HTTPServer.py | 6 +-
lib/bridgedb/Main.py | 10 +-
lib/bridgedb/Tests.py | 4 +-
lib/bridgedb/Time.py | 266 -------------------------------
lib/bridgedb/email/server.py | 4 +-
lib/bridgedb/schedule.py | 267 ++++++++++++++++++++++++++++++++
lib/bridgedb/test/test_HTTPServer.py | 4 +-
lib/bridgedb/test/test_email_server.py | 6 +-
8 files changed, 284 insertions(+), 283 deletions(-)
diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py
index b436df2..8289be3 100644
--- a/lib/bridgedb/HTTPServer.py
+++ b/lib/bridgedb/HTTPServer.py
@@ -481,7 +481,7 @@ class ReCaptchaProtectedResource(CaptchaProtectedResource):
``'captcha_response_field'``. These POST arguments should be
obtained from :meth:`render_GET`.
:rtupe: :api:`twisted.internet.defer.Deferred`
- :returns: A deferred wich will callback with a tuple in the following
+ :returns: A deferred which will callback with a tuple in the following
form:
(:type:`bool`, :api:`twisted.web.server.Request`)
If the CAPTCHA solution was valid, a tuple will contain::
@@ -619,7 +619,7 @@ class WebResourceBridges(resource.Resource):
:type distributor: :class:`IPBasedDistributor`
:param distributor: The mechanism to retrieve bridges for this
distributor.
- :type schedule: :class:`IntervalSchedule`
+ :type schedule: :class:`~bridgedb.schedule.ScheduledInterval`
:param schedule: The time period used to tweak the bridge selection
procedure.
:param int N: The number of bridges to hand out per query.
@@ -669,7 +669,7 @@ class WebResourceBridges(resource.Resource):
:returns: A plaintext or HTML response to serve.
"""
# XXX why are we getting the interval if our distributor might be
- # using bridgedb.Time.NoSchedule?
+ # using bridgedb.schedule.Unscheduled?
interval = self.schedule.getInterval(time.time())
bridges = ( )
ip = None
diff --git a/lib/bridgedb/Main.py b/lib/bridgedb/Main.py
index 1b4420e..ccc844d 100644
--- a/lib/bridgedb/Main.py
+++ b/lib/bridgedb/Main.py
@@ -20,12 +20,12 @@ from twisted.internet import reactor
from bridgedb import crypto
from bridgedb import persistent
from bridgedb import safelog
+from bridgedb import schedule
from bridgedb import util
from bridgedb.parse import options
import bridgedb.Bridges as Bridges
import bridgedb.Dist as Dist
-import bridgedb.Time as Time
import bridgedb.Storage
@@ -590,12 +590,12 @@ def startup(options):
# Configure all servers:
if config.HTTPS_DIST and config.HTTPS_SHARE:
- #webSchedule = Time.IntervalSchedule("day", 2)
- webSchedule = Time.NoSchedule()
+ #webSchedule = schedule.ScheduledInterval("day", 2)
+ webSchedule = schedule.Unscheduled()
HTTPServer.addWebServer(config, ipDistributor, webSchedule)
if config.EMAIL_DIST and config.EMAIL_SHARE:
- #emailSchedule = Time.IntervalSchedule("day", 1)
- emailSchedule = Time.NoSchedule()
+ #emailSchedule = schedule.ScheduledInterval("day", 1)
+ emailSchedule = schedule.Unscheduled()
addSMTPServer(config, emailDistributor, emailSchedule)
# Actually run the servers.
diff --git a/lib/bridgedb/Tests.py b/lib/bridgedb/Tests.py
index 6fcdbc6..219802b 100644
--- a/lib/bridgedb/Tests.py
+++ b/lib/bridgedb/Tests.py
@@ -17,7 +17,7 @@ from datetime import datetime
import bridgedb.Bridges
import bridgedb.Main
import bridgedb.Dist
-import bridgedb.Time
+import bridgedb.schedule
import bridgedb.Storage
import re
import ipaddr
@@ -768,7 +768,7 @@ def testSuite():
for module in [ bridgedb.Bridges,
bridgedb.Main,
bridgedb.Dist,
- bridgedb.Time ]:
+ bridgedb.schedule ]:
suite.addTest(doctest.DocTestSuite(module))
return suite
diff --git a/lib/bridgedb/Time.py b/lib/bridgedb/Time.py
deleted file mode 100644
index 4c4a2e2..0000000
--- a/lib/bridgedb/Time.py
+++ /dev/null
@@ -1,266 +0,0 @@
-# -*- coding: utf-8 ; test-case-name: bridgedb.test.test_Time -*-
-#
-# This file is part of BridgeDB, a Tor bridge distribution system.
-#
-# :authors: Nick Mathewson
-# :copyright: (c) 2007-2014, The Tor Project, Inc.
-# :license: see LICENSE for licensing information
-
-
-"""This module implements functions for dividing time into chunks."""
-
-import calendar
-
-from datetime import datetime
-
-from zope import interface
-from zope.interface import implements
-from zope.interface import Attribute
-
-
-#: The known time intervals (or *periods*) for dividing time by.
-KNOWN_INTERVALS = ["second", "minute", "hour", "day", "week", "month"]
-
-
-class UnknownInterval(ValueError):
- """Raised if an interval isn't one of the :data:`KNOWN_INTERVALS`."""
-
-
-def toUnixSeconds(timestruct):
- """Convert a datetime struct to a Unix timestamp in seconds.
-
- :param timestruct: A ``datetime.datetime`` object to convert into a
- timestamp in Unix Era seconds.
- :rtype: int
- """
- return calendar.timegm(timestruct)
-
-def fromUnixSeconds(timestamp):
- """Convert a Unix timestamp to a datetime struct.
-
- :param int timestamp: A timestamp in Unix Era seconds.
- :rtype: :type:`datetime.datetime`
- """
- return datetime.fromtimestamp(timestamp)
-
-
-class ISchedule(interface.Interface):
- """A ``Interface`` specification for a Schedule."""
-
- intervalPeriod = Attribute(
- "The type of period which this Schedule's intervals will rotate by.")
- intervalCount = Attribute(
- "Number of **intervalPeriod**s before rotation to the next interval")
-
- def intervalStart(when=None):
- """Get the start time of the interval that contains **when**."""
-
- def getInterval(when=None):
- """Get the interval which includes an arbitrary **when**."""
-
- def nextIntervalStarts(when=None):
- """Get the start of the interval after the one containing **when**."""
-
-
-class Unscheduled(object):
- """A base ``Schedule`` that has only one period that contains all time."""
-
- implements(ISchedule)
-
- def __init__(self, period=None, count=None):
- """Create a schedule for dividing time into intervals.
-
- :param str period: One of the periods in :data:`KNOWN_INTERVALS`.
- :param int count: The number of **period**s in an interval.
- """
- self.intervalCount = count
- self.intervalPeriod = period
-
- def intervalStart(self, when=0):
- """Get the start time of the interval that contains **when**.
-
- :param int when: The time which we're trying to find the corresponding
- interval for.
- :rtype: int
- :returns: The Unix epoch timestamp for the start time of the interval
- that contains **when**.
- """
- return toUnixSeconds(datetime.min.timetuple())
-
- def getInterval(self, when=0):
- """Get the interval that contains the time **when**.
-
- :param int when: The time which we're trying to find the corresponding
- interval for.
- :rtype: str
- :returns: A timestamp in the form ``YEAR-MONTH[-DAY[-HOUR]]``. It's
- specificity depends on what type of interval we're using. For
- example, if using ``"month"``, the return value would be something
- like ``"2013-12"``.
- """
- return fromUnixSeconds(when).strftime('%04Y-%02m-%02d %02H:%02M:%02S')
-
- def nextIntervalStarts(self, when=0):
- """Return the start time of the interval starting _after_ when.
-
- :rtype: int
- :returns: Return the Y10K bug.
- """
- return toUnixSeconds(datetime.max.timetuple())
-
-
-class ScheduledInterval(Unscheduled):
- """An class that splits time into periods, based on seconds, minutes,
- hours, days, weeks, or months.
-
- :ivar str intervalPeriod: One of the :data:`KNOWN_INTERVALS`.
- :ivar int intervalCount: The number of times **intervalPeriod** should be
- repeated within an interval.
- """
- implements(ISchedule)
-
- def __init__(self, period=None, count=None):
- """Create a schedule for dividing time into intervals.
-
- :param str period: One of the periods in :data:`KNOWN_INTERVALS`.
- :param int count: The number of **period**s in an interval.
- """
- super(ScheduledInterval, self).__init__(period, count)
- self._setIntervalCount(count)
- self._setIntervalPeriod(period)
-
- def _setIntervalCount(self, count=None):
- """Set our :ivar:`intervalCount`.
-
- .. attention:: This method should be called _before_
- :meth:`_setIntervalPeriod`, because the latter may change the
- count, if it decides to change the period (for example, to
- simplify things by changing weeks into days).
-
- :param int count: The number of times the :ivar:`intervalPeriod`
- should be repeated during the interval. Defaults to ``1``.
- :raises UnknownInterval: if the specified **count** was invalid.
- """
- try:
- if not count > 0:
- count = 1
- count = int(count)
- except (TypeError, ValueError):
- raise UnknownInterval("%s.intervalCount: %r ist not an integer."
- % (self.__class__.__name__, count))
- self.intervalCount = count
-
- def _setIntervalPeriod(self, period=None):
- """Set our :ivar:`intervalPeriod`.
-
- :param str period: One of the :data:`KNOWN_INTERVALS`, or its
- plural. Defaults to ``'hour'``.
- :raises UnknownInterval: if the specified **period** is unknown.
- """
- if not period:
- period = 'hour'
- try:
- period = period.lower()
- # Depluralise the period if necessary, i.e., "months" -> "month".
- if period.endswith('s'):
- period = period[:-1]
-
- if not period in KNOWN_INTERVALS:
- raise ValueError
- except (TypeError, AttributeError, ValueError):
- raise UnknownInterval("%s doesn't know about the %r interval type."
- % (self.__class__.__name__, period))
- self.intervalPeriod = period
-
- if period == 'week':
- self.intervalPeriod = 'day'
- self.intervalCount *= 7
-
- def intervalStart(self, when=0):
- """Get the start time of the interval that contains **when**.
-
- :param int when: The time which we're trying to determine the start of
- interval that contains it. This should be given in Unix seconds,
- for example, taken from :func:`calendar.timegm`.
- :rtype: int
- :returns: The Unix epoch timestamp for the start time of the interval
- that contains **when**.
- """
- if self.intervalPeriod == 'month':
- # For months, we always start at the beginning of the month.
- date = fromUnixSeconds(when)
- months = (date.year * 12) + (date.month - 1)
- months -= (months % self.intervalCount)
- month = months % 12 + 1
- return toUnixSeconds((months // 12, month, 1, 0, 0, 0))
- elif self.intervalPeriod == 'day':
- # For days, we start at the beginning of a day.
- when -= when % (86400 * self.intervalCount)
- return when
- elif self.intervalPeriod == 'hour':
- # For hours, we start at the beginning of an hour.
- when -= when % (3600 * self.intervalCount)
- return when
- elif self.intervalPeriod == 'minute':
- when -= when % (60 * self.intervalCount)
- return when
- elif self.intervalPeriod == 'second':
- when -= when % self.intervalCount
- return when
-
- def getInterval(self, when=0):
- """Get the interval that contains the time **when**.
-
- >>> import calendar
- >>> from bridgedb.Time import ScheduledInterval
- >>> sched = ScheduledInterval('month', 1)
- >>> when = calendar.timegm((2007, 12, 12, 0, 0, 0))
- >>> sched.getInterval(when)
- '2007-12'
- >>> then = calendar.timegm((2014, 05, 13, 20, 25, 13))
- >>> sched.getInterval(then)
- '2014-05'
-
- :param int when: The time which we're trying to find the corresponding
- interval for. Given in Unix seconds, for example, taken from
- :func:`calendar.timegm`.
- :rtype: str
- :returns: A timestamp in the form ``YEAR-MONTH[-DAY[-HOUR]]``. It's
- specificity depends on what type of interval we're using. For
- example, if using ``"month"``, the return value would be something
- like ``"2013-12"``.
- """
- date = fromUnixSeconds(self.intervalStart(when))
-
- fstr = "%04Y-%02m"
- if self.intervalPeriod != 'month':
- fstr += "-%02d"
- if self.intervalPeriod != 'day':
- fstr += " %02H"
- if self.intervalPeriod != 'hour':
- fstr += ":%02M"
- if self.intervalPeriod == 'minute':
- fstr += ":%02S"
-
- return date.strftime(fstr)
-
- def nextIntervalStarts(self, when=0):
- """Return the start time of the interval starting _after_ when.
-
- :returns: The Unix epoch timestamp for the start time of the interval
- that contains **when**.
- """
- seconds = self.intervalStart(when)
-
- if self.intervalPeriod == 'month':
- date = fromUnixSeconds(seconds)
- months = date.month + self.intervalCount
- return toUnixSeconds((date.year, months, 1, 0, 0, 0))
- elif self.intervalPeriod == 'day':
- return seconds + (86400 * self.intervalCount)
- elif self.intervalPeriod == 'hour':
- return seconds + (3600 * self.intervalCount)
- elif self.intervalPeriod == 'minute':
- return seconds + (60 * self.intervalCount)
- elif self.intervalPeriod == 'second':
- return seconds + self.intervalCount
diff --git a/lib/bridgedb/email/server.py b/lib/bridgedb/email/server.py
index 678c154..e963e61 100644
--- a/lib/bridgedb/email/server.py
+++ b/lib/bridgedb/email/server.py
@@ -212,7 +212,7 @@ class MailContext(object):
:type config: :class:`bridgedb.persistent.Conf`
:type distributor: :class:`bridgedb.Dist.EmailBasedDistributor`.
:param distributor: DOCDOC
- :type schedule: :class:`bridgedb.Time.IntervalSchedule`.
+ :type schedule: :class:`bridgedb.schedule.ScheduledInterval`.
:param schedule: DOCDOC
"""
self.config = config
@@ -740,7 +740,7 @@ def addServer(config, distributor, schedule):
:type distributor: :class:`bridgedb.Dist.EmailBasedDistributor`
:param dist: A distributor which will handle database interactions, and
will decide which bridges to give to who and when.
- :type schedule: :class:`bridgedb.Time.IntervalSchedule`
+ :type schedule: :class:`bridgedb.schedule.ScheduledInterval`
:param schedule: The schedule. XXX: Is this even used?
"""
context = MailContext(config, distributor, schedule)
diff --git a/lib/bridgedb/schedule.py b/lib/bridgedb/schedule.py
new file mode 100644
index 0000000..6cef1a6
--- /dev/null
+++ b/lib/bridgedb/schedule.py
@@ -0,0 +1,267 @@
+# -*- coding: utf-8 ; test-case-name: bridgedb.test.test_schedule -*-
+#
+# This file is part of BridgeDB, a Tor bridge distribution system.
+#
+# :authors: Nick Mathewson
+# Isis Lovecruft <isis(a)torproject.org> 0xa3adb67a2cdb8b35
+# :copyright: (c) 2007-2014, The Tor Project, Inc.
+# (c) 2014, Isis Lovecruft
+# :license: see LICENSE for licensing information
+
+"""This module implements functions for dividing time into chunks."""
+
+import calendar
+
+from datetime import datetime
+
+from zope import interface
+from zope.interface import implements
+from zope.interface import Attribute
+
+
+#: The known time intervals (or *periods*) for dividing time by.
+KNOWN_INTERVALS = ["second", "minute", "hour", "day", "week", "month"]
+
+
+class UnknownInterval(ValueError):
+ """Raised if an interval isn't one of the :data:`KNOWN_INTERVALS`."""
+
+
+def toUnixSeconds(timestruct):
+ """Convert a datetime struct to a Unix timestamp in seconds.
+
+ :param timestruct: A ``datetime.datetime`` object to convert into a
+ timestamp in Unix Era seconds.
+ :rtype: int
+ """
+ return calendar.timegm(timestruct)
+
+def fromUnixSeconds(timestamp):
+ """Convert a Unix timestamp to a datetime struct.
+
+ :param int timestamp: A timestamp in Unix Era seconds.
+ :rtype: :type:`datetime.datetime`
+ """
+ return datetime.fromtimestamp(timestamp)
+
+
+class ISchedule(interface.Interface):
+ """A ``Interface`` specification for a Schedule."""
+
+ intervalPeriod = Attribute(
+ "The type of period which this Schedule's intervals will rotate by.")
+ intervalCount = Attribute(
+ "Number of **intervalPeriod**s before rotation to the next interval")
+
+ def intervalStart(when=None):
+ """Get the start time of the interval that contains **when**."""
+
+ def getInterval(when=None):
+ """Get the interval which includes an arbitrary **when**."""
+
+ def nextIntervalStarts(when=None):
+ """Get the start of the interval after the one containing **when**."""
+
+
+class Unscheduled(object):
+ """A base ``Schedule`` that has only one period that contains all time."""
+
+ implements(ISchedule)
+
+ def __init__(self, period=None, count=None):
+ """Create a schedule for dividing time into intervals.
+
+ :param str period: One of the periods in :data:`KNOWN_INTERVALS`.
+ :param int count: The number of **period**s in an interval.
+ """
+ self.intervalCount = count
+ self.intervalPeriod = period
+
+ def intervalStart(self, when=0):
+ """Get the start time of the interval that contains **when**.
+
+ :param int when: The time which we're trying to find the corresponding
+ interval for.
+ :rtype: int
+ :returns: The Unix epoch timestamp for the start time of the interval
+ that contains **when**.
+ """
+ return toUnixSeconds(datetime.min.timetuple())
+
+ def getInterval(self, when=0):
+ """Get the interval that contains the time **when**.
+
+ :param int when: The time which we're trying to find the corresponding
+ interval for.
+ :rtype: str
+ :returns: A timestamp in the form ``YEAR-MONTH[-DAY[-HOUR]]``. It's
+ specificity depends on what type of interval we're using. For
+ example, if using ``"month"``, the return value would be something
+ like ``"2013-12"``.
+ """
+ return fromUnixSeconds(when).strftime('%04Y-%02m-%02d %02H:%02M:%02S')
+
+ def nextIntervalStarts(self, when=0):
+ """Return the start time of the interval starting _after_ when.
+
+ :rtype: int
+ :returns: Return the Y10K bug.
+ """
+ return toUnixSeconds(datetime.max.timetuple())
+
+
+class ScheduledInterval(Unscheduled):
+ """An class that splits time into periods, based on seconds, minutes,
+ hours, days, weeks, or months.
+
+ :ivar str intervalPeriod: One of the :data:`KNOWN_INTERVALS`.
+ :ivar int intervalCount: The number of times **intervalPeriod** should be
+ repeated within an interval.
+ """
+ implements(ISchedule)
+
+ def __init__(self, period=None, count=None):
+ """Create a schedule for dividing time into intervals.
+
+ :param str period: One of the periods in :data:`KNOWN_INTERVALS`.
+ :param int count: The number of **period**s in an interval.
+ """
+ super(ScheduledInterval, self).__init__(period, count)
+ self._setIntervalCount(count)
+ self._setIntervalPeriod(period)
+
+ def _setIntervalCount(self, count=None):
+ """Set our :ivar:`intervalCount`.
+
+ .. attention:: This method should be called _before_
+ :meth:`_setIntervalPeriod`, because the latter may change the
+ count, if it decides to change the period (for example, to
+ simplify things by changing weeks into days).
+
+ :param int count: The number of times the :ivar:`intervalPeriod`
+ should be repeated during the interval. Defaults to ``1``.
+ :raises UnknownInterval: if the specified **count** was invalid.
+ """
+ try:
+ if not count > 0:
+ count = 1
+ count = int(count)
+ except (TypeError, ValueError):
+ raise UnknownInterval("%s.intervalCount: %r ist not an integer."
+ % (self.__class__.__name__, count))
+ self.intervalCount = count
+
+ def _setIntervalPeriod(self, period=None):
+ """Set our :ivar:`intervalPeriod`.
+
+ :param str period: One of the :data:`KNOWN_INTERVALS`, or its
+ plural. Defaults to ``'hour'``.
+ :raises UnknownInterval: if the specified **period** is unknown.
+ """
+ if not period:
+ period = 'hour'
+ try:
+ period = period.lower()
+ # Depluralise the period if necessary, i.e., "months" -> "month".
+ if period.endswith('s'):
+ period = period[:-1]
+
+ if not period in KNOWN_INTERVALS:
+ raise ValueError
+ except (TypeError, AttributeError, ValueError):
+ raise UnknownInterval("%s doesn't know about the %r interval type."
+ % (self.__class__.__name__, period))
+ self.intervalPeriod = period
+
+ if period == 'week':
+ self.intervalPeriod = 'day'
+ self.intervalCount *= 7
+
+ def intervalStart(self, when=0):
+ """Get the start time of the interval that contains **when**.
+
+ :param int when: The time which we're trying to determine the start of
+ interval that contains it. This should be given in Unix seconds,
+ for example, taken from :func:`calendar.timegm`.
+ :rtype: int
+ :returns: The Unix epoch timestamp for the start time of the interval
+ that contains **when**.
+ """
+ if self.intervalPeriod == 'month':
+ # For months, we always start at the beginning of the month.
+ date = fromUnixSeconds(when)
+ months = (date.year * 12) + (date.month - 1)
+ months -= (months % self.intervalCount)
+ month = months % 12 + 1
+ return toUnixSeconds((months // 12, month, 1, 0, 0, 0))
+ elif self.intervalPeriod == 'day':
+ # For days, we start at the beginning of a day.
+ when -= when % (86400 * self.intervalCount)
+ return when
+ elif self.intervalPeriod == 'hour':
+ # For hours, we start at the beginning of an hour.
+ when -= when % (3600 * self.intervalCount)
+ return when
+ elif self.intervalPeriod == 'minute':
+ when -= when % (60 * self.intervalCount)
+ return when
+ elif self.intervalPeriod == 'second':
+ when -= when % self.intervalCount
+ return when
+
+ def getInterval(self, when=0):
+ """Get the interval that contains the time **when**.
+
+ >>> import calendar
+ >>> from bridgedb.schedule import ScheduledInterval
+ >>> sched = ScheduledInterval('month', 1)
+ >>> when = calendar.timegm((2007, 12, 12, 0, 0, 0))
+ >>> sched.getInterval(when)
+ '2007-12'
+ >>> then = calendar.timegm((2014, 05, 13, 20, 25, 13))
+ >>> sched.getInterval(then)
+ '2014-05'
+
+ :param int when: The time which we're trying to find the corresponding
+ interval for. Given in Unix seconds, for example, taken from
+ :func:`calendar.timegm`.
+ :rtype: str
+ :returns: A timestamp in the form ``YEAR-MONTH[-DAY[-HOUR]]``. It's
+ specificity depends on what type of interval we're using. For
+ example, if using ``"month"``, the return value would be something
+ like ``"2013-12"``.
+ """
+ date = fromUnixSeconds(self.intervalStart(when))
+
+ fstr = "%04Y-%02m"
+ if self.intervalPeriod != 'month':
+ fstr += "-%02d"
+ if self.intervalPeriod != 'day':
+ fstr += " %02H"
+ if self.intervalPeriod != 'hour':
+ fstr += ":%02M"
+ if self.intervalPeriod == 'minute':
+ fstr += ":%02S"
+
+ return date.strftime(fstr)
+
+ def nextIntervalStarts(self, when=0):
+ """Return the start time of the interval starting _after_ when.
+
+ :returns: The Unix epoch timestamp for the start time of the interval
+ that contains **when**.
+ """
+ seconds = self.intervalStart(when)
+
+ if self.intervalPeriod == 'month':
+ date = fromUnixSeconds(seconds)
+ months = date.month + self.intervalCount
+ return toUnixSeconds((date.year, months, 1, 0, 0, 0))
+ elif self.intervalPeriod == 'day':
+ return seconds + (86400 * self.intervalCount)
+ elif self.intervalPeriod == 'hour':
+ return seconds + (3600 * self.intervalCount)
+ elif self.intervalPeriod == 'minute':
+ return seconds + (60 * self.intervalCount)
+ elif self.intervalPeriod == 'second':
+ return seconds + self.intervalCount
diff --git a/lib/bridgedb/test/test_HTTPServer.py b/lib/bridgedb/test/test_HTTPServer.py
index 8bc1da7..91ab17e 100644
--- a/lib/bridgedb/test/test_HTTPServer.py
+++ b/lib/bridgedb/test/test_HTTPServer.py
@@ -29,7 +29,7 @@ from twisted.web.resource import Resource
from twisted.web.test import requesthelper
from bridgedb import HTTPServer
-from bridgedb.Time import IntervalSchedule
+from bridgedb.schedule import ScheduledInterval
# For additional logger output for debugging, comment out the following:
@@ -518,7 +518,7 @@ class WebResourceBridgesTests(unittest.TestCase):
self.root = Resource()
self.dist = DummyIPBasedDistributor()
- self.sched = IntervalSchedule('hour', 1)
+ self.sched = ScheduledInterval('hour', 1)
self.nBridgesPerRequest = 2
self.bridgesResource = HTTPServer.WebResourceBridges(
self.dist, self.sched, N=2,
diff --git a/lib/bridgedb/test/test_email_server.py b/lib/bridgedb/test/test_email_server.py
index b7e12c6..23c65b8 100644
--- a/lib/bridgedb/test/test_email_server.py
+++ b/lib/bridgedb/test/test_email_server.py
@@ -21,9 +21,9 @@ import types
from bridgedb.Dist import EmailBasedDistributor
from bridgedb.email import server
-from bridgedb.Time import NoSchedule
from bridgedb.parse.addr import BadEmail
from bridgedb.persistent import Conf
+from bridgedb.schedule import Unscheduled
from bridgedb.test.test_HTTPServer import DummyBridge
from bridgedb.test.util import fileCheckDecorator
@@ -73,7 +73,7 @@ def _createMailContext(config=None, distributor=None):
domainmap=config.EMAIL_DOMAIN_MAP,
domainrules=config.EMAIL_DOMAIN_RULES)
- context = server.MailContext(config, distributor, NoSchedule())
+ context = server.MailContext(config, distributor, Unscheduled())
return context
@@ -426,4 +426,4 @@ class EmailServerServiceTests(unittest.TestCase):
self.skip = True
raise unittest.SkipTest("Not finished yet")
from twisted.internet import reactor
- server.addServer(self.config, self.distributor, NoSchedule)
+ server.addServer(self.config, self.distributor, Unscheduled)
1
0
commit ff5980fe8bab178bc113964a0e6c31a531387c2f
Author: Isis Lovecruft <isis(a)torproject.org>
Date: Tue May 13 23:17:01 2014 +0000
Rewrite bridgedb.Time module.
---
lib/bridgedb/Time.py | 308 +++++++++++++++++++++++++++++++++-----------------
1 file changed, 204 insertions(+), 104 deletions(-)
diff --git a/lib/bridgedb/Time.py b/lib/bridgedb/Time.py
index 707bf9b..4c4a2e2 100644
--- a/lib/bridgedb/Time.py
+++ b/lib/bridgedb/Time.py
@@ -10,157 +10,257 @@
"""This module implements functions for dividing time into chunks."""
import calendar
-import time
+
+from datetime import datetime
from zope import interface
from zope.interface import implements
+from zope.interface import Attribute
+
+
+#: The known time intervals (or *periods*) for dividing time by.
+KNOWN_INTERVALS = ["second", "minute", "hour", "day", "week", "month"]
+
+
+class UnknownInterval(ValueError):
+ """Raised if an interval isn't one of the :data:`KNOWN_INTERVALS`."""
+
-KNOWN_INTERVALS = [ "hour", "day", "week", "month" ]
+def toUnixSeconds(timestruct):
+ """Convert a datetime struct to a Unix timestamp in seconds.
+
+ :param timestruct: A ``datetime.datetime`` object to convert into a
+ timestamp in Unix Era seconds.
+ :rtype: int
+ """
+ return calendar.timegm(timestruct)
+
+def fromUnixSeconds(timestamp):
+ """Convert a Unix timestamp to a datetime struct.
+
+ :param int timestamp: A timestamp in Unix Era seconds.
+ :rtype: :type:`datetime.datetime`
+ """
+ return datetime.fromtimestamp(timestamp)
class ISchedule(interface.Interface):
"""A ``Interface`` specification for a Schedule."""
- def intervalStart(when):
- """Set the start time of the current interval to **when**."""
+ intervalPeriod = Attribute(
+ "The type of period which this Schedule's intervals will rotate by.")
+ intervalCount = Attribute(
+ "Number of **intervalPeriod**s before rotation to the next interval")
+
+ def intervalStart(when=None):
+ """Get the start time of the interval that contains **when**."""
def getInterval(when=None):
"""Get the interval which includes an arbitrary **when**."""
- def nextIntervalStarts():
- """Get the start time for the next interval."""
+ def nextIntervalStarts(when=None):
+ """Get the start of the interval after the one containing **when**."""
-class ScheduleBase(object):
- """Base class for all ``Schedule`` classes."""
+class Unscheduled(object):
+ """A base ``Schedule`` that has only one period that contains all time."""
implements(ISchedule)
- def intervalStart(self, when):
- pass
+ def __init__(self, period=None, count=None):
+ """Create a schedule for dividing time into intervals.
- def getInterval(self, when=None):
- pass
+ :param str period: One of the periods in :data:`KNOWN_INTERVALS`.
+ :param int count: The number of **period**s in an interval.
+ """
+ self.intervalCount = count
+ self.intervalPeriod = period
- def nextIntervalStarts(self):
- pass
+ def intervalStart(self, when=0):
+ """Get the start time of the interval that contains **when**.
+ :param int when: The time which we're trying to find the corresponding
+ interval for.
+ :rtype: int
+ :returns: The Unix epoch timestamp for the start time of the interval
+ that contains **when**.
+ """
+ return toUnixSeconds(datetime.min.timetuple())
+
+ def getInterval(self, when=0):
+ """Get the interval that contains the time **when**.
-class IntervalSchedule(ScheduleBase):
- """An IntervalSchedule splits time into somewhat natural periods, based on
+ :param int when: The time which we're trying to find the corresponding
+ interval for.
+ :rtype: str
+ :returns: A timestamp in the form ``YEAR-MONTH[-DAY[-HOUR]]``. It's
+ specificity depends on what type of interval we're using. For
+ example, if using ``"month"``, the return value would be something
+ like ``"2013-12"``.
+ """
+ return fromUnixSeconds(when).strftime('%04Y-%02m-%02d %02H:%02M:%02S')
+
+ def nextIntervalStarts(self, when=0):
+ """Return the start time of the interval starting _after_ when.
+
+ :rtype: int
+ :returns: Return the Y10K bug.
+ """
+ return toUnixSeconds(datetime.max.timetuple())
+
+
+class ScheduledInterval(Unscheduled):
+ """An class that splits time into periods, based on seconds, minutes,
hours, days, weeks, or months.
- :ivar str itype: One of "month", "day", "hour".
- :ivar int count: How many of the units in :ivar:`itype` belong to each period.
+ :ivar str intervalPeriod: One of the :data:`KNOWN_INTERVALS`.
+ :ivar int intervalCount: The number of times **intervalPeriod** should be
+ repeated within an interval.
"""
+ implements(ISchedule)
+
+ def __init__(self, period=None, count=None):
+ """Create a schedule for dividing time into intervals.
+
+ :param str period: One of the periods in :data:`KNOWN_INTERVALS`.
+ :param int count: The number of **period**s in an interval.
+ """
+ super(ScheduledInterval, self).__init__(period, count)
+ self._setIntervalCount(count)
+ self._setIntervalPeriod(period)
- def __init__(self, intervaltype, count):
- """Divide time into intervals of **count** number of **intervaltype**.
+ def _setIntervalCount(self, count=None):
+ """Set our :ivar:`intervalCount`.
- :param str intervaltype: One of ``'month'``, ``'week'``, ``'day'``,
- or ``'hour'``.
+ .. attention:: This method should be called _before_
+ :meth:`_setIntervalPeriod`, because the latter may change the
+ count, if it decides to change the period (for example, to
+ simplify things by changing weeks into days).
- :param int count: How many of the units in **intervaltype** belong to
- each period.
+ :param int count: The number of times the :ivar:`intervalPeriod`
+ should be repeated during the interval. Defaults to ``1``.
+ :raises UnknownInterval: if the specified **count** was invalid.
+ """
+ try:
+ if not count > 0:
+ count = 1
+ count = int(count)
+ except (TypeError, ValueError):
+ raise UnknownInterval("%s.intervalCount: %r ist not an integer."
+ % (self.__class__.__name__, count))
+ self.intervalCount = count
+
+ def _setIntervalPeriod(self, period=None):
+ """Set our :ivar:`intervalPeriod`.
+
+ :param str period: One of the :data:`KNOWN_INTERVALS`, or its
+ plural. Defaults to ``'hour'``.
+ :raises UnknownInterval: if the specified **period** is unknown.
"""
- it = intervaltype.lower()
- if it.endswith("s"): it = it[:-1]
- if it not in KNOWN_INTERVALS:
- raise TypeError("What's a %s?"%it)
- assert count > 0
- if it == 'week':
- it = 'day'
- count *= 7
- self.itype = it
- self.count = count
-
- def intervalStart(self, when):
+ if not period:
+ period = 'hour'
+ try:
+ period = period.lower()
+ # Depluralise the period if necessary, i.e., "months" -> "month".
+ if period.endswith('s'):
+ period = period[:-1]
+
+ if not period in KNOWN_INTERVALS:
+ raise ValueError
+ except (TypeError, AttributeError, ValueError):
+ raise UnknownInterval("%s doesn't know about the %r interval type."
+ % (self.__class__.__name__, period))
+ self.intervalPeriod = period
+
+ if period == 'week':
+ self.intervalPeriod = 'day'
+ self.intervalCount *= 7
+
+ def intervalStart(self, when=0):
"""Get the start time of the interval that contains **when**.
+ :param int when: The time which we're trying to determine the start of
+ interval that contains it. This should be given in Unix seconds,
+ for example, taken from :func:`calendar.timegm`.
:rtype: int
:returns: The Unix epoch timestamp for the start time of the interval
that contains **when**.
"""
- if self.itype == 'month':
+ if self.intervalPeriod == 'month':
# For months, we always start at the beginning of the month.
- tm = time.gmtime(when)
- n = tm.tm_year * 12 + tm.tm_mon - 1
- n -= (n % self.count)
- month = n%12 + 1
- return calendar.timegm((n//12, month, 1, 0, 0, 0))
- elif self.itype == 'day':
+ date = fromUnixSeconds(when)
+ months = (date.year * 12) + (date.month - 1)
+ months -= (months % self.intervalCount)
+ month = months % 12 + 1
+ return toUnixSeconds((months // 12, month, 1, 0, 0, 0))
+ elif self.intervalPeriod == 'day':
# For days, we start at the beginning of a day.
- when -= when % (86400 * self.count)
+ when -= when % (86400 * self.intervalCount)
return when
- elif self.itype == 'hour':
+ elif self.intervalPeriod == 'hour':
# For hours, we start at the beginning of an hour.
- when -= when % (3600 * self.count)
+ when -= when % (3600 * self.intervalCount)
+ return when
+ elif self.intervalPeriod == 'minute':
+ when -= when % (60 * self.intervalCount)
+ return when
+ elif self.intervalPeriod == 'second':
+ when -= when % self.intervalCount
return when
- else:
- assert False
- def getInterval(self, when):
+ def getInterval(self, when=0):
"""Get the interval that contains the time **when**.
>>> import calendar
- >>> from bridgedb.Time import IntervalSchedule
- >>> t = calendar.timegm((2007, 12, 12, 0, 0, 0))
- >>> I = IntervalSchedule('month', 1)
- >>> I.getInterval(t)
+ >>> from bridgedb.Time import ScheduledInterval
+ >>> sched = ScheduledInterval('month', 1)
+ >>> when = calendar.timegm((2007, 12, 12, 0, 0, 0))
+ >>> sched.getInterval(when)
'2007-12'
+ >>> then = calendar.timegm((2014, 05, 13, 20, 25, 13))
+ >>> sched.getInterval(then)
+ '2014-05'
:param int when: The time which we're trying to find the corresponding
- interval for.
+ interval for. Given in Unix seconds, for example, taken from
+ :func:`calendar.timegm`.
:rtype: str
:returns: A timestamp in the form ``YEAR-MONTH[-DAY[-HOUR]]``. It's
- specificity depends on what type of interval we're
- using. For example, if using ``"month"``, the return value
- would be something like ``"2013-12"``.
+ specificity depends on what type of interval we're using. For
+ example, if using ``"month"``, the return value would be something
+ like ``"2013-12"``.
+ """
+ date = fromUnixSeconds(self.intervalStart(when))
+
+ fstr = "%04Y-%02m"
+ if self.intervalPeriod != 'month':
+ fstr += "-%02d"
+ if self.intervalPeriod != 'day':
+ fstr += " %02H"
+ if self.intervalPeriod != 'hour':
+ fstr += ":%02M"
+ if self.intervalPeriod == 'minute':
+ fstr += ":%02S"
+
+ return date.strftime(fstr)
+
+ def nextIntervalStarts(self, when=0):
+ """Return the start time of the interval starting _after_ when.
+
+ :returns: The Unix epoch timestamp for the start time of the interval
+ that contains **when**.
"""
- if self.itype == 'month':
- tm = time.gmtime(when)
- n = tm.tm_year * 12 + tm.tm_mon - 1
- n -= (n % self.count)
- month = n%12 + 1
- return "%04d-%02d" % (n // 12, month)
- elif self.itype == 'day':
- when = self.intervalStart(when) + 7200 #slop
- tm = time.gmtime(when)
- return "%04d-%02d-%02d" % (tm.tm_year, tm.tm_mon, tm.tm_mday)
- elif self.itype == 'hour':
- when = self.intervalStart(when) + 120 #slop
- tm = time.gmtime(when)
- return "%04d-%02d-%02d %02d" % (tm.tm_year, tm.tm_mon, tm.tm_mday,
- tm.tm_hour)
- else:
- assert False
-
- def nextIntervalStarts(self, when):
- """Return the start time of the interval starting _after_ when."""
- if self.itype == 'month':
- tm = time.gmtime(when)
- n = tm.tm_year * 12 + tm.tm_mon - 1
- n -= (n % self.count)
- month = n%12 + 1
- tm = (n // 12, month+self.count, 1, 0,0,0)
- return calendar.timegm(tm)
- elif self.itype == 'day':
- return self.intervalStart(when) + 86400 * self.count
- elif self.itype == 'hour':
- return self.intervalStart(when) + 3600 * self.count
-
-
-class NoSchedule(ScheduleBase):
- """A Schedule that has only one period for all time."""
-
- def __init__(self):
- pass
-
- def intervalStart(self, when):
- return 0
-
- def getInterval(self, when):
- return "1970"
-
- def nextIntervalStarts(self, when):
- return 2147483647L # INT32_MAX
+ seconds = self.intervalStart(when)
+
+ if self.intervalPeriod == 'month':
+ date = fromUnixSeconds(seconds)
+ months = date.month + self.intervalCount
+ return toUnixSeconds((date.year, months, 1, 0, 0, 0))
+ elif self.intervalPeriod == 'day':
+ return seconds + (86400 * self.intervalCount)
+ elif self.intervalPeriod == 'hour':
+ return seconds + (3600 * self.intervalCount)
+ elif self.intervalPeriod == 'minute':
+ return seconds + (60 * self.intervalCount)
+ elif self.intervalPeriod == 'second':
+ return seconds + self.intervalCount
1
0
[bridgedb/master] Add bridgedb.schedule module to Sphinx build configs.
by isis@torproject.org 16 May '14
by isis@torproject.org 16 May '14
16 May '14
commit 0efa47c8574a2557191de74ffacf96b7ab593af3
Author: Isis Lovecruft <isis(a)torproject.org>
Date: Tue May 13 23:33:24 2014 +0000
Add bridgedb.schedule module to Sphinx build configs.
---
doc/sphinx/source/bridgedb.rst | 1 +
doc/sphinx/source/bridgedb.schedule.rst | 10 ++++++++++
doc/sphinx/source/conf.py | 1 +
3 files changed, 12 insertions(+)
diff --git a/doc/sphinx/source/bridgedb.rst b/doc/sphinx/source/bridgedb.rst
index aa775f9..e52c041 100644
--- a/doc/sphinx/source/bridgedb.rst
+++ b/doc/sphinx/source/bridgedb.rst
@@ -19,6 +19,7 @@ BridgeDB Package and Module Documentation
bridgedb.persistent
bridgedb.runner
bridgedb.safelog
+ bridgedb.schedule
bridgedb.Stability
bridgedb.Storage
bridgedb.strings
diff --git a/doc/sphinx/source/bridgedb.schedule.rst b/doc/sphinx/source/bridgedb.schedule.rst
new file mode 100644
index 0000000..66f727c
--- /dev/null
+++ b/doc/sphinx/source/bridgedb.schedule.rst
@@ -0,0 +1,10 @@
+.. _schedule:
+
+bridgedb.schedule
+-----------------
+
+.. automodule:: bridgedb.schedule
+ :members:
+ :undoc-members:
+ :private-members:
+ :show-inheritance:
diff --git a/doc/sphinx/source/conf.py b/doc/sphinx/source/conf.py
index 977032f..161a471 100644
--- a/doc/sphinx/source/conf.py
+++ b/doc/sphinx/source/conf.py
@@ -39,6 +39,7 @@ import bridgedb.Main
import bridgedb.persistent
import bridgedb.runner
import bridgedb.safelog
+import bridgedb.schedule
import bridgedb.Stability
import bridgedb.Storage
import bridgedb.strings
1
0
[bridgedb/master] Add a ScheduledInterval timeout to make GimpCaptcha stale.
by isis@torproject.org 16 May '14
by isis@torproject.org 16 May '14
16 May '14
commit 2d16b608449be112023cbeb3bccfe901502c5e44
Author: Isis Lovecruft <isis(a)torproject.org>
Date: Wed May 14 21:54:39 2014 +0000
Add a ScheduledInterval timeout to make GimpCaptcha stale.
* FIXES #11215 which describes a problem where a successful challenge
string and CAPTCHA solution pair can be replayed to the server, once
per bridge hashring rotation period (every three hours) to get a new
set of bridges without solving a CAPTCHA.
* ADD a `GimpCaptcha.sched` attribute which holds a
`bridgedb.schedule.ScheduledInterval` for determining which time
period the CAPTCHA was created in, as well as for determining if
we're still in the same time period during CAPTCHA solution
verification.
* ADD a padded timestamp to the encrypted bloc, ENC_BLOB, inside the
format of the GimpCaptcha.challenge strings.
* ADD a captcha.CaptchaExpired exception which is raised when we're
checking a CAPTCHA solution that is no longer in the allowed time
interval.
---
lib/bridgedb/HTTPServer.py | 12 +++++--
lib/bridgedb/captcha.py | 79 ++++++++++++++++++++++++++++++++------------
2 files changed, 67 insertions(+), 24 deletions(-)
diff --git a/lib/bridgedb/HTTPServer.py b/lib/bridgedb/HTTPServer.py
index 8289be3..9d76e28 100644
--- a/lib/bridgedb/HTTPServer.py
+++ b/lib/bridgedb/HTTPServer.py
@@ -313,14 +313,20 @@ class GimpCaptchaProtectedResource(CaptchaProtectedResource):
:rtupe: bool
:returns: True, if the CAPTCHA solution was valid; False otherwise.
"""
+ valid = False
challenge, solution = self.extractClientSolution(request)
clientIP = self.getClientIP(request)
clientHMACKey = crypto.getHMAC(self.hmacKey, clientIP)
- valid = captcha.GimpCaptcha.check(challenge, solution,
- self.secretKey, clientHMACKey)
+
+ try:
+ valid = captcha.GimpCaptcha.check(challenge, solution,
+ self.secretKey, clientHMACKey)
+ except captcha.CaptchaExpired as error:
+ logging.warn(error)
+ valid = False
+
logging.debug("%sorrect captcha from %r: %r."
% ("C" if valid else "Inc", clientIP, solution))
-
return valid
def getCaptchaImage(self, request):
diff --git a/lib/bridgedb/captcha.py b/lib/bridgedb/captcha.py
index e10bc81..758c1f3 100644
--- a/lib/bridgedb/captcha.py
+++ b/lib/bridgedb/captcha.py
@@ -39,6 +39,7 @@
\_ GimpCaptcha - Class for obtaining a CAPTCHA from a local cache.
|- hmacKey - A client-specific key for HMAC generation.
|- cacheDir - The path to the local CAPTCHA cache directory.
+ |- sched - A class for timing out CAPTCHAs after an interval.
\_ get() - Get a CAPTCHA image from the cache and create a challenge.
..
@@ -58,6 +59,7 @@ from base64 import urlsafe_b64decode
import logging
import random
import os
+import time
import urllib2
from BeautifulSoup import BeautifulSoup
@@ -65,9 +67,13 @@ from BeautifulSoup import BeautifulSoup
from zope.interface import Interface, Attribute, implements
from bridgedb import crypto
+from bridgedb import schedule
from bridgedb.txrecaptcha import API_SSL_SERVER
+class CaptchaExpired(ValueError):
+ """Raised when a client's CAPTCHA is too stale."""
+
class CaptchaKeyError(Exception):
"""Raised if a CAPTCHA system's keys are invalid or missing."""
@@ -200,6 +206,8 @@ class GimpCaptcha(Captcha):
.. _gimp-captcha: https://github.com/isislovecruft/gimp-captcha
"""
+ sched = schedule.ScheduledInterval('minutes', 30)
+
def __init__(self, publicKey=None, secretKey=None, hmacKey=None,
cacheDir=None):
"""Create a ``GimpCaptcha`` which retrieves images from **cacheDir**.
@@ -242,37 +250,52 @@ class GimpCaptcha(Captcha):
:param str secretKey: A PKCS#1 OAEP-padded, private RSA key, used for
verifying the client's solution to the CAPTCHA.
:param bytes hmacKey: A private key for generating HMACs.
+ :raises CaptchaExpired: if the **solution** was for a stale CAPTCHA.
:rtype: bool
- :returns: True if the CAPTCHA solution was correct.
+ :returns: ``True`` if the CAPTCHA solution was correct and not
+ stale. ``False`` otherwise.
"""
- validHMAC = False
+ hmacIsValid = False
if not solution:
- return validHMAC
+ return hmacIsValid
logging.debug("Checking CAPTCHA solution %r against challenge %r"
% (solution, challenge))
try:
decoded = urlsafe_b64decode(challenge)
- hmac = decoded[:20]
- original = decoded[20:]
- verified = crypto.getHMAC(hmacKey, original)
- validHMAC = verified == hmac
+ hmacFromBlob = decoded[:20]
+ encBlob = decoded[20:]
+ hmacNew = crypto.getHMAC(hmacKey, encBlob)
+ hmacIsValid = hmacNew == hmacFromBlob
except Exception:
return False
finally:
- if validHMAC:
+ if hmacIsValid:
try:
- decrypted = secretKey.decrypt(original)
+ answerBlob = secretKey.decrypt(encBlob)
+
+ timestamp = answerBlob[:12].lstrip('0')
+ then = cls.sched.nextIntervalStarts(int(timestamp))
+ now = int(time.time())
+ answer = answerBlob[12:]
except Exception as error:
logging.warn(error.message)
else:
- if solution.lower() == decrypted.lower():
+ # If the beginning of the 'next' interval (the interval
+ # after the one when the CAPTCHA timestamp was created)
+ # has already passed, then the CAPTCHA is stale.
+ if now >= then:
+ exp = schedule.fromUnixSeconds(then).isoformat(sep=' ')
+ raise CaptchaExpired("Solution %r was for a CAPTCHA "
+ "which already expired at %s."
+ % (solution, exp))
+ if solution.lower() == answer.lower():
return True
return False
def createChallenge(self, answer):
- """Encrypt-then-HMAC the CAPTCHA **answer**.
+ """Encrypt-then-HMAC a timestamp plus the CAPTCHA **answer**.
A challenge string consists of a URL-safe, base64-encoded string which
contains an ``HMAC`` concatenated with an ``ENC_BLOB``, in the
@@ -295,34 +318,48 @@ class GimpCaptcha(Captcha):
| | applying :func:`~crypto.getHMAC` to the | |
| | ``ENC_BLOB``. | |
+-------------+--------------------------------------------+----------+
- | ENC_BLOB | An encrypted ``ANSWER``, created with | varies |
+ | ENC_BLOB | An encrypted ``ANSWER_BLOB``, created with | varies |
| | a PKCS#1 OAEP-padded RSA :ivar:`publicKey`.| |
+-------------+--------------------------------------------+----------+
+ | ANSWER_BLOB | Contains the concatenated ``TIMESTAMP`` | varies |
+ | | and ``ANSWER``. | |
+ +-------------+--------------------------------------------+----------+
+ | TIMESTAMP | A Unix Epoch timestamp, in seconds, | 12 bytes |
+ | | left-padded with "0"s. | |
+ +-------------+--------------------------------------------+----------+
| ANSWER | A string containing answer to this | 8 bytes |
| | CAPTCHA :ivar:`image`. | |
+-------------+--------------------------------------------+----------+
The steps taken to produce a ``CHALLENGE`` are then:
- 1. Encrypt the ``ANSWER`` to :ivar:`publicKey` to create
- the ``ENC_BLOB``.
+ 1. Create a ``TIMESTAMP``, and pad it on the left with ``0``s to 12
+ bytes in length.
+
+ 2. Next, take the **answer** to this CAPTCHA :ivar:`image: and
+ concatenate the padded ``TIMESTAMP`` and the ``ANSWER``, forming
+ an ``ANSWER_BLOB``.
+
+ 3. Encrypt the resulting ``ANSWER_BLOB`` to :ivar:`publicKey` to
+ create the ``ENC_BLOB``.
- 2. Use the client-specific :ivar:`hmacKey` to apply the
+ 4. Use the client-specific :ivar:`hmacKey` to apply the
:func:`~crypto.getHMAC` function to the ``ENC_BLOB``, obtaining
an ``HMAC``.
- 3. Create the final ``CHALLENGE`` string by concatenating the
+ 5. Create the final ``CHALLENGE`` string by concatenating the
``HMAC`` and ``ENC_BLOB``, then base64-encoding the result.
:param str answer: The answer to a CAPTCHA.
:rtype: str
:returns: A challenge string.
"""
- encrypted = self.publicKey.encrypt(answer)
- hmac = crypto.getHMAC(self.hmacKey, encrypted)
- challenge = hmac + encrypted
- encoded = urlsafe_b64encode(challenge)
- return encoded
+ timestamp = str(int(time.time())).zfill(12)
+ blob = timestamp + answer
+ encBlob = self.publicKey.encrypt(blob)
+ hmac = crypto.getHMAC(self.hmacKey, encBlob)
+ challenge = urlsafe_b64encode(hmac + encBlob)
+ return challenge
def get(self):
"""Get a random CAPTCHA from the cache directory.
1
0
16 May '14
commit b58e062ee248de19767614da152776b3ad6bbaae
Author: Isis Lovecruft <isis(a)torproject.org>
Date: Wed May 14 03:18:51 2014 +0000
Add unittests for bridgedb.schedule module.
---
lib/bridgedb/test/test_schedule.py | 201 ++++++++++++++++++++++++++++++++++++
1 file changed, 201 insertions(+)
diff --git a/lib/bridgedb/test/test_schedule.py b/lib/bridgedb/test/test_schedule.py
new file mode 100644
index 0000000..24c45ef
--- /dev/null
+++ b/lib/bridgedb/test/test_schedule.py
@@ -0,0 +1,201 @@
+# -*- coding: utf-8 -*-
+#
+# This file is part of BridgeDB, a Tor bridge distribution system.
+#
+# :authors: Isis Lovecruft 0xA3ADB67A2CDB8B35 <isis(a)torproject.org>
+# :copyright: (c) 2014, Isis Lovecruft
+# (c) 2014, The Tor Project, Inc.
+# :license: see LICENSE for licensing information
+
+"""Unittests for the :mod:`bridgedb.schedule` module."""
+
+from __future__ import print_function
+
+from twisted.trial import unittest
+
+from bridgedb import schedule
+
+
+class UnscheduledTests(unittest.TestCase):
+ """Tests for :class:`bridgedb.scheduled.Unscheduled`."""
+
+ def setUp(self):
+ self.sched = schedule.Unscheduled()
+
+ def test_Unscheduled_init(self):
+ """The instance should be an instance of its class."""
+ self.assertIsInstance(self.sched, schedule.Unscheduled)
+
+ def test_Unscheduled_providesISchedule(self):
+ """Unscheduled should implement the ISchedule interface."""
+ schedule.ISchedule.namesAndDescriptions()
+ self.assertTrue(schedule.ISchedule.providedBy(self.sched))
+
+ def test_Unscheduled_intervalStart_noargs(self):
+ time = self.sched.intervalStart()
+ self.assertIsInstance(time, int)
+ self.assertEquals(time, -62135596800)
+
+ def test_Unscheduled_getInterval_noargs(self):
+ time = self.sched.getInterval()
+ self.assertIsInstance(time, str)
+ self.assertEquals(time, "1970-01-01 00:00:00")
+
+ def test_Unscheduled_nextIntervalStarts_noargs(self):
+ time = self.sched.nextIntervalStarts()
+ self.assertIsInstance(time, int)
+ self.assertEquals(time, 253402300799)
+
+
+class ScheduledIntervalTests(unittest.TestCase):
+ """Tests for :class:`bridgedb.scheduled.ScheduledInterval`."""
+
+ def setUp(self):
+ import time
+ self.now = time.time
+ self.sched = schedule.ScheduledInterval
+
+ def test_ScheduledInterval_providesISchedule(self):
+ """ScheduledInterval should implement the ISchedule interface."""
+ self.assertTrue(schedule.ISchedule.providedBy(self.sched('month', 1)))
+
+ def _check_init(self, sched):
+ """The instance should be an instance of its class."""
+ self.assertIsInstance(sched, schedule.ScheduledInterval)
+
+ def test_ScheduledInterval_init_month(self):
+ self._check_init(self.sched('month', 1))
+
+ def test_ScheduledInterval_init_week(self):
+ self._check_init(self.sched('week', 2))
+
+ def test_ScheduledInterval_init_day(self):
+ self._check_init(self.sched('days', 5))
+
+ def test_ScheduledInterval_init_hour(self):
+ self._check_init(self.sched('hours', 12))
+
+ def test_ScheduledInterval_init_minute(self):
+ self._check_init(self.sched('minute', 10))
+
+ def test_ScheduledInterval_init_seconds(self):
+ self._check_init(self.sched('seconds', 30))
+
+ def test_ScheduledInterval_init_badIntervalPeriod(self):
+ self.assertRaises(schedule.UnknownInterval,
+ self.sched, 'decades', 2)
+
+ def test_ScheduledInterval_init_badIntervalCount(self):
+ self.assertRaises(schedule.UnknownInterval,
+ self.sched, 'minutes', 'd20')
+
+ def test_ScheduledInterval_init_negativeIntervalCount(self):
+ sched = self.sched('days', -100000)
+ self.assertEquals(sched.intervalCount, 1)
+ self.assertEquals(sched.intervalPeriod, 'day')
+
+ def test_ScheduledInterval_init_noargs(self):
+ """Check that the defaults parameters function as expected."""
+ sched = self.sched()
+ self.assertEquals(sched.intervalCount, 1)
+ self.assertEquals(sched.intervalPeriod, 'hour')
+
+ def _check_intervalStart(self, period='second', count=30, variance=30):
+ """Test the ScheduledInterval.intervalStart() method.
+
+ :param str period: The interval type for the period.
+ :param int count: The number of **period**s within an interval.
+ :param int variance: The amount of variance (in seconds) to tolerate
+ between the start of the interval containing now, and now.
+ """
+ now = int(self.now())
+ sched = self.sched(period, count)
+ time = sched.intervalStart(now)
+ self.assertIsInstance(time, int)
+ self.assertApproximates(now, time, variance)
+
+ def test_ScheduledInterval_intervalStart_month(self):
+ self._check_intervalStart('month', 1, 31*24*60*60)
+
+ def test_ScheduledInterval_intervalStart_week(self):
+ self._check_intervalStart('week', 2, 14*24*60*60)
+
+ def test_ScheduledInterval_intervalStart_day(self):
+ self._check_intervalStart('days', 5, 5*24*60*60)
+
+ def test_ScheduledInterval_intervalStart_hour(self):
+ self._check_intervalStart('hours', 12, 12*60*60)
+
+ def test_ScheduledInterval_intervalStart_minute(self):
+ self._check_intervalStart('minute', 10, 10*60)
+
+ def test_ScheduledInterval_intervalStart_seconds(self):
+ self._check_intervalStart('seconds', 30, 30)
+
+ def _check_getInterval(self, period='second', count=30, variance=30):
+ """Test the ScheduledInterval.getInterval() method.
+
+ :param str period: The interval type for the period.
+ :param int count: The number of **period**s within an interval.
+ :param int variance: The amount of variance (in seconds) to tolerate
+ between the start of the interval containing now, and now.
+ """
+ now = int(self.now())
+ sched = self.sched(period, count)
+ ts = sched.getInterval(now)
+ self.assertIsInstance(ts, str)
+ secs = [int(x) for x in ts.replace('-', ' ').replace(':', ' ').split()]
+ [secs.append(0) for _ in xrange(6-len(secs))]
+ secs = schedule.calendar.timegm(secs)
+ self.assertApproximates(now, secs, variance)
+
+ def test_ScheduledInterval_getInterval_month(self):
+ self._check_getInterval('month', 2, 2*31*24*60*60)
+
+ def test_ScheduledInterval_getInterval_week(self):
+ self._check_getInterval('week', 1, 7*24*60*60)
+
+ def test_ScheduledInterval_getInterval_day(self):
+ self._check_getInterval('days', 4, 4*24*60*60)
+
+ def test_ScheduledInterval_getInterval_hour(self):
+ self._check_getInterval('hours', 23, 23*60*60)
+
+ def test_ScheduledInterval_getInterval_minute(self):
+ self._check_getInterval('minutes', 15, 15*60)
+
+ def test_ScheduledInterval_getInterval_seconds(self):
+ self._check_getInterval('seconds', 10, 60)
+
+ def _check_nextIntervalStarts(self, period='second', count=30, variance=30):
+ """Test the ScheduledInterval.nextIntervalStarts() method.
+
+ :param str period: The interval type for the period.
+ :param int count: The number of **period**s within an interval.
+ :param int variance: The amount of variance (in seconds) to tolerate
+ between the start of the interval containing now, and now.
+ """
+ now = int(self.now())
+ sched = self.sched(period, count)
+ time = sched.nextIntervalStarts(now)
+ self.assertIsInstance(time, int)
+ # (now + variance - time) should be > variance
+ self.assertApproximates(now + variance, time, variance)
+
+ def test_ScheduledInterval_nextIntervalStarts_month(self):
+ self._check_nextIntervalStarts('month', 2, 2*31*24*60*60)
+
+ def test_ScheduledInterval_nextIntervalStarts_week(self):
+ self._check_nextIntervalStarts('week', 1, 7*24*60*60)
+
+ def test_ScheduledInterval_nextIntervalStarts_day(self):
+ self._check_nextIntervalStarts('days', 4, 4*24*60*60)
+
+ def test_ScheduledInterval_nextIntervalStarts_hour(self):
+ self._check_nextIntervalStarts('hours', 23, 23*60*60)
+
+ def test_ScheduledInterval_nextIntervalStarts_minute(self):
+ self._check_nextIntervalStarts('minutes', 15, 15*60)
+
+ def test_ScheduledInterval_nextIntervalStarts_seconds(self):
+ self._check_nextIntervalStarts('seconds', 10, 10)
1
0