# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-agent-to-agent-session-establishment-has-silently-degraded-to-unauthenticated-transport.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-agent-to-agent-session-establishment-has-silently-degraded-to-unauthenticated-transport.warrant.json
# Markdown SHA-256:   29716272f77978ddf6fa009115aa3a695385ed74564b0a26003f0e09d0e04809
# Code AST SHA-256:   499a16b03978e4d63c5f879c3dc7fd637dfa1aca5dd6d93c0366d9e13c6421de
# Verified Classes:   SessionIdentitySkewError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class SessionIdentitySkewError(RuntimeError):
    """Raised when a session's peer identity is inherited from a shared
    connection rather than re-derived from the per-request credential."""
    pass


def establish_session(request, connection_cache, session_store):
    """
    Enforce that session peer identity is derived per-request, not from the
    connection. connection_cache maps connection_id -> cached peer identity
    (advisory only). session_store maps session_id -> recorded peer identity.
    """
    session_id = request.headers.get("x-session-id")
    if not session_id:
        raise SessionIdentitySkewError("missing session identifier on request")

    # Authority: the credential presented on THIS request.
    request_identity = request.credential.subject
    if request_identity is None:
        raise SessionIdentitySkewError("request carries no authenticated subject")

    # Advisory: what the connection was originally opened for.
    cached_identity = connection_cache.get(request.connection_id)

    # Recorded: what the session store believes the peer is.
    recorded_peer = session_store.get_peer(session_id)

    # The invariant: all three must agree. Disagreement is silent degradation.
    if cached_identity is not None and cached_identity != request_identity:
        # Connection was opened for a different peer; it is shared substrate.
        # Evict rather than reuse, and reject this request on this connection.
        connection_cache.evict(request.connection_id)
        raise SessionIdentitySkewError(
            f"connection {request.connection_id} cached peer "
            f"{cached_identity!r} but request credential is "
            f"{request_identity!r}; refusing to inherit connection identity"
        )

    if recorded_peer is not None and recorded_peer != request_identity:
        raise SessionIdentitySkewError(
            f"session {session_id} recorded peer {recorded_peer!r} but "
            f"request credential is {request_identity!r}; "
            f"session peer identity is stale"
        )

    # Only now may we bind the session.
    session_store.bind_peer(session_id, request_identity)
    connection_cache.set(request.connection_id, request_identity)
    return {"session_id": session_id, "peer": request_identity}
