Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Patch Session Expiry for EncryptedCookieStorage #326

Merged
merged 1 commit into from
Oct 10, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion aiohttp_session/cookie_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async def load_session(self, request):
try:
data = self._decoder(
self._fernet.decrypt(
cookie.encode('utf-8')).decode('utf-8'))
cookie.encode('utf-8'), ttl=self.max_age).decode('utf-8'))
return Session(None, data=data,
new=False, max_age=self.max_age)
except InvalidToken:
Expand Down
37 changes: 36 additions & 1 deletion tests/test_encrypted_cookie_storage.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import json
import base64
import time
Expand All @@ -7,10 +8,13 @@

from cryptography.fernet import Fernet

from aiohttp_session import Session, session_middleware, get_session
from aiohttp_session import Session, session_middleware, get_session, new_session
from aiohttp_session.cookie_storage import EncryptedCookieStorage


MAX_AGE = 1


def make_cookie(client, fernet, data):
session_data = {
'session': data,
Expand Down Expand Up @@ -160,3 +164,34 @@ async def logout(request):
client.session.cookie_jar.update_cookies({'AIOHTTP_SESSION': evil_cookie})
resp = await client.get('/')
assert resp.cookies['AIOHTTP_SESSION'].value != evil_cookie


async def test_fernet_ttl(aiohttp_client, fernet, key):
async def login(request):
session = await new_session(request)
session['created'] = int(time.time())
return web.Response()

async def handler(request):
session = await get_session(request)
now = time.time()
created = session['created'] if not session.new else None
text = ''
if created is not None and (time.time() - created) > MAX_AGE:
text += 'WARNING!'
return web.Response(text=text)

middleware = session_middleware(EncryptedCookieStorage(key, max_age=MAX_AGE))
app = web.Application(middlewares=[middleware])
app.router.add_route('POST', '/', login)
app.router.add_route('GET', '/', handler)

client = await aiohttp_client(app)
resp = await client.post('/')
assert 'AIOHTTP_SESSION' in resp.cookies
cookie = resp.cookies['AIOHTTP_SESSION'].value
await asyncio.sleep(MAX_AGE + 1)
client.session.cookie_jar.update_cookies({'AIOHTTP_SESSION': cookie})
resp = await client.get('/')
body = await resp.text()
assert body == ''