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
32 changes: 27 additions & 5 deletions api/oss/src/apis/fastapi/sessions/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -1055,15 +1055,39 @@ async def set_session_stream_header(

`visibility` is the visibility a header call that creates the session asks for. It
is ignored on an existing session, and a `private` without an owner is dropped.
A call with a `visibility` may carry no header field: it only creates the session
(the /w pre-create of a new chat) and changes nothing on an existing one. Without
a `visibility`, a body with no header field (an empty or wrapped body) is refused.
"""
if not header.has_header_field and visibility is None:
# The body validation error FastAPI answered before this rule moved here.
raise HTTPException(
status_code=422,
detail=[
{
"type": "value_error",
"loc": ["body"],
"msg": "Value error, no header field to update; send name or "
"description at the top level",
"input": {},
}
],
)
_validate_session_id_http(session_id)
resolved_source = _resolve_name_source(name_source=name_source, author=author)

# A header call on an unknown id creates the session, so a hidden one answers
# the one canonical not-found body.
# the one canonical not-found body. A call with no header field changes nothing
# on an existing session: it is part of sending a new chat's first message, so it
# needs what a send needs (a member may send into a colleague's project chat).
action = (
Permission.EDIT_SESSIONS
if header.has_header_field
else Permission.RUN_SESSIONS
)
if not await allow_resource(
request,
action=Permission.EDIT_SESSIONS,
action=action,
resource=session_resource(session_id),
):
raise not_found_exception()
Expand All @@ -1077,9 +1101,7 @@ async def set_session_stream_header(
access=policy_for_request(
request, kind=SharedItemKind.SESSION, requested=visibility
),
recheck=session_recheck(
request, action=Permission.EDIT_SESSIONS, session_id=session_id
),
recheck=session_recheck(request, action=action, session_id=session_id),
)
return SessionStreamResponse(stream=sanitize_session_stream(stream))

Expand Down
14 changes: 6 additions & 8 deletions api/oss/src/core/sessions/streams/dtos.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
Field,
PrivateAttr,
field_validator,
model_validator,
)

from agenta.sdk.models.workflows import WorkflowServiceRequestData
Expand Down Expand Up @@ -200,13 +199,12 @@ def _trim_a_name(cls, value: Optional[str]) -> Optional[str]:
)
return trimmed

@model_validator(mode="after")
def _require_header_field(self) -> "SessionStreamHeaderEdit":
if not self.model_fields_set.intersection({"name", "description"}):
raise ValueError(
"no header field to update; send name or description at the top level"
)
return self
@property
def has_header_field(self) -> bool:
"""Whether the edit names a header field. The header route refuses an edit
without one (a wrapped or empty body), unless the call only creates the session
with a requested visibility (the /w pre-create of a new chat)."""
return bool(self.model_fields_set.intersection({"name", "description"}))


class SessionStreamQuery(BaseModel):
Expand Down
37 changes: 37 additions & 0 deletions api/oss/src/core/sessions/streams/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -1306,6 +1306,14 @@ async def set_header(
request created in the meantime is checked before the edit.
"""
_validate_session_id(session_id)
if not header.has_header_field:
return await self._create_header_row(
project_id=project_id,
user_id=user_id,
session_id=session_id,
access=access,
recheck=recheck,
)
unchecked = recheck is not None and session_was_missing(
project_id=project_id, session_id=session_id
)
Expand Down Expand Up @@ -1349,6 +1357,35 @@ async def set_header(
await self._publish_changed(project_id=project_id, session_id=session_id)
return updated

async def _create_header_row(
self,
*,
project_id: UUID,
user_id: Optional[UUID],
session_id: str,
access: AccessPolicy,
recheck: Optional[SessionRecheck],
) -> Optional[SessionStream]:
"""A header call with no header field only creates the session with `access`
(the /w pre-create of a new chat) and returns the row it created. An existing
row is left unchanged and not returned: the call is checked like a send, which
does not include reading the session (one that a concurrent first touch created
is still checked first, so a hidden one answers like a hidden one)."""
try:
created = await self._create_row(
project_id=project_id,
user_id=user_id,
stream=SessionStreamCreate(session_id=session_id, access=access),
)
Comment on lines +1375 to +1379

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Security & Privacy · Quick win

🔎 Supported by static analysis

Script executed:

#!/bin/bash
# Inspect the policy substitution and the channel-session RUN decision.
ast-grep outline api/oss/src/dbs/postgres/sessions/streams/dao.py --match create
ast-grep outline api/oss/src/core/sharing/service.py --items all --match 'created_session_access|check_resource|decide'
rg -n -C 5 'has_channel_thread|created_session_access|CHANNEL_SESSION|RUN_SESSIONS' api/oss/src/core/sharing api/oss/src/dbs/postgres/sessions/streams/dao.py

Repository: Agenta-AI/agenta

Length of output: 11103


Script executed:

rg -n -F -e '_create_header_row' -e 'has_channel_thread' -e 'set_header' -e '_create_row' -e 'recheck' -- api/oss/src/core/sessions/streams/service.py || test "$?" -eq 1
rg -n -C 25 -F -e 'async def _create_header_row' -- api/oss/src/core/sessions/streams/service.py || test "$?" -eq 1
rg -n -A 14 -F -e 'def _project_members_send' -- api/oss/src/core/sharing/service.py || test "$?" -eq 1

Repository: Agenta-AI/agenta

Length of output: 5409


Recheck a channel-thread row after the header pre-create.

When _create_header_row creates a row, the DAO can substitute the channel policy if a channel thread already names the session. The method then returns that row without running recheck. The send and heartbeat create paths run the check on the created row in this case. The header path does not. A project member who passes the initial check can therefore receive a channel-session row that the channel RUN rule would refuse. Add the same check after a successful create:

🔒 Suggested fix
--- "a/api/oss/src/core/sessions/streams/service.py"
+++ "b/api/oss/src/core/sessions/streams/service.py"
@@ -1372,11 +1372,13 @@
         does not include reading the session (one that a concurrent first touch created
         is still checked first, so a hidden one answers like a hidden one)."""
         try:
             created = await self._create_row(
                 project_id=project_id,
                 user_id=user_id,
                 stream=SessionStreamCreate(session_id=session_id, access=access),
             )
+            if recheck is not None and getattr(created, "has_channel_thread", None) is True:
+                await recheck()
         except SessionStreamAlreadyExists:
             if recheck is not None and session_was_missing(
                 project_id=project_id, session_id=session_id
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
created = await self._create_row(
project_id=project_id,
user_id=user_id,
stream=SessionStreamCreate(session_id=session_id, access=access),
)
created = await self._create_row(
project_id=project_id,
user_id=user_id,
stream=SessionStreamCreate(session_id=session_id, access=access),
)
if recheck is not None and getattr(created, "has_channel_thread", None) is True:
await recheck()

except SessionStreamAlreadyExists:
if recheck is not None and session_was_missing(
project_id=project_id, session_id=session_id
):
await recheck()
return None
await self._publish_changed(project_id=project_id, session_id=session_id)
return created

async def query_streams(
self,
*,
Expand Down
109 changes: 109 additions & 0 deletions api/oss/tests/pytest/acceptance/sharing/test_header_precreate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
"""The /w pre-create of a new chat, against a running API (M3 regression).

/w creates a new chat as a project-visible session before its first run, with a header
call that carries only `visibility` (no name: the chat has no title yet). The header
route refused that call (422, "no header field to update"), so every first /w send
failed with "Message wasn't sent".
"""

import pytest

from oss.tests.pytest.acceptance.sharing.support import (
core_rows,
new_session_id,
stream_row,
)

pytestmark = [
pytest.mark.acceptance,
pytest.mark.integration,
pytest.mark.xdist_group("sharing_header_precreate"),
]


def _name(project_id, session_id):
rows = core_rows(
"SELECT name FROM session_streams WHERE project_id = $1::uuid "
"AND session_id = $2",
project_id,
session_id,
)
return rows[0]["name"]


def _put_header(caller, session_id, *, body, visibility=None):
params = {"session_id": session_id}
if visibility is not None:
params["visibility"] = visibility
return caller("PUT", "/sessions/streams/header", params=params, json=body)


def test_a_visibility_only_header_creates_a_project_session(sharing_cast):
alice = sharing_cast["alice"]
session_id = new_session_id()

created = _put_header(alice, session_id, body={}, visibility="project")
assert created.status_code == 200, created.text
stream = created.json()["stream"]
assert stream["name"] is None
row = stream_row(sharing_cast.project_id, session_id)
assert (row["visibility"], row["owner_user_id"]) == ("project", alice.user_id)


def test_a_visibility_only_header_leaves_an_existing_session_unchanged(sharing_cast):
alice = sharing_cast["alice"]
session_id = new_session_id()
named = _put_header(alice, session_id, body={"name": "kept"}, visibility="private")
assert named.status_code == 200, named.text

again = _put_header(alice, session_id, body={}, visibility="project")
assert again.status_code == 200, again.text
# It returns no session data for an existing session (it is checked like a send).
assert again.json()["stream"] is None
assert _name(sharing_cast.project_id, session_id) == "kept"
row = stream_row(sharing_cast.project_id, session_id)
assert (row["visibility"], row["owner_user_id"]) == ("private", alice.user_id)


def test_an_empty_header_without_a_visibility_is_still_refused(sharing_cast):
response = _put_header(sharing_cast["alice"], new_session_id(), body={})
assert response.status_code == 422, response.text


def test_a_member_s_pre_create_on_a_colleague_s_project_chat_changes_nothing(
sharing_cast,
):
"""Bob opens Alice's project chat before its first answer, and his first send
pre-creates it again: the call needs what a send needs, so it passes and changes
nothing (Alice stays the owner, her name stays)."""
alice, bob = sharing_cast["alice"], sharing_cast["bob"]
session_id = new_session_id()
created = _put_header(
alice, session_id, body={"name": "alice's"}, visibility="project"
)
assert created.status_code == 200, created.text

again = _put_header(bob, session_id, body={}, visibility="project")
assert again.status_code == 200, again.text
assert again.json()["stream"] is None
assert _name(sharing_cast.project_id, session_id) == "alice's"
row = stream_row(sharing_cast.project_id, session_id)
assert (row["visibility"], row["owner_user_id"]) == ("project", alice.user_id)

# A rename still needs the edit right: only Alice renames her chat.
rename = _put_header(bob, session_id, body={"name": "bob's"})
assert rename.status_code == 403, rename.text


def test_a_pre_create_on_a_hidden_chat_answers_not_found(sharing_cast):
alice, bob = sharing_cast["alice"], sharing_cast["bob"]
session_id = new_session_id()
created = _put_header(
alice, session_id, body={"name": "mine"}, visibility="private"
)
assert created.status_code == 200, created.text

hidden = _put_header(bob, session_id, body={}, visibility="project")
assert hidden.status_code == 404, hidden.text
row = stream_row(sharing_cast.project_id, session_id)
assert (row["visibility"], row["owner_user_id"]) == ("private", alice.user_id)
11 changes: 6 additions & 5 deletions api/oss/tests/pytest/unit/sessions/test_stream_header_merge.py
Original file line number Diff line number Diff line change
Expand Up @@ -445,11 +445,12 @@ def test_empty_name_stays_the_explicit_clear():
assert SessionStreamHeaderEdit(name="").name == ""


def test_empty_header_edit_is_rejected():
from pydantic import ValidationError

with pytest.raises(ValidationError, match="no header field to update"):
SessionStreamHeaderEdit()
def test_empty_header_edit_names_no_header_field():
# The header route refuses it unless the call only creates the session with a
# requested visibility (acceptance: test_header_precreate.py).
assert SessionStreamHeaderEdit().has_header_field is False
assert SessionStreamHeaderEdit(name=None).has_header_field is True
assert SessionStreamHeaderEdit(description="d").has_header_field is True


def test_explicit_none_name_still_means_no_change():
Expand Down
2 changes: 1 addition & 1 deletion docs/design/sharing-program/interfaces/m3/interfaces.md
Original file line number Diff line number Diff line change
Expand Up @@ -537,7 +537,7 @@ Callers pass the execution target, never the session's stored references (techni
| Path | Symbol | Change |
| --- | --- | --- |
| P1 turn start | `SessionStreamsService._start_turn` (`core/sessions/streams/service.py` ~1131) and `command(...)` | new required kwarg `access: AccessPolicy`. Callers: router `set_session_stream`, `core/channels/commands.py` (channel session, passes `OWNERLESS_PROJECT_POLICY`). |
| P2 rename before the first turn | `SessionStreamsService.set_header` create arm (~978) | new required kwarg `access: AccessPolicy`, used only in the create arm. The `SessionStreamAlreadyExists` arm writes no access field. |
| P2 rename before the first turn | `SessionStreamsService.set_header` create arm (~978) | new required kwarg `access: AccessPolicy`, used only in the create arm. The `SessionStreamAlreadyExists` arm writes no access field. A header call with a `visibility` and no header field only creates the session (the /w pre-create of a new chat; an existing row is returned unchanged). Without a `visibility`, a body with no header field is refused with 422, as before. |

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Data Integrity & Integration · Quick win

Correct the existing-session response description.

For a visibility-only call on an existing session, set_header returns None. The response therefore contains stream: null; it does not return the unchanged row. State that the row remains unchanged and no session data is returned.

| P3 trigger claim | `SessionStreamsDAO.claim_trigger_delivery` (`dbs/postgres/sessions/streams/dao.py` ~163) and `TriggerSessionClaimsDAOInterface.claim_trigger_delivery` | new required kwarg `access: AccessPolicy`; the `from_select` column list adds both columns. `on_conflict_do_update` stays tags-only. Caller `TriggersDispatcher._run` passes `initial_policy(principal=<trigger principal>, origin=schedule or subscription, sender_user_id=None, kind=SESSION)`. |
| P4 heartbeat | `SessionStreamsService.heartbeat(*, project_id, request, runner_verified=False, envelope)` (M2) and `_heartbeat_locked` | new required kwargs `access: AccessPolicy` (used only in the `prior_stream is None` create), `run_admission: RunAdmission`, `admission_envelope: RunEnvelope`, next to M2's `envelope` (which is `None` for Bearer and ApiKey). `_heartbeat_locked` reads `prior_stream` once, at the top, before the supersession check (its branch reuses the row). Then it authorizes: row absent → `admit_turn(session_id=None)`, then insert the row (initial flags, `turn_id`, `access`) before any liveness lock; on `SessionStreamAlreadyExists` read the winning row and authorize it as below before any lock, update or response; row present and verified continuity (`request.is_running`, `request.turn_id == prior_stream.turn_id`, and `get_turn_admission(...)` equals `admission_envelope.authority.principal`; `get_turn_admission` is one `EVAL` of `CURRENT_TURN_ADMISSION_LUA`, which returns and renews the record only while the session's `running` key equals the turn; a Redis error counts as no record) → no check; otherwise → `admit_turn(session_id=request.session_id)` for a running beat, `admit(session_id, agent_artifact_id=None)` for any other beat. After a successful check of a running beat with a `turn_id`, for the row actually used, `record_turn_admission(...)` (a write error is logged; the next beat is checked again) (Redis, NEW `record_turn_admission` and `get_turn_admission` in `dbs/redis/sessions/locks.py` next to `bind_turn`; key per project, session and turn; value the admitted `PrincipalRef`; same TTL as the binding; written only after create-or-conflict is resolved and the used row passed). NEW `forget_turn_admissions(engine, *, project_id, session_id, turn_ids)` deletes the records on the end beat, on displacement (cancel, steer, kill), on handover and on stop; a refused end beat (not running, with a `turn_id`) whose record names the same principal deletes that record too, so a replay of an ended turn is fully checked. A refusal raises before any lock, row write or response. A heartbeat with no envelope answers the canonical 404 before any row read. Router `heartbeat_session_stream` computes `access` and `admission_envelope = request_run_envelope(request)`; it reads no session row. |

Expand Down
Loading