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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,6 @@ artemis-admin-audit.jsonl

# Demo board scratch (scripts/preview_demo.py)
.preview-demo/

# Generated by tests that pass a MagicMock as a db path
/MagicMock/
5 changes: 4 additions & 1 deletion apps/admin_console/core/access_control.py
Original file line number Diff line number Diff line change
Expand Up @@ -845,7 +845,10 @@ def route_tier(path: str, methods: set[str], is_websocket: bool = False) -> str
return "qa_or_service"
if methods == {"POST"} and path in _PUBLIC_MUTATING_PATHS:
return "public"
if path == "/api/runs/{session_id}/annotations/{annotation_id}" and methods in (
if path in (
"/api/runs/{session_id}/annotations/{annotation_id}",
"/api/runs/{session_id}/comments/{comment_id}",
) and methods in (
{"PATCH"},
{"DELETE"},
):
Expand Down
2 changes: 2 additions & 0 deletions apps/admin_console/core/preview_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@
"GET /api/runs/{session_id}/annotations/{annotation_id}/evidence",
"GET /api/runs/{session_id}/comments",
"POST /api/runs/{session_id}/comments",
"PATCH /api/runs/{session_id}/comments/{comment_id}",
"DELETE /api/runs/{session_id}/comments/{comment_id}",
"GET /api/system/retention",
"GET /api/system/storage",
"GET /api/system/whoami",
Expand Down
26 changes: 26 additions & 0 deletions apps/admin_console/database/repositories/annotation_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,32 @@ def list_comments(conn: sqlite3.Connection, session_id: str) -> list[Comment]:
return [Comment(*row) for row in rows]


def get_comment(conn: sqlite3.Connection, comment_id: str) -> Comment | None:
row = conn.execute(
"SELECT comment_id, session_id, author_principal_id, body, created_at, edited_at "
"FROM run_comments WHERE comment_id = ?",
(comment_id,),
).fetchone()
return Comment(*row) if row else None


def edit_comment(conn: sqlite3.Connection, comment_id: str, body: str) -> Comment:
"""Replace the body with the same checks as ``add_comment`` and set ``edited_at``."""
if not 1 <= len(body) <= config.COMMENT_BODY_MAX_CHARS or "\x00" in body:
raise invalid_comment_body()
with conn:
conn.execute(
"UPDATE run_comments SET body = ?, edited_at = ? WHERE comment_id = ?",
(body, time.time(), comment_id),
)
return get_comment(conn, comment_id)


def delete_comment(conn: sqlite3.Connection, comment_id: str) -> None:
with conn:
conn.execute("DELETE FROM run_comments WHERE comment_id = ?", (comment_id,))


def anchor_invalid(detail: str) -> AdminAPIError:
return AdminAPIError(
422,
Expand Down
53 changes: 51 additions & 2 deletions apps/admin_console/routers/run_annotations.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ async def checked(request: Request):
raise notes.invalid_comment_body() from exc
raise
except AdminAPIError as exc:
if request.method == "POST" and exc.code == "not_signed_in":
if request.method != "GET" and exc.code == "not_signed_in":
raise _note_actor_required() from exc
raise

Expand Down Expand Up @@ -296,7 +296,56 @@ def create_comment(
return _present_comment(conn, comment)


def _require_author(annotation: notes.Annotation, principal_id: str) -> None:
def _comment(conn, session_id: str, comment_id: str) -> notes.Comment:
comment = notes.get_comment(conn, comment_id)
if comment is None or comment.session_id != session_id:
raise run_not_visible()
return comment


@comment_router.patch(
"/api/runs/{session_id}/comments/{comment_id}", dependencies=[Depends(evidence_scope)]
)
def edit_comment(
session_id: str,
comment_id: str,
body: CommentCreate,
identity: AccessIdentity = Depends(public_tier),
):
with _database(session_id, identity, include_comments=True) as conn:
# Run visibility and comment existence answer before the actor check; the principal
# lookup writes on its own connection, so it must run before BEGIN IMMEDIATE.
_comment(conn, session_id, comment_id)
principal_id = note_principal(identity)
with conn:
conn.execute("BEGIN IMMEDIATE")
_require_author(_comment(conn, session_id, comment_id), principal_id)
require_note_write(principal_id)
return _present_comment(conn, notes.edit_comment(conn, comment_id, body.body))


@comment_router.delete(
"/api/runs/{session_id}/comments/{comment_id}",
status_code=204,
dependencies=[Depends(evidence_scope)],
)
def delete_comment(
session_id: str, comment_id: str, identity: AccessIdentity = Depends(public_tier)
):
with _database(session_id, identity, include_comments=True) as conn:
_comment(conn, session_id, comment_id)
principal_id = note_principal(identity)
with conn:
conn.execute("BEGIN IMMEDIATE")
comment = _comment(conn, session_id, comment_id)
if not scope_for(identity).admin:
_require_author(comment, principal_id)
require_note_write(principal_id)
notes.delete_comment(conn, comment_id)
return Response(status_code=204)


def _require_author(annotation: notes.Annotation | notes.Comment, principal_id: str) -> None:
if annotation.author_principal_id != principal_id:
raise AdminAPIError(
403,
Expand Down
20 changes: 16 additions & 4 deletions docs/board-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ Identity headers are trusted only behind the authenticating proxy; see
| `PATCH, DELETE /api/runs/{session_id}/annotations/{annotation_id}` | Edit, resolve or delete an annotation. |
| `GET /api/runs/{session_id}/annotations/{annotation_id}/evidence` | Resolve an annotation anchor. |
| `GET, POST /api/runs/{session_id}/comments` | List or add comments. |
| `PATCH, DELETE /api/runs/{session_id}/comments/{comment_id}` | Not yet implemented (CHE-7704). |
| `PATCH, DELETE /api/runs/{session_id}/comments/{comment_id}` | Edit or delete a comment. |
| `GET /api/stream` | Existing SSE stream; carries the board events below. |

Every route is classified in the access-control and preview route registries
Expand Down Expand Up @@ -474,11 +474,23 @@ write budget with `POST /api/runs/{session_id}/comments` (default 30 writes in
`author` is the principal's email, or `null` when no email is recorded.
Timestamps use ISO 8601, and `edited_at` is `null` on creation.

Both routes are public-tier and preview `REAL`, subject to run visibility. An
- `PATCH /api/runs/{session_id}/comments/{comment_id}` accepts only
`{"body": "..."}` and returns 200 with the comment, body unchanged as plain
text and `edited_at` set. Only the author can edit, admins included. A
non-author gets `comment_not_permitted` 403.
- `DELETE /api/runs/{session_id}/comments/{comment_id}` returns 204 with no body.
The author or an admin can delete. Any other caller gets
`comment_not_permitted` 403.
- A comment id that does not exist, or that belongs to another run, returns
`run_not_visible` 404, the same as an unreadable run. Both routes count
against the shared annotation and comment write budget; a refused call
(403, 404) spends none.

All four routes are public-tier and preview `REAL`, subject to run visibility. An
unreadable, unknown, deleted, or prefix-only run returns `run_not_visible` 404.
Anyone who can read the run and has a verified writing identity can add a
comment; these routes do not return `comment_not_permitted`. In authenticated
modes a POST without a verified issuer and subject returns `actor_required` 401.
comment; create does not return `comment_not_permitted`. In authenticated
modes a write without a verified issuer and subject returns `actor_required` 401.
Invalid JSON or a rejected body returns `request_invalid` 422 with the configured
character cap in the hint. Exceeding the shared annotation and comment write
budget returns `rate_limited` 429 with `Retry-After`.
Expand Down
5 changes: 5 additions & 0 deletions tests/unit/admin_console/test_preview_routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,11 @@ def test_run_comment_routes_use_real_preview_handlers(method):
assert f"{method} /api/runs/{{session_id}}/comments" in pr.REAL


@pytest.mark.parametrize("method", ["PATCH", "DELETE"])
def test_run_comment_item_routes_use_real_preview_handlers(method):
assert f"{method} /api/runs/{{session_id}}/comments/{{comment_id}}" in pr.REAL


@pytest.mark.parametrize(
"key",
[
Expand Down
6 changes: 6 additions & 0 deletions tests/unit/admin_console/test_route_tiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ def _assert_routes_have_declared_tiers(routes):
"/api/runs/{session_id}/annotations",
"/api/runs/{session_id}/annotations/{annotation_id}",
"/api/runs/{session_id}/comments",
"/api/runs/{session_id}/comments/{comment_id}",
}
if path in public_note_controls:
from apps.admin_console.core.ownership import evidence_scope
Expand Down Expand Up @@ -134,6 +135,11 @@ def test_run_comment_routes_are_public_tier(method):
assert route_tier("/api/runs/{session_id}/comments", {method}) == "public"


@pytest.mark.parametrize("method", ["PATCH", "DELETE"])
def test_run_comment_item_routes_are_public_tier(method):
assert route_tier("/api/runs/{session_id}/comments/{comment_id}", {method}) == "public"


@pytest.mark.parametrize(
("method", "path"),
[
Expand Down
55 changes: 55 additions & 0 deletions tests/unit/admin_console/test_run_comments.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,58 @@ def test_note_write_budget_uses_configured_limit(note_limiter, monkeypatch):
with pytest.raises(AdminAPIError) as caught:
run_annotations.require_note_write(AUTHOR)
assert caught.value.code == "rate_limited"


def test_get_comment_returns_the_comment_or_none(thread):
conn, run = thread
comment = notes.add_comment(conn, run, "find me", AUTHOR)

assert notes.get_comment(conn, comment.comment_id) == comment
assert notes.get_comment(conn, "cmt_missing") is None


def test_edit_comment_replaces_body_and_sets_edited_at(thread, monkeypatch):
conn, run = thread
comment = notes.add_comment(conn, run, "before", AUTHOR)
monkeypatch.setattr(notes, "time", SimpleNamespace(time=lambda: 500.0))

edited = notes.edit_comment(conn, comment.comment_id, " <b>after</b>\n")

assert edited.body == " <b>after</b>\n" and edited.edited_at == 500.0
assert edited.created_at == comment.created_at
assert notes.get_comment(conn, comment.comment_id) == edited
assert notes.list_comments(conn, run) == [edited]


@pytest.mark.parametrize(
"body", ["", "x" * 4001, "before\x00after"], ids=["empty", "over-cap", "nul"]
)
def test_edit_comment_rejects_invalid_bodies_without_changing_it(thread, body):
conn, run = thread
comment = notes.add_comment(conn, run, "before", AUTHOR)
with pytest.raises(AdminAPIError) as caught:
notes.edit_comment(conn, comment.comment_id, body)

assert (caught.value.status_code, caught.value.code) == (422, "request_invalid")
assert notes.get_comment(conn, comment.comment_id) == comment


def test_edit_comment_uses_configured_cap(thread, monkeypatch):
conn, run = thread
comment = notes.add_comment(conn, run, "before", AUTHOR)
monkeypatch.setattr(config, "COMMENT_BODY_MAX_CHARS", 4)

assert notes.edit_comment(conn, comment.comment_id, "1234").body == "1234"
with pytest.raises(AdminAPIError):
notes.edit_comment(conn, comment.comment_id, "12345")


def test_delete_comment_removes_only_that_comment(thread):
conn, run = thread
gone = notes.add_comment(conn, run, "gone", AUTHOR)
kept = notes.add_comment(conn, run, "kept", AUTHOR)

notes.delete_comment(conn, gone.comment_id)

assert notes.list_comments(conn, run) == [kept]
assert notes.get_comment(conn, gone.comment_id) is None
Loading
Loading