update session

This commit is contained in:
2025-10-10 12:52:41 -03:00
parent 2de2d4dc0e
commit c9438d49fb
15 changed files with 116 additions and 112 deletions

View File

@@ -1,6 +1,5 @@
from http.cookies import SimpleCookie
import jwt
from authlib.oauth2.rfc6749 import errors
from authlib.oauth2.rfc6749.util import scope_to_list
from aws_lambda_powertools import Logger
@@ -9,12 +8,12 @@ from aws_lambda_powertools.event_handler.exceptions import (
BadRequestError,
ForbiddenError,
ServiceError,
UnauthorizedError,
)
from joserfc.errors import JoseError
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair, SortKey
from boto3clients import dynamodb_client
from config import ISSUER, OAUTH2_TABLE, SESSION_SECRET
from config import OAUTH2_TABLE
from oauth2 import server
router = Router()
@@ -26,19 +25,24 @@ dyn = DynamoDBPersistenceLayer(OAUTH2_TABLE, dynamodb_client)
def authorize():
current_event = router.current_event
cookies = _parse_cookies(current_event.get('cookies', []))
session_id = cookies.get('session_id')
session = cookies.get('__session')
if not session_id:
raise BadRequestError('Missing session_id')
if not session:
raise BadRequestError('Missing session')
try:
sub, session_scope = verify_session(session_id)
sid, sub = session.split(':')
# Raise if session is not found
dyn.collection.get_item(
KeyPair('SESSION', sid),
exc_cls=InvalidSession,
)
grant = server.get_consent_grant(
request=router.current_event,
end_user=sub,
)
user_scopes = _user_scopes(sub)
client_scopes = set(scope_to_list(grant.client.scope))
user_scopes = set(scope_to_list(session_scope)) if session_scope else set()
# Deny authorization if user lacks scopes requested by client
if not client_scopes.issubset(user_scopes):
@@ -49,7 +53,7 @@ def authorize():
grant_user=sub,
grant=grant,
)
except jwt.exceptions.InvalidTokenError as err:
except JoseError as err:
logger.exception(err)
raise BadRequestError(str(err))
except errors.OAuth2Error as err:
@@ -60,39 +64,19 @@ def authorize():
)
def verify_session(session_id: str) -> tuple[str, str | None]:
payload = jwt.decode(
session_id,
SESSION_SECRET,
algorithms=['HS256'],
issuer=ISSUER,
options={
'require': ['exp', 'sub', 'iss', 'sid'],
},
)
user = dyn.collection.get_items(
KeyPair(
pk='SESSION',
sk=payload['sid'],
rename_key='session',
def _user_scopes(sub: str) -> set:
return set(
scope_to_list(
dyn.collection.get_item(
KeyPair(
pk=sub,
sk=SortKey(sk='SCOPE', path_spec='scope'),
),
exc_cls=BadRequestError,
)
)
+ KeyPair(
pk=payload['sub'],
sk=SortKey(
sk='SCOPE',
path_spec='scope',
rename_key='scope',
),
),
flatten_top=False,
)
if 'session' not in user:
raise SessionRevokedError('Session revoked')
return payload['sub'], user.get('scope')
def _parse_cookies(cookies: list[str] | None) -> dict[str, str]:
parsed_cookies = {}
@@ -108,4 +92,4 @@ def _parse_cookies(cookies: list[str] | None) -> dict[str, str]:
return parsed_cookies
class SessionRevokedError(UnauthorizedError): ...
class InvalidSession(BadRequestError): ...

View File

@@ -3,7 +3,6 @@ from typing import Annotated
from uuid import uuid4
import boto3
import jwt
from aws_lambda_powertools.event_handler import (
Response,
)
@@ -17,10 +16,8 @@ from passlib.hash import pbkdf2_sha256
from boto3clients import dynamodb_client
from config import (
ISSUER,
OAUTH2_TABLE,
SESSION_EXPIRES_IN,
SESSION_SECRET,
)
router = Router()
@@ -45,7 +42,7 @@ def session(
status_code=HTTPStatus.OK,
cookies=[
Cookie(
name='session_id',
name='__session',
value=new_session(user_id),
http_only=True,
secure=True,
@@ -127,26 +124,15 @@ def _get_idp_user(
def new_session(sub: str) -> str:
session_id = str(uuid4())
sid = str(uuid4())
now_ = now()
exp = ttl(start_dt=now_, seconds=SESSION_EXPIRES_IN)
token = jwt.encode(
{
'sid': session_id,
'sub': sub,
'iss': ISSUER,
'iat': int(now_.timestamp()),
'exp': exp,
},
SESSION_SECRET,
algorithm='HS256',
)
with dyn.transact_writer() as transact:
transact.put(
item={
'id': 'SESSION',
'sk': session_id,
'sk': sid,
'user_id': sub,
'ttl': exp,
'created_at': now_,
@@ -155,13 +141,13 @@ def new_session(sub: str) -> str:
transact.put(
item={
'id': sub,
'sk': f'SESSION#{session_id}',
'sk': f'SESSION#{sid}',
'ttl': exp,
'created_at': now_,
}
)
return token
return f'{sid}:{sub}'
class UserNotFoundError(NotFoundError):