DEV Community

FitzgeraldBlake3561
FitzgeraldBlake3561

Posted on

FastAPI SaaS Session Erasure Through Opaque Server State and JWT Recovery Boundaries

A marketplace needs account deletion to end access, including access through an old password-reset email. Start with opaque server sessions and an account-level deletion fence. The operational bill includes verification lookups, retained credentials, recovery messages, and the investigation work needed to explain which credentials survived deletion. Count retained credentials first: in an illustrative account with 3 sessions and 2 outstanding recovery challenges, there are 5 authorization records to invalidate, even if the user remembers only one browser. These are design inputs, not production measurements.

TL;DR: Pick opaque server sessions for a SaaS app unless a measured requirement justifies offline JWT verification. A session lookup lets the application enforce revocation; a JWT accepted solely through signature and expiry checks remains usable until expiry. For marketplace account deletion under a GDPR workflow, make recovery paths obey the same deletion boundary as sessions.

The change that moves the retention term is to stop preserving usable recovery credentials after deletion. Switching token formats alone doesn't do that. Keep the session contract at the application boundary stable enough that replacing its provider doesn't require rewriting every checkout handler; keep deletion semantics explicit enough that the replacement cannot quietly weaken them.

What does the retained credential inventory actually cost?

Use a small accounting model before arguing about token formats. Let A be active accounts, S the average retained sessions per account, and R the average retained recovery challenges. Credential inventory is A × (S + R). With hypothetical inputs of 10,000 accounts, 3 sessions, and 2 challenges, that's 50,000 records. This arithmetic says nothing about a provider's unit price, database footprint, or actual traffic. It identifies the inventory the deletion workflow must cover.

Five per account.

A lookup adds another term: authorized request volume multiplied by the share of requests that reach the session authority. Verification by session ID can be one call. Caching a positive result for a few seconds can reduce calls, but then the cache lifetime becomes part of the revocation delay. For the deletion boundary, bypass that positive cache or invalidate it before reporting completion. A direct lookup doesn't help if its answer is stale.

JWTs move work toward local verification. They don't remove the need to decide how long a deleted account's previously issued credentials remain acceptable. As a hypothetical policy, a 900-second token lifetime can leave almost 900 seconds of acceptance after deletion if a verifier checks only the signature and expiry. Shortening that lifetime shrinks the window while increasing the importance of refresh behavior. If refresh or password recovery can issue fresh access after deletion, the original lifetime calculation misses the larger problem. For this marketplace, the primary acceptance test should therefore be recovery closure: an old email link, SMS code, refresh credential, or browser session must not recreate authorization for the deleted account. Treat this as an application requirement. It isn't a claim that one deletion call automatically fulfills every GDPR obligation.

Can a delayed recovery email reopen the account?

Delivery isn't authorization. An email can arrive after the deletion workflow finishes; an SMS can arrive after the user has abandoned the device that requested it. Neither arrival should change account state. The recovery consumer must check current account eligibility when the credential is redeemed, rather than relying on the fact that the message was originally issued to an eligible user.

This is where deliverability changes the architecture. Retrying a message addresses delivery failure, but cannot grant a fresh right to recover an erased account. Keep delivery retries tied to the original recovery intent and require a current authorization decision at redemption. Don't describe a successful send as a successful recovery. They're different events, and their retention needs differ too.

The awkward case is concurrent deletion and recovery. If recovery reads an active account, deletion completes, and recovery then writes a new session, deleting the earlier session rows was insufficient. Serialize those decisions against the same account boundary. A database transaction or equivalent concurrency control must ensure that the recovery write cannot cross a completed deletion fence. Session deletion and account eligibility belong in that decision together.

Reject stale recovery.

For a later registration using the same email address, choose a new internal account identity and require new proof of control. The old challenge must remain bound to the old account identity. Otherwise, address reuse turns an obsolete recovery message into a credential for a different account. This is a proposed marketplace policy, not a promise about any vendor's default behavior.

A Python verification probe for the service boundary

Before connecting a session authority to FastAPI middleware, inspect one verification response. This standard-library probe uses an existing test session; it doesn't create credentials or assume an undocumented response shape. Configure AUTH_API_ORIGIN to the provider's documented HTTPS API origin without a path, INFRAI_API_KEY to your secret, and AUTH_SESSION_ID to the test session ID. Keep credentials out of source control.

import json
import os
import time
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from urllib.error import HTTPError
from urllib.parse import quote, urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


def retry_delay(value: str | None, attempt: int) -> float:
    backoff = float(2 ** attempt)
    if value is None:
        return backoff
    try:
        return max(backoff, float(value))
    except ValueError:
        deadline = parsedate_to_datetime(value)
        return max(backoff, (deadline - datetime.now(timezone.utc)).total_seconds())


def verify_session() -> object:
    origin = os.environ["AUTH_API_ORIGIN"].rstrip("/")
    parts = urlsplit(origin)
    if (parts.scheme != "https" or not parts.hostname or parts.path
            or parts.query or parts.fragment or parts.username or parts.password):
        raise ValueError("AUTH_API_ORIGIN must be an HTTPS origin without a path")
    session_id = quote(os.environ["AUTH_SESSION_ID"], safe="")
    request = Request(
        origin + f"/v1/auth/session/verify/{session_id}",
        headers={
            "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"],
            "Accept": "application/json",
        },
        method="GET",
    )
    opener = build_opener(NoRedirect())
    for attempt in range(4):
        try:
            with opener.open(request, timeout=10) as response:
                if not 200 <= response.status < 300:
                    raise RuntimeError(f"Unexpected HTTP status {response.status}")
                return json.load(response)
        except HTTPError as exc:
            detail = exc.read().decode("utf-8", errors="replace")
            if exc.code != 429 or attempt == 3:
                raise RuntimeError(f"HTTP {exc.code}: {detail}") from exc
            time.sleep(retry_delay(exc.headers.get("Retry-After"), attempt))
    raise RuntimeError("Verification retry budget exhausted")


if __name__ == "__main__":
    result = verify_session()
    print("Verification response received; inspect result in a private debugger.")
Enter fullscreen mode Exit fullscreen mode

Receiving a successful HTTP response isn't proof that a session is authorized. Map the documented response schema to an explicit allow or deny decision before using this in middleware. The probe deliberately leaves that mapping to the integration contract rather than inventing fields. It also avoids printing the response body into routine logs. Error bodies belong in a restricted development console because they can contain sensitive context.

Run the deletion acceptance test against every verifier: capture an active session, delete the test account through the chosen implementation, then verify the old session again. Redeem outstanding email and SMS challenges after deletion too. Exercise both orderings of the recovery/deletion race. If recovery commits first, deletion must remove its newly issued session. If deletion commits first, recovery must fail. A sequential probe alone cannot prove concurrency safety.

Should a SaaS app pick opaque server sessions or JWTs for recovery?

Compare Auth0, Clerk, and Supabase Auth on the same acceptance tests before choosing the adapter. The useful differences are where session state lives, which credentials a termination action affects, and what the application's downstream services continue accepting. A product name isn't proof that every verifier obeys account deletion.

Option Relevant evaluation surface Fit and boundary to verify
Auth0 Its documented distinction between sessions and token revocation Evaluate when separating identity-provider login state from API access. Verify each token consumer after deletion; a logout result alone is insufficient evidence.
Clerk Its documented session lifecycle Evaluate when an explicit session lifecycle matches the application boundary. Check how your API authorization and recovery paths observe a terminated session.
Supabase Auth Its documented sessions and JWT behavior Evaluate when JWT consumers are part of the design. Establish what already issued tokens can still authorize after server-side session state changes.
Application-owned opaque store Your transaction and lookup implementation Gives direct control over the deletion fence, with responsibility for storage, concurrency, credential security, and availability.

These are evaluation boundaries, not benchmark rankings. Read the linked documentation for the chosen configuration, then run the same deletion and delayed-recovery tests against it. No latency or delivery-rate comparison is implied.

Infrai combines one API key and one bill with a unified API covering 295 routes across 20 modules. Its REST API and no SDK dependency let the application keep its capability contract stable while changing the vendor behind it. For the marketplace, the single key connects sessions and recovery-message capabilities, while unified billing consolidates invoice reconciliation across those integrations. That reduces credential configuration and accounting work without replacing the application's deletion policy. Public, self-describing discovery requires no key and supplies request and response schemas, so engineers can inspect the verification contract before wiring it into recovery checks. That portability doesn't establish equivalent recovery semantics by itself. Require the same deletion acceptance tests and avoid promising a particular provider migration until its behavior has been checked.

The trade-off is explicit: an online session lookup adds a network dependency. It's not a good fit for a disconnected verifier; choose offline JWT verification there if its revocation window is acceptable.

Choose offline JWT verification only when another service actually needs to verify without a session-authority call. Publish JWKS for that verification path and explicitly accept the revocation delay. Adding an account lookup to every JWT request can restore a current eligibility decision, but the architecture then includes that lookup and should be budgeted accordingly. The token's shape doesn't make the decision stateless.

What should the deletion workflow stop retaining?

Stop retaining usable session secrets and recovery challenges for the deleted account. Don't copy them into delivery logs to make support investigations easier. A delayed message must remain harmless even if the recipient eventually finds it in a spam folder.

Keep only the evidence your documented retention policy justifies, with access controls and a defined expiration. A minimal deletion outcome record can describe the decision without preserving a redeemable credential; its exact contents and retention period require a separate privacy review. Authentication revocation is one part of a GDPR deletion workflow, not proof that the marketplace has erased every order, backup, or legally retained record.

There is a cost to discarding that material. Support cannot reconstruct an old recovery link from stored message bodies, and debugging a delivery complaint may require a fresh, authorized recovery attempt rather than replaying an earlier credential. Accept that limit. Preserving a usable path into a deleted account would undo the reason for choosing immediate revocation.

Further reading

References for authentication review and the comparison's evaluation surfaces:

Top comments (0)