Coder Social home page Coder Social logo

pallets / itsdangerous Goto Github PK

View Code? Open in Web Editor NEW
2.8K 56.0 214.0 620 KB

Safely pass trusted data to untrusted environments and back.

Home Page: https://itsdangerous.palletsprojects.com

License: BSD 3-Clause "New" or "Revised" License

Python 100.00%
python security hmac serialization itsdangerous pallets

itsdangerous's People

Contributors

alanhamlett avatar dasich avatar davidism avatar dependabot-preview[bot] avatar dependabot[bot] avatar dirkmueller avatar dnicolodi avatar esadek avatar eugene-eeo avatar ft-arnout avatar greyli avatar jaraco avatar jayvdb avatar jparise avatar legoktm avatar lepture avatar lucian1900 avatar maxcountryman avatar minho42 avatar mitsuhiko avatar northernsage avatar polyfunc avatar pombredanne avatar pre-commit-ci[bot] avatar pwlandoll avatar quobit avatar sileht avatar thomaswaldmann avatar untitaker avatar volker48 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

itsdangerous's Issues

Permission to generate stubs for itsdangerous in typeshed

Howdy,

I'd like to add stubs for Flask to https://github.com/python/typeshed, a repository used to store PEP 484 type signatures for the python stdlib and popular third party libraries. As per PEP 484, permission is required from the library owner before merging type signatures into typeshed - https://www.python.org/dev/peps/pep-0484/#the-typeshed-repo

Here's the corresponding typeshed issue -
python/typeshed#28

You guys covered werkzeug and Jinja in pallets/flask#2012 but didn't mention itsdangerous ๐Ÿ˜„

Here's the PR by the way:
python/typeshed#537

It actually surfaced a few of what I would consider bugs with itsdangerous with bytes and str in Python 3. For example:

from itsdangerous import Signer

s = Signer('secret-key')
s.sign('hi')

results in:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/site-packages/itsdangerous.py", line 353, in sign
    return value + want_bytes(self.sep) + self.get_signature(value)
TypeError: Can't convert 'bytes' object to str implicitly

And:

s.verify_signature('hi', 'some_signature')

Results in:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/site-packages/itsdangerous.py", line 362, in verify_signature
    return self.algorithm.verify_signature(key, value, sig)
  File "/usr/local/lib/python3.5/site-packages/itsdangerous.py", line 243, in verify_signature
    return constant_time_compare(sig, self.get_signature(key, value))
  File "/usr/local/lib/python3.5/site-packages/itsdangerous.py", line 268, in get_signature
    mac = hmac.new(key, msg=value, digestmod=self.digest_method)
  File "/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/hmac.py", line 144, in new
    return HMAC(key, msg, digestmod)
  File "/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/hmac.py", line 84, in __init__
    self.update(msg)
  File "/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/hmac.py", line 93, in update
    self.inner.update(msg)
TypeError: Unicode-objects must be encoded before hashing

RFC7519 compliance

According to RFC7519, the expiration date should be in the claims, rather than the header. Would this be supported?

Issues signing string on Python 3

This code works in Python 2 but doesn't seem to work properly in Python 3. Not a particularly complex example.

Python 3.6.1 (default, Apr  4 2017, 09:40:21)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from itsdangerous import Signer
>>> s = Signer('AAAAAAAAAAAAAAAAAAAA')
>>> s.sign('[email protected]')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/kchung/.virtualenvs/ctfd3/lib/python3.6/site-packages/itsdangerous.py", line 353, in sign
    return value + want_bytes(self.sep) + self.get_signature(value)
TypeError: must be str, not bytes
>>>

Installation fails with `AttributeError`

On a clean Fedora 26 box, the command sudo pip3 install itsdangerous fails with

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-5jettonu/itsdangerous/setup.py", line 20, in <module>
        'Programming Language :: Python :: 3',
      File "/usr/lib64/python3.6/distutils/core.py", line 148, in setup
        dist.run_commands()
      File "/usr/lib64/python3.6/distutils/dist.py", line 955, in run_commands
        self.run_command(cmd)
      File "/usr/lib64/python3.6/distutils/dist.py", line 974, in run_command
        cmd_obj.run()
      File "/usr/lib/python3.6/site-packages/setuptools/command/install.py", line 61, in run
        return orig.install.run(self)
      File "/usr/lib64/python3.6/distutils/command/install.py", line 557, in run
        self.run_command(cmd_name)
      File "/usr/lib64/python3.6/distutils/cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "/usr/lib64/python3.6/distutils/dist.py", line 974, in run_command
        cmd_obj.run()
      File "/usr/lib/python3.6/site-packages/setuptools/command/install_scripts.py", line 33, in run
        bs_cmd = (self.get_finalized_command('build_scripts', create=False) or
      File "/usr/lib64/python3.6/distutils/cmd.py", line 299, in get_finalized_command
        cmd_obj.ensure_finalized()
    AttributeError: 'NoneType' object has no attribute 'ensure_finalized'

    ----------------------------------------
Command "/usr/bin/python3 -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-5jettonu/itsdangerous/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-4m6wlda7-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-5jettonu/itsdangerous/

Package versions

  • python3-devel-3.6.2-5.fc26.x86_64
  • pip 9.0.1 from /usr/lib/python3.6/site-packages (python 3.6)
  • itsdangerous-0.24-py3.6

Reproducibility

A Vagrantfile is provided to help reproduce the issue.

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  # You can search for boxes at https://atlas.hashicorp.com/search
  config.vm.box = "fedora/26-cloud-base"
  config.ssh.forward_agent = true

  config.vm.synced_folder ".", "/vagrant", disabled: true

  config.vm.provider "virtualbox" do |vb|
    vb.name = "itsdangerous"
    vb.gui = false
    vb.memory = "2048"
    vb.cpus = "2"
  end

  config.vm.provision "shell", inline: <<-SHELL
    dnf install -y python3-devel
    pip3 install --upgrade pip
  SHELL
end

Simply copy the contents above to a file named Vagrantfile, then issue the following commands while in the same directory:

(host) $ vagrant up
(host) $ vagrant ssh
(vm)   $ sudo pip3 install itsdangerous

Can't convert 'bytes' object to str implicitly

Mac OS 10.8.4
Python 3.3.1
itsdangerous 0.23

Trying to reproduce tutorial from http://pythonhosted.org/itsdangerous/:

>>> from itsdangerous import Signer
>>> s = Signer('secret-key')
>>> s.sign('my string')
'my string.wh6tMHxLgJqB6oY1uT73iMlyrOA'

and see:

In [13]: from itsdangerous import Signer

In [14]: s = Signer('secret-key')

In [15]: s.sign('my string')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-6ac9e5e97289> in <module>()
----> 1 s.sign('my string')

.../lib/python3.3/site-packages/itsdangerous-0.23-py3.3.egg/itsdangerous.py in sign(self, value)
    326     def sign(self, value):
    327         """Signs the given string."""
--> 328         return value + want_bytes(self.sep) + self.get_signature(value)
    329 
    330     def verify_signature(self, value, sig):

TypeError: Can't convert 'bytes' object to str implicitly

OS Dates before 01/01/2011 are broken

I'm using an embedded linux with a startup kernal time of 01/01/2010, with flask hosted site as a config tool. If the device doesn't have an internet connection (to update time from NTP), and they trigger TimeStampSigner.sign() function in itsdangerous.py, the int_to_byte assert fails as num is < 0.

I've not delved into why the logic expects the date to be greater then 2011, but it breaks it for me.

Python 3.4: TypeError: key: expected bytes or bytearray, but got 'tuple'

Traceback (most recent call last):
  File "---/venv/lib/python3.4/site-packages/flask/app.py", line 1836, in __call__
    return self.wsgi_app(environ, start_response)
  File "---/htt-api/venv/lib/python3.4/site-packages/flask/app.py", line 1813, in wsgi_app
    ctx.push()
  File "---/venv/lib/python3.4/site-packages/flask/ctx.py", line 321, in push
    self.session = self.app.open_session(self.request)
  File "---/venv/lib/python3.4/site-packages/flask/app.py", line 825, in open_session
    return self.session_interface.open_session(self, request)
  File "---/venv/lib/python3.4/site-packages/flask/sessions.py", line 310, in open_session
    data = s.loads(val, max_age=max_age)
  File "---/venv/lib/python3.4/site-packages/itsdangerous.py", line 643, in loads
    .unsign(s, max_age, return_timestamp=True)
  File "---/venv/lib/python3.4/site-packages/itsdangerous.py", line 422, in unsign
    result = Signer.unsign(self, value)
  File "---/venv/lib/python3.4/site-packages/itsdangerous.py", line 371, in unsign
    if self.verify_signature(value, sig):
  File "---/venv/lib/python3.4/site-packages/itsdangerous.py", line 357, in verify_signature
    key = self.derive_key()
  File "---/venv/lib/python3.4/site-packages/itsdangerous.py", line 336, in derive_key
    mac = hmac.new(self.secret_key, digestmod=self.digest_method)
  File "/usr/lib64/python3.4/hmac.py", line 144, in new
    return HMAC(key, msg, digestmod)
  File "/usr/lib64/python3.4/hmac.py", line 42, in __init__
    raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
TypeError: key: expected bytes or bytearray, but got 'tuple'

I suspect this is due to hmac changes in 3.4: https://docs.python.org/3/library/hmac.html

hmac.new(key, msg=None, digestmod=None)

Return a new hmac object. key is a bytes or bytearray object giving the secret key. If msg is present, the method call update(msg) is made. digestmod is the digest name, digest constructor or module for the HMAC object to use. It supports any name suitable to hashlib.new() and defaults to the hashlib.md5 constructor.

Changed in version 3.4: Parameter key can be a bytes or bytearray object. Parameter msg can be of any type supported by hashlib. Parameter digestmod can be the name of a hash algorithm.

Deprecated since version 3.4: MD5 as implicit default digest for digestmod is deprecated.

This prevents visiting any of the routes in Flask, not just those which require login, which I would consider a pretty major problem.

Deprecation proposal

Having read through the docs, it would seem that JWT is now a better solution. It covers more use cases, has more language implementations and is also an RFC standard. Many of the languages, in particular Python, have much more active repos and commit history.

Is there anything in particular that itsdangerous does, which JWT does not cover? If not, I would like to propose deprecating this library in favour of JWT.

JES support

Would it make sense to also support JES (JSON Encryption Standard) in addition to JWS? This would allow you to store potentially sensitive information in untrusted storage.

E.g. think of a registration form which includes a lot of personal information. Traditionally, the form information are stored locally on the server and a verification link is sent to an email. This puts the burden of temporary storage on the server.
If JES is supported, the submitted form data could be included in the verification link. Since email is considered insecure, we don't want this information to be retrievable by anyone else but the server. The benefit in doing so is that the server doesn't have to handle (store and purge) unverified information.

Of course this could be implemented with ad-hoc serialization, but since there's a standard for it, maybe it's better to support it.

otr addon

der tv planer geht nich der rest geht

Unsigning Signed cookie from Django in Flask App

I am working on a Flask app that will take a signed cookie from Django (working on cross site single domain cookie stuff) and pull information out of it for use in my Flask app, but when Django signs the cookie initially, the separator it uses to sign the cookie is 2 colons versus a single . or single :.

So when my Flask app tries to unsign the cookie, and I set the sep=":" it thinks the request is bad because the signature looks like data:sigpart1:sigpart2

TimedSerializer.loads load_payload source code confusion

Hello, i am learning the flask source code.
I want know how the itsdangerous loads digest value, i track one request , similar ๏ผš

  1. flask call the TimedSerializer.loads() method
  2. the TimedSerializer.loads() call Serializer.load_payload() method pass parameter base64d(i print it , it is a digest value)
    3.but when i print it in load_payload() function, it is a string like dict,i can't find where convert digest value to string.
    this is TimedSerializer.loads() code with testing print code:
    image
    this is Serializer.load_payload() method with testing print code:
    image

Changing character in signature base64 doesn't invalidate signature

Hi.

I decided to use itsdangerous for signing in some application. The unittests' results were quite random (sometimes it passed, sometimes not).
The test checked malforming of a signature. I was lazy so I changed only last byte in signature. I was using itsdangerous==0.23.

The code did something like that:

secret = '9ISi8M11WmwC6A=='
valid = 'z8ScUFn13crlUQ==.z08qK6VBPU8lSlnZON_xgFXlAEhpgJbG0H_MAWYSQkvUhhrIrDrDKCUrNqKh6ToY6XogaQD2UoTvRo2eHzZPLw'
invalid = 'z8ScUFn13crlUQ==.z08qK6VBPU8lSlnZON_xgFXlAEhpgJbG0H_MAWYSQkvUhhrIrDrDKCUrNqKh6ToY6XogaQD2UoTvRo2eHzZPLx'

from itsdangerous import Signer
from hashlib import sha512

s = Signer(secret, digest_method=sha512)

s.unsign(valid)
s.unsign(invalid)

Above code will execute correctly (at least on my machine, amd64, python2.7.5+, itsdangerous==0.23).

For a while of digging I think I found the source of the problem.

unsign -> verify_signature -> base64_decode -> base64.urlsafe_b64decode

A little example:

In [11]: base64.urlsafe_b64decode('z08qK6VBPU8lSlnZON_xgFXlAEhpgJbG0H_MAWYSQkvUhhrIrDrDKCUrNqKh6ToY6XogaQD2UoTvRo2eHzZPLw==')
Out[11]: '\xcfO*+\xa5A=O%JY\xd98\xdf\xf1\x80U\xe5\x00Hi\x80\x96\xc6\xd0\x7f\xcc\x01f\x12BK\xd4\x86\x1a\xc8\xac:\xc3(%+6\xa2\xa1\xe9:\x18\xe9z i\x00\xf6R\x84\xefF\x8d\x9e\x1f6O/'

In [12]: base64.urlsafe_b64decode('z08qK6VBPU8lSlnZON_xgFXlAEhpgJbG0H_MAWYSQkvUhhrIrDrDKCUrNqKh6ToY6XogaQD2UoTvRo2eHzZPLx==')
Out[12]: '\xcfO*+\xa5A=O%JY\xd98\xdf\xf1\x80U\xe5\x00Hi\x80\x96\xc6\xd0\x7f\xcc\x01f\x12BK\xd4\x86\x1a\xc8\xac:\xc3(%+6\xa2\xa1\xe9:\x18\xe9z i\x00\xf6R\x84\xefF\x8d\x9e\x1f6O/'

Maybe some additional padding should be added? Or maybe base64 should be replaced?

Tomek

add expiry date to TimestampSigner

Could you please add some kind of expiry date to the TimestampSigner? I want to allow my users to decide how long their links should be valid. Currently i have to include the current timestamp (by using the TimestampSigner) and the max age the user wants. So in such a case it would be much more helpful to handle the integrated Timestamp as expiry date and not as creation date ... but even if i would handle the date check myself, it seems not to be possible to define the now-timestamp used by the TimestampSigner.

TimedSerializer.loads() raises an error when return_timestamp=True

Here is the traceback:

>>> s = itsdangerous.TimedSerializer('a')
>>> token = s.dumps('hello')
>>> s.loads(token)
u'hello'
>>> s.loads(token, return_timestamp=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/private/tmp/dateutils/lib/python2.6/site-packages/itsdangerous.py", line 275, in loads
    return self.load_payload(base64d)
  File "/private/tmp/dateutils/lib/python2.6/site-packages/itsdangerous.py", line 220, in load_payload
    return self.serializer.loads(payload)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 307, in loads
    return _default_decoder.decode(s)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 319, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer

derive_key() occasionally returns invalid key. On ARM71.

(I moved this question from Flask's github)

The signing of session-cookies works fine on development computer. But when moving the software to an embedded device, ARM71, 32 bit the derive_key() occasionally fail and returns an invalid key. Making the cookie invalid.

It is actually the hmac that returns invalid hashed string, but this only happens when running the flask application.

def derive_key(self):
    """This method is called to derive the key.  If you're unhappy with
    the default key derivation choices you can override them here.
    Keep in mind that the key derivation in itsdangerous is not intended
    to be used as a security method to make a complex key out of a short
    password.  Instead you should use large random secret keys.
    """
    salt = want_bytes(self.salt)
    if self.key_derivation == 'concat':
        return self.digest_method(salt + self.secret_key).digest()
    elif self.key_derivation == 'django-concat':
        return self.digest_method(salt + b'signer' +
            self.secret_key).digest()
    elif self.key_derivation == 'hmac':
        mac = hmac.new(self.secret_key, digestmod=self.digest_method) ##### 1
        print(binascii.hexlify(mac.digest()))
        mac.update(salt)               ##### 2
        print(binascii.hexlify(mac.digest()))
        return mac.digest()
    elif self.key_derivation == 'none':
        return self.secret_key
    else:
        raise TypeError('Unknown key derivation method')

secret_key = b"testing"
salt = "cookie-session"

After #####1, binascii.hexlify(mac.digest()) = b'6ab6fc891eefd3b78743ea28b1803811561a7c9b'
After #####2, binascii.hexlify(mac.digest()) = b'd58bd52b4ced54374ea5baca0b6aa52b0e03af74'

But sometimes (1) above return b'9dac0c533fcca6cb787aa332d8f152ffb7e6b960'
and (2) does not change when adding salt: b'9dac0c533fcca6cb787aa332d8f152ffb7e6b960'

Been trying to solve this for a couple of days without success. Any ideas?

Make new release?

The latest one is from 2014, and multiple bugs have been fixed since.

(Including this one: wtforms/flask-wtf#275; the bug is reported in flask-wtf but I believe that current-master itsdangerous handles that correctly)

Low precision of timestamp while creating a token

It looks like the timestamp that is used for tokengeneration is not precise enough. It seems like it only uses an accuracy on a second level but is not handling milliseconds?

You can reproduce this with the following snippet:

import time
from itsdangerous import URLSafeTimedSerializer

serializer = URLSafeTimedSerializer('some-secret', 'some-salt')

for i in range(1, 10):
    print(serializer.dumps({'test': 1}))
    time.sleep(0.5)

which gives me the same token twice within 1 second:

eyJ0ZXN0IjoxfQ.C48Cmw.oaO_dsjdedzISztrO9Vg9HbEsYs
eyJ0ZXN0IjoxfQ.C48Cmw.oaO_dsjdedzISztrO9Vg9HbEsYs
eyJ0ZXN0IjoxfQ.C48CnA.D_jhOJP5Pjw5ZL63RJ85Od8Ol5U
eyJ0ZXN0IjoxfQ.C48CnA.D_jhOJP5Pjw5ZL63RJ85Od8Ol5U
eyJ0ZXN0IjoxfQ.C48CnQ.O9K1VLYhxcIhadLJnHQsga7VDWE
eyJ0ZXN0IjoxfQ.C48CnQ.O9K1VLYhxcIhadLJnHQsga7VDWE
eyJ0ZXN0IjoxfQ.C48Cng.8FhIko9bMt7898nRdve6qhSAuOI
eyJ0ZXN0IjoxfQ.C48Cng.8FhIko9bMt7898nRdve6qhSAuOI
eyJ0ZXN0IjoxfQ.C48Cnw.m-GRF4GyGn1-h5CJudKkSAxKQWw

Should it use timestamps with at least millisecond resolution?

It might not be much of an issue when used in real-world scenarios like creating reset password tokens and the like but it definitely is a drawback in test environments, if you want to check whether a newly created token does actually differ.

Also you never want to introduce additional sleeping time.

Since e.g. flask-security/flask-security-fork is using this lib, this might affect quite some use cases and production apps.

docstring url generates sphinx error

a change too simple for forking :]

--- itsdangerous.py.orig        Wed Dec  4 23:08:19 2013                                                      
+++ itsdangerous.py     Wed Dec  4 23:08:22 2013                                                              
@@ -729,7 +729,7 @@ class TimedJSONWebSignatureSerializer(JSONWebSignature                                    
     JWS currently does not specify this behavior but it mentions a possibility                               
     extension like this in the spec.  Expiry date is encoded into the header                                 
     similarily as specified in `draft-ietf-oauth-json-web-token                                              
-    <http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#expDef`_.                             
+    <http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#expDef>`_.                            

     The unsign method can raise a :exc:`SignatureExpired` method if the                                      
     unsigning failed because the signature is expired.  This exception is a

Serializer.load_payload overrides in subclasses have incompatible signatures

Mypy recently introduced stricter checks for function signature compatibility (python/mypy#2521). Since itsdangerous is included in the typeshed library with typing stubs, it found an issue with the signatures of load_payload. Consider:

class Serializer:
  def load_payload(self, payload, serializer=None): ...

vs.

class JSONWebSignatureSerializer(Serializer):
  def load_payload(self, payload, return_header=False): ...

vs.

class URLSafeSerializerMixin(object):
  def load_payload(self, payload): ...

class URLSafeSerializer(URLSafeSerializerMixin, Serializer): ...
class TimedSerializer(Serializer): ...
class URLSafeTimedSerializer(URLSafeSerializerMixin, TimedSerializer): ...

Basically, it's invalid to replace load_payload() accepting an optional kwarg with an implementation that doesn't.

`TimestampSigner.validate` will raise `SignatureExpired`

I'm not 100% sure of the intended functionality, but it seems like TimestampSigner.validate should not raise any exceptions. If the timestamp is older than the max age, the function should return False rather than raise an exception.

Separator check fails

I'm able to inadvertently create a signature that contains separator itself.

See:

In [21]: s = Signer('secret-key', sep='_')

In [22]: signed = s.sign('foobar')

In [23]: signed
Out[23]: 'foobar_bM9Ftq9n87nl0Xc_Rs9orkssfJ0'

In [24]: s.unsign(signed)
---------------------------------------------------------------------------
BadSignature                              Traceback (most recent call last)
<ipython-input-24-ea5a1a92fab7> in <module>()
----> 1 s.unsign(signed)

/Users/catalbas/envs/token-test/lib/python2.7/site-packages/itsdangerous.pyc in unsign(self, signed_value)
    372             return value
    373         raise BadSignature('Signature %r does not match' % sig,
--> 374                            payload=value)
    375 
    376     def validate(self, signed_value):

BadSignature: Signature 'Rs9orkssfJ0' does not match

exception in itsdangerous.py

Hey, guys!
I've passed a wrong token into TimedJSONWebSignatureSerializer::loads and got an exception in itsdangerous.py:380.
Here is a traceback:

Traceback (most recent call last):

  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/flask/app.py", line 2000, in __call__
    return self.wsgi_app(environ, start_response)
  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/flask/app.py", line 1991, in wsgi_app
    response = self.make_response(self.handle_exception(e))
  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/flask/app.py", line 1567, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/flask/app.py", line 1988, in wsgi_app
    response = self.full_dispatch_request()
  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/flask/app.py", line 1641, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/flask/app.py", line 1544, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/flask/app.py", line 1639, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/flask/app.py", line 1625, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/flask_httpauth.py", line 86, in decorated
    if not self.authenticate(auth, password):
  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/flask_httpauth.py", line 123, in authenticate
    return self.verify_password_callback(username, client_password)
  File "/Users/artem/projects/DotaAsker/server/app/views.py", line 41, in verify_password
    user = User.verify_auth_token(username_or_token)
  File "/Users/artem/projects/DotaAsker/server/app/models.py", line 146, in verify_auth_token
    data = s.loads(token)
  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/itsdangerous.py", line 795, in loads
    self, s, salt, return_header=True)
  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/itsdangerous.py", line 749, in loads
    self.make_signer(salt, self.algorithm).unsign(want_bytes(s)),
  File "/Users/artem/projects/DotaAsker/server/flask/lib/python2.7/site-packages/itsdangerous.py", line 368, in unsign
    if sep not in signed_value:
TypeError: argument of type 'NoneType' is not iterable

I've just expecting it to throw a BadSignature, but it seems that code didn't reach that line. Any suggestions?

How to return false rather than error message?

Hi ,I use the 0.24.

I use the URLSafeTimedSerializer, and loads with max_age.

When the signature was expired, I want to get the return value False rather than the error message, how I do?

itsdangerous.SignatureExpired: Signature age 1897 > 360 seconds

I have read the doc, but I haven't found the solution yet.

Thank you very much.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.