ushka.sessions.session
This module provides the Session class, a secure client-side session manager
for the Ushka framework.
It implements HMAC-SHA256 for data integrity and timestamp-based validation
to prevent replay attacks, ensuring that session data stored in cookies is
tamper-proof and has a defined lifespan. With [session] encrypt = true the
cookie is a Fernet token instead: tamper-proof, expiring and unreadable.
In this module
def cookie_keys() | The Fernet keys that encrypt the session cookie, or None when [session] encrypt is off (the cookie is only signed). |
class Session | Secure Client-Side Session (HMAC-SHA256) with Timestamp. |
class ServerSession | A session whose data lives in a SessionStore, not in the cookie. |
def cookie_keys
def cookie_keys(config: Any) -> list[str] | NoneThe Fernet keys that encrypt the session cookie, or None when
[session] encrypt is off (the cookie is only signed).
class Session (dict)
Secure Client-Side Session (HMAC-SHA256) with Timestamp.
This class extends dict to provide a secure, client-side session mechanism.
It uses HMAC-SHA256 for data integrity and includes a timestamp to prevent
replay attacks and enforce session expiration.
Parameters
| Name | Type | Description |
|---|---|---|
secret_key | str | A strong, random secret key used for signing the session data. Essential for security. |
raw_cookie_value | str | The raw value of the session cookie received from the client.
If provided, the session data will be decoded and validated from this.
Defaults to |
max_age | int | The maximum age of the session in seconds. After this period, the session is considered expired. Defaults to 1209600 (14 days). |
secure | bool | If |
samesite | str | The |
Methods
__init__ | Initializes a new Session instance. |
clear | Removes all items from the session and marks it as modified. |
pop | Removes the specified key from the session and returns its value. |
update | Updates the session with key-value pairs from another dictionary or iterable. |
setdefault | Inserts a key with a default value if the key is not already in the session. |
get_response_headers | Generates the Set-Cookie header ready for the WSGI/ASGI server. |
__init__
def __init__(
secret_key: str,
raw_cookie_value: str | None = None,
max_age: int = 1209600,
secure: bool = True,
samesite: str = 'lax',
encrypt_keys: list[str] | None = None,
)Initializes a new Session instance.
Parameters
| Name | Type | Description |
|---|---|---|
secret_key | str | A strong, random secret key used for signing the session data. |
raw_cookie_value | str | The raw value of the session cookie received from the client. |
max_age | int | The maximum age of the session in seconds. Defaults to 14 days. |
secure | bool | If |
samesite | str | The |
encrypt_keys | list of str | Fernet keys (the first encrypts, all decrypt). When given, the
cookie holds an encrypted token instead of a signed payload
( |
clear
def clear() -> NoneRemoves all items from the session and marks it as modified.
pop
def pop(key: Any, default: Any = None) -> AnyRemoves the specified key from the session and returns its value.
Marks the session as modified if the key existed.
Parameters
| Name | Type | Description |
|---|---|---|
key | Any | The key of the item to remove. |
default | Any | The value to return if the key is not found. Defaults to |
Returns
| Type | Description |
|---|---|
Any | The value associated with the key, or |
update
def update(*args, **kwargs) -> NoneUpdates the session with key-value pairs from another dictionary or iterable.
Marks the session as modified if any updates occur.
Parameters
| Name | Type | Description |
|---|---|---|
*args | Positional arguments passed to the underlying | |
**kwargs | Keyword arguments passed to the underlying |
setdefault
def setdefault(key: Any, default: Any = None) -> AnyInserts a key with a default value if the key is not already in the session.
Marks the session as modified if the key is newly inserted.
Parameters
| Name | Type | Description |
|---|---|---|
key | Any | The key to check and potentially insert. |
default | Any | The value to insert if the key is not found. Defaults to |
Returns
| Type | Description |
|---|---|
Any | The value for the key (either existing or newly inserted). |
get_response_headers
def get_response_headers() -> list[tuple[bytes, bytes]]Generates the Set-Cookie header ready for the WSGI/ASGI server.
class ServerSession (Session)
A session whose data lives in a SessionStore, not in the cookie.
The cookie holds only <id>.<signature>: an unguessable random id signed
with the secret key. Revoking the session deletes the record, so a copied
cookie stops working at once. There is no 4 KB limit, and values must be
JSON serializable.
Create it with ServerSession.load(); the response saves it (commit).
Use revoke() (or clear()) to log out, rotate() to change the id at
login, and revoke_user_sessions() to log a user out everywhere.
Methods
load | Builds the session of a request: from the store when the cookie is valid, empty otherwise (forged, unknown, revoked or expired). |
revoke | Ends the session: the record is deleted and the cookie expired. Anything written afterwards starts a new session with a new id. |
clear | Same as revoke(): logging out really invalidates the session. |
rotate | Gives the session a new id and keeps its data. Call it at login, so an id planted beforehand (session fixation) is worthless. The first… |
commit | Writes the changes to the store. The response calls it. A session nobody changed costs one read, plus an occasional last_seen update when… |
load
@classmethod
async def load(
store: Any,
raw_cookie_value: str | None,
**options: Any,
) -> ServerSessionBuilds the session of a request: from the store when the cookie is valid, empty otherwise (forged, unknown, revoked or expired).
revoke
def revoke() -> NoneEnds the session: the record is deleted and the cookie expired. Anything written afterwards starts a new session with a new id.
clear
def clear() -> NoneSame as revoke(): logging out really invalidates the session.
rotate
def rotate() -> NoneGives the session a new id and keeps its data. Call it at login, so
an id planted beforehand (session fixation) is worthless. The first
time [session] user_key is set on a session, it rotates by itself.
commit
async def commit() -> NoneWrites the changes to the store. The response calls it. A session
nobody changed costs one read, plus an occasional last_seen
update when there is an idle timeout.