Skip to content

Expose the proxy-aware client IP used for session IP binding #87

Description

@allen0099

Problem

With ip_binding enabled, the middleware compares the session's stored ip_address with the address returned by _get_client_ip() (fastapi_cachex/session/middleware.py). When the request comes through one of SessionConfig.trusted_proxies, that address is taken from X-Forwarded-For / X-Real-IP (the rightmost untrusted X-Forwarded-For entry).

Applications pass ip_address to SessionManager.create_session() themselves. The natural value is request.client.host, which is also what the docs examples use. Behind a trusted proxy, however, that is the proxy's address. The IP stored at login therefore never matches the IP the middleware checks on later requests, and every bound session is rejected on its second request.

The helper that resolves the correct address is private, so applications must re-implement the trusted-proxy logic and keep it in sync.

Proposal

Make the resolution public, for example:

  • a function get_client_ip(request, config) -> str | None exported from fastapi_cachex.session, and/or
  • a FastAPI dependency (ClientIPDep) that uses the configured SessionConfig, and/or
  • an option for create_session() to take the IP (and User-Agent) from a Request directly, so the stored and checked values always come from the same code.

The same applies to user_agent, although it has no proxy subtlety.

Current documentation

docs/SESSION.md (since #85) warns about this when trusted_proxies is set.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requestsessionSession management subsystem

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions