Ushka

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 SessionSecure Client-Side Session (HMAC-SHA256) with Timestamp.
class ServerSessionA session whose data lives in a SessionStore, not in the cookie.
def cookie_keys(config: Any) -> list[str] | None

The 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

NameTypeDescription
secret_keystr

A strong, random secret key used for signing the session data. Essential for security.

raw_cookie_valuestr

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 None.

max_ageint

The maximum age of the session in seconds. After this period, the session is considered expired. Defaults to 1209600 (14 days).

securebool

If True, the session cookie will only be transmitted over HTTPS. Defaults to True.

samesitestr

The SameSite attribute for the session cookie ('lax', 'strict', 'none'). Defaults to 'lax'.

Methods

__init__Initializes a new Session instance.
clearRemoves all items from the session and marks it as modified.
popRemoves the specified key from the session and returns its value.
updateUpdates the session with key-value pairs from another dictionary or iterable.
setdefaultInserts a key with a default value if the key is not already in the session.
get_response_headersGenerates 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

NameTypeDescription
secret_keystr

A strong, random secret key used for signing the session data.

raw_cookie_valuestr

The raw value of the session cookie received from the client.

max_ageint

The maximum age of the session in seconds. Defaults to 14 days.

securebool

If True, the session cookie will only be transmitted over HTTPS.

samesitestr

The SameSite attribute for the session cookie.

encrypt_keyslist of str

Fernet keys (the first encrypts, all decrypt). When given, the cookie holds an encrypted token instead of a signed payload ([session] encrypt); see cookie_keys.

clear

def clear() -> None

Removes all items from the session and marks it as modified.

pop

def pop(key: Any, default: Any = None) -> Any

Removes the specified key from the session and returns its value.

Marks the session as modified if the key existed.

Parameters

NameTypeDescription
keyAny

The key of the item to remove.

defaultAny

The value to return if the key is not found. Defaults to None.

Returns

TypeDescription
Any

The value associated with the key, or default if the key is not found.

update

def update(*args, **kwargs) -> None

Updates the session with key-value pairs from another dictionary or iterable.

Marks the session as modified if any updates occur.

Parameters

NameTypeDescription
*args

Positional arguments passed to the underlying dict.update method.

**kwargs

Keyword arguments passed to the underlying dict.update method.

setdefault

def setdefault(key: Any, default: Any = None) -> Any

Inserts 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

NameTypeDescription
keyAny

The key to check and potentially insert.

defaultAny

The value to insert if the key is not found. Defaults to None.

Returns

TypeDescription
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

loadBuilds the session of a request: from the store when the cookie is valid, empty otherwise (forged, unknown, revoked or expired).
revokeEnds the session: the record is deleted and the cookie expired. Anything written afterwards starts a new session with a new id.
clearSame as revoke(): logging out really invalidates the session.
rotateGives the session a new id and keeps its data. Call it at login, so an id planted beforehand (session fixation) is worthless. The first…
commitWrites 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,
) -> ServerSession

Builds the session of a request: from the store when the cookie is valid, empty otherwise (forged, unknown, revoked or expired).

revoke

def revoke() -> None

Ends the session: the record is deleted and the cookie expired. Anything written afterwards starts a new session with a new id.

clear

def clear() -> None

Same as revoke(): logging out really invalidates the session.

rotate

def rotate() -> None

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 time [session] user_key is set on a session, it rotates by itself.

commit

async def commit() -> None

Writes 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.