Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions backend/chat_gateway_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,12 +234,24 @@ def _external_turn_fence_headers(
]


def _chat_session_deleted(db: Session, session_id: str) -> bool:
def _session_store_rejection(
db: Session, token: str, session_id: str, turn_id: str
) -> HTTPException:
try:
chat_session_id = uuid.UUID(session_id)
chat_turn_id = uuid.UUID(turn_id)
except ValueError:
return False
return db.get(ChatSession, chat_session_id) is None
return HTTPException(status_code=403, detail="Capability rejected")
if db.get(ChatSession, chat_session_id) is None:
return HTTPException(status_code=404, detail="Chat session not found")
if ChatCapabilityService(db).revoked(
token,
scope="session_store",
chat_session_id=chat_session_id,
turn_id=chat_turn_id,
):
return HTTPException(status_code=410, detail="Chat turn has ended")
return HTTPException(status_code=403, detail="Capability rejected")


def _scope(
Expand All @@ -262,10 +274,8 @@ def _scope(
)
except (CapabilityError, ValueError):
db.rollback()
if scope == "session_store" and _chat_session_deleted(db, session_id):
raise HTTPException(
status_code=404, detail="Chat session not found"
) from None
if scope == "session_store":
raise _session_store_rejection(db, token, session_id, turn_id) from None
raise HTTPException(status_code=403, detail="Capability rejected") from None
if "external_turn" not in row.scopes:
return row
Expand Down
21 changes: 21 additions & 0 deletions backend/services/chat_capability_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,27 @@ def meter_hf_catalog(
row.hf_recursive_list_calls += 1
self.db.flush()

def revoked(
self,
token: str,
*,
scope: str,
chat_session_id: uuid.UUID,
turn_id: uuid.UUID,
) -> bool:
row = self.db.execute(
select(ChatTurnCapability).where(
ChatTurnCapability.token_hash == _digest(token)
)
).scalar_one_or_none()
return (
row is not None
and row.revoked_at is not None
and row.chat_session_id == chat_session_id
and row.turn_id == turn_id
and scope in row.scopes
)

def revoke(self, capability_id: uuid.UUID) -> bool:
row = self.db.get(ChatTurnCapability, capability_id)
if row is None or row.revoked_at is not None:
Expand Down
17 changes: 11 additions & 6 deletions backend/tests/chat_gateway/test_turn_fence.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,17 +578,22 @@ def _reject_capability(*_args, **_kwargs):


@pytest.mark.parametrize(
("scope", "chat_exists", "status_code"),
("scope", "chat_exists", "revoked", "status_code"),
[
("session_store", False, 404),
("session_store", True, 403),
("model", False, 403),
("session_store", False, False, 404),
("session_store", True, True, 410),
("session_store", True, False, 403),
("model", False, False, 403),
("model", True, True, 403),
],
)
def test_rejected_capability_is_404_only_for_a_deleted_chat_session_store(
monkeypatch, scope, chat_exists, status_code
def test_rejected_session_store_capability_reports_a_deleted_chat_or_ended_turn(
monkeypatch, scope, chat_exists, revoked, status_code
):
monkeypatch.setattr(gateway.ChatCapabilityService, "validate", _reject_capability)
monkeypatch.setattr(
gateway.ChatCapabilityService, "revoked", lambda *_args, **_kwargs: revoked
)
db = FenceDB(on_get=lambda *_args: object() if chat_exists else None)

with pytest.raises(HTTPException) as error:
Expand Down
39 changes: 39 additions & 0 deletions backend/tests/chat_sandbox/test_provider_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,45 @@ def flush(self):
)


def test_capability_reports_revocation_only_for_its_own_turn_and_scope():
session_id = uuid.uuid4()
turn_id = uuid.uuid4()
token = "revoked-test-token"
row = ChatTurnCapability(
id=uuid.uuid4(),
token_hash=_digest(token),
chat_session_id=session_id,
turn_id=turn_id,
scopes=["session_store"],
expires_at=datetime.now(UTC) + timedelta(minutes=1),
)

class Result:
def scalar_one_or_none(self):
return row

class DB:
def execute(self, _query):
return Result()

service = ChatCapabilityService(DB())

def revoked(**overrides):
arguments = {
"scope": "session_store",
"chat_session_id": session_id,
"turn_id": turn_id,
} | overrides
return service.revoked(token, **arguments)

assert not revoked()
row.revoked_at = datetime.now(UTC)
assert revoked()
assert not revoked(scope="model")
assert not revoked(turn_id=uuid.uuid4())
assert not revoked(chat_session_id=uuid.uuid4())


def test_workspace_snapshot_provider_only_snapshots_workspace():
calls: list[tuple[str, int, int]] = []

Expand Down
7 changes: 4 additions & 3 deletions docs/autonomous-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,10 @@ outage. The latency rule
fired in 4 of 1,222 windows. Existing sanitized operational counters still
supply persistence and capacity failures.

A session-store call for a chat the user deleted mid-turn returns 404, not 403,
so the `session_store_forbidden` runtime alert counts only real capability
rejections.
A session-store call for a chat the user deleted mid-turn returns 404, and one
whose turn already ended (the user pressed stop, which revokes the turn's
capability) returns 410, not 403. The `session_store_forbidden` runtime alert
therefore counts only real capability rejections.

A separately allowlisted synthetic job (`run_chat_synthetic_probe`,
`pwc-cron-run-chat-synthetic-probe.timer`) polls its due/trigger state every minute
Expand Down
Loading