pyramid_nacl_session
¶
- This Pyramid add-on defines an encrypting, pickle-based cookie serializer,
- using
PyNaCl
[1] to generate the symmetric encryption for the cookie state.
[1] https://pynacl.readthedocs.io/en/latest/secret/
Contents:
Using pyramid_nacl_session
¶
Setup¶
Once pyramid_nacl_session
is installed, you typically use the
config.include
mechanism to include it into your Pyramid project’s
configuration.
In your Pyramid project’s __init__.py
:
with Configurator(settings=settings) as config:
config.include('pyramid_nacl_session')
# ... more config.includes
config.scan()
Alternately, instead of using the Configurator’s include
method, you can
activate pyramid_nacl_session
by changing your application’s .ini
file, using the following line:
pyramid.includes = pyramid_nacl_session
Usage¶
Generate a secret key¶
To facilitate sharing the secret across instances, pyramid_nacl_session
provides a print_secret
script, which generates and hexlifies a random
secret, printing it to standard output:
$ bin/print_secret
840aaafdc36f067fbad9baf006efc0f672b86ab0dcb6a3e43ecc1f9d760915e5
Cut-and-paste into your config file:
session.secret =
840aaafdc36f067fbad9baf006efc0f672b86ab0dcb6a3e43ecc1f9d760915e5
Session management¶
If you have included pyramid_nacl_session
in your Pyramid project’s
configuration as shown above then
pyramid_nacl_session.session_factory_from_settings()
is called
automatically and you need do nothing else.
Otherwise you will need to create a Pyramid session factory by adding a
call to either the pyramid_nacl_session.EncryptedCookieSessionFactory()
function or the pyramid_nacl_session.session_factory_from_settings()
function in the configuration code of your Pyramid project’s __init__.py
file and subsequently register that session factory with Pyramid.
At that point, accessing request.session
will provide a Pyramid session
using PyNaCl as a backend.
pyramid_nacl_session.session_factory_from_settings()
obtains session
settings from the **settings
dictionary passed to the Configurator.
It assumes that you’ve placed session configuration parameters prefixed with
session.
in your Pyramid application’s .ini
file.
For example:
[app:myapp]
# other settings
session.secret = 840aaafdc36f067fbad9baf006efc0f672b86ab0dcb6a3e43ecc1f9d760915e5
session.serializer = json
If your .ini
file has such settings, you can use
pyramid_nacl_session.session_factory_from_settings()
in your
application’s configuration.
For example, let’s assume this code is in the __init__.py
of your Pyramid
application that uses an .ini
file with the session.
settings above to
obtain its **settings
dictionary.
from pyramid_nacl_session import session_factory_from_settings
from pyramid.config import Configurator
def app(global_config, **settings):
""" This function returns a WSGI application.
It is usually called by the PasteDeploy framework during
``paster serve``.
"""
session_factory = session_factory_from_settings(settings)
with Configurator(settings=settings) as config:
config.set_session_factory(session_factory)
# other configuration stuff
return config.make_wsgi_app()
pyramid_nacl_session
API Reference¶
-
class
pyramid_nacl_session.
EncryptedSerializer
(secret, serializer=None)¶ Encrypt session state using PyNaCl.
Parameters: - secret (bytes) – a 32-byte random secret for encrypting/decrypting the pickled session state.
- serializer – An object with two methods:
loads
anddumps
. Theloads
method should accept bytes and return a Python object. Thedumps
method should accept a Python object and return bytes. AValueError
should be raised for malformed inputs. Default:None
, which will usepyramid.session.PickleSerializer
.
-
pyramid_nacl_session.
EncryptedCookieSessionFactory
(secret, cookie_name='session', max_age=None, path='/', domain=None, secure=False, httponly=False, timeout=1200, reissue_time=0, set_on_exception=True, serializer=None, samesite='Lax')¶ Configure a session factory which will provide encrypted cookie-based sessions. The return value of this function is a session factory which may be used with the
pyramid.config.Configurator.set_session_factory()
method.The session factory returned by this function will create sessions which are limited to storing fewer than 4000 bytes of data (as the payload must fit into a single cookie).
Parameters:
secret
- A string which is used to sign the cookie. The secret should be at
least as long as the block size of the selected hash algorithm. For
sha512
this would mean a 128 bit (64 character) secret. It should be unique within the set of secret values provided to Pyramid for its various subsystems (see Admonishment Against Secret-Sharing). cookie_name
- The name of the cookie used for sessioning. Default:
'session'
. max_age
- The maximum age of the cookie used for sessioning (in seconds).
Default:
None
(browser scope). path
- The path used for the session cookie. Default:
'/'
. domain
- The domain used for the session cookie. Default:
None
(no domain). secure
- The ‘secure’ flag of the session cookie. Default:
False
. httponly
- Hide the cookie from Javascript by setting the ‘HttpOnly’ flag of the
session cookie. Default:
False
. samesite
- The ‘samesite’ option of the session cookie. Set the value to
None
to turn off the samesite option. Default:'Lax'
. timeout
- A number of seconds of inactivity before a session times out. If
None
then the cookie never expires. This lifetime only applies to the value within the cookie. Meaning that if the cookie expires due to a lowermax_age
, then this setting has no effect. Default:1200
. reissue_time
- The number of seconds that must pass before the cookie is automatically
reissued as the result of accessing the session. The
duration is measured as the number of seconds since the last session
cookie was issued and ‘now’. If this value is
0
, a new cookie will be reissued on every request accessing the session. IfNone
then the cookie’s lifetime will never be extended. A good rule of thumb: if you want auto-expired cookies based on inactivity: set thetimeout
value to 1200 (20 mins) and set thereissue_time
value to perhaps a tenth of thetimeout
value (120 or 2 mins). It’s nonsensical to set thetimeout
value lower than thereissue_time
value, as the ticket will never be reissued. However, such a configuration is not explicitly prevented. Default:0
. set_on_exception
- If
True
, set a session cookie even if an exception occurs while rendering a view. Default:True
. serializer
- An object with two methods:
loads
anddumps
. Theloads
method should accept bytes and return a Python object. Thedumps
method should accept a Python object and return bytes. AValueError
should be raised for malformed inputs. If a serializer is not passed, thepyramid.session.PickleSerializer
serializer will be used.
-
pyramid_nacl_session.
generate_secret
(as_hex=True)¶ Generate a random, 32-byte secret.
Parameters: as_hex (boolean) – If true, convert the secret to hex. Return type: bytes Returns: the secret (perhaps converted to hex).
-
pyramid_nacl_session.
session_factory_from_settings
(settings)¶ Return a Pyramid session factory using PyNaCl session settings supplied from a Paste configuration file.
Changelog¶
1.0.0 (2020-08-17)¶
- Add
session_factory_from_settings
andincludeme
. See https://github.com/Pylons/pyramid_nacl_session/pull/11 - Support the
samesite
option and default toLax
. See https://github.com/Pylons/pyramid_nacl_session/pull/14 - Drop Python 2.6, 3.3, and 3.4 support.
- Add Python 3.6, 3.7 and 3.8 support.
0.3 (2016-02-16)¶
- Drop Python 3.2 support.
- Drop the trailing padding (
=
) from base64 content. See https://github.com/Pylons/pyramid_nacl_session/pull/7 - Add the
EncryptedCookieSessionFactory
as the primary API for using an encrypted session. See https://github.com/Pylons/pyramid_nacl_session/pull/6
0.2 (2015-11-23)¶
- Split the
EncryptingPickleSerializer
intoEncryptedSerializer
with a default dependency onpyramid.session.PickleSerializer
allowing alternative serializers to be used with the encryption interface. See https://github.com/Pylons/pyramid_nacl_session/pull/4
0.1 (2015-11-23)¶
- Initial release.