Skip to content
Python

fix(teams): authorize attachment reads

Rakesh Utekar0939fd6624a7
diff --git a/coworker/server/app.py b/coworker/server/app.py
index f63599c1..457c0811 100644
--- a/coworker/server/app.py
+++ b/coworker/server/app.py
@@ -783,12 +783,12 @@ def create_app(manager: SessionManager) -> FastAPI:
from fastapi.responses import Response
try:
- path = manager.attachment_store.path_for(name)
+ data, mime = manager.board_attachment(session_id, name)
except TeamsBoardError as error:
return JSONResponse({"error": str(error)}, status_code=404)
return Response(
- content=path.read_bytes(),
- media_type=manager.attachment_store.mime_for(name),
+ content=data,
+ media_type=mime,
)
@app.post("/v1/sessions/{session_id}/board/comment")
@@ -998,22 +998,23 @@ def create_app(manager: SessionManager) -> FastAPI:
data, str(body.get("filename", ""))
)
filename = str(body.get("filename", ""))
- event = manager.team_store.comment(
+ event = manager.team_store.attach_ref(
str(body.get("space", "")),
actor,
int(body.get("id", 0)),
str(body.get("caption", "")) or f"attached {filename}",
- refs=[ref],
+ ref,
)
return {"ref": ref, "seq": event["seq"]}
return _board(request, run)
@app.get("/v1/board/attachment")
- def board_attachment(request: Request, name: str):
+ def board_attachment(request: Request, name: str, space: str):
def run(actor):
from fastapi.responses import Response
+ manager.team_store.require_attachment_access(space, actor, name)
path = manager.attachment_store.path_for(name)
return Response(
content=path.read_bytes(),
diff --git a/coworker/server/manager.py b/coworker/server/manager.py
index 40285768..130ede1f 100644
--- a/coworker/server/manager.py
+++ b/coworker/server/manager.py
@@ -1688,6 +1688,17 @@ class SessionManager:
def _user_actor(self) -> TeamActor:
return TeamActor(id="user", role=TeamRole.USER)
+ def board_attachment(self, session_id: str, stored: str) -> tuple[bytes, str]:
+ """Read an attachment referenced by the session's board as the user."""
+ space = self._board_space(session_id)
+ if space is None:
+ raise TeamsBoardError("attachment not found")
+ self.team_store.require_attachment_access(
+ space, self._user_actor(), stored
+ )
+ path = self.attachment_store.path_for(stored)
+ return path.read_bytes(), self.attachment_store.mime_for(stored)
+
def board_item_detail(self, session_id: str, item_id: int) -> dict[str, Any]:
"""One item in full, with its TIMELINE — creations, assignments,
transitions, and comments merged chronologically (the detail pane renders
diff --git a/coworker/teams/attachments.py b/coworker/teams/attachments.py
index 807981c8..90acb9fe 100644
--- a/coworker/teams/attachments.py
+++ b/coworker/teams/attachments.py
@@ -22,7 +22,7 @@ import re
from pathlib import Path
from typing import Optional
-from .model import BoardError
+from .model import BoardError, BoardNotFoundError
ATTACHMENT_SCHEME = "attachment://"
MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024
@@ -69,12 +69,10 @@ class AttachmentStore:
def path_for(self, stored: str) -> Path:
"""Resolve a stored name (`<sha256>.<ext>`) to its file. The strict name
check is the traversal guard — nothing else reaches the filesystem."""
- stored = stored.strip()
- if not _STORED_NAME.fullmatch(stored):
- raise BoardError(f"not an attachment name: {stored!r}")
+ stored = validate_stored_name(stored)
path = self.root / stored
if not path.exists():
- raise BoardError(f"no attachment {stored}")
+ raise BoardNotFoundError("attachment not found")
return path
def mime_for(self, stored: str) -> str:
@@ -88,6 +86,14 @@ def stored_name(ref: str) -> Optional[str]:
return ref[len(ATTACHMENT_SCHEME):].split("#", 1)[0]
+def validate_stored_name(stored: str) -> str:
+ """Return one normalized stored name, rejecting malformed input."""
+ stored = stored.strip()
+ if not _STORED_NAME.fullmatch(stored):
+ raise BoardError(f"not an attachment name: {stored!r}")
+ return stored
+
+
def _validate(data: bytes, filename: str) -> str:
if not data:
raise BoardError("attachment is empty")
diff --git a/coworker/teams/cli.py b/coworker/teams/cli.py
index 6bb5de26..98d73082 100644
--- a/coworker/teams/cli.py
+++ b/coworker/teams/cli.py
@@ -356,7 +356,7 @@ def _cmd_attachment(args) -> int:
from .attachments import stored_name
stored = stored_name(args.ref) or args.ref
- data, _mime = _dialect(args).attachment(stored)
+ data, _mime = _dialect(args).attachment(_space(args), stored)
out = Path(args.out) if args.out else Path(
args.ref.rsplit("#", 1)[-1] if "#" in args.ref else stored
)
diff --git a/coworker/teams/dialect.py b/coworker/teams/dialect.py
index b96a01d8..df66ac6e 100644
--- a/coworker/teams/dialect.py
+++ b/coworker/teams/dialect.py
@@ -87,7 +87,9 @@ class BoardDialect(Protocol):
*,
caption: str = "",
) -> dict[str, Any]: ...
- def attachment(self, stored: str) -> tuple[bytes, str]: ...
+ def attachment(self, space: str, stored: str) -> tuple[bytes, str]:
+ """Read a blob referenced by an actor-visible item in ``space``."""
+ ...
def policy(self, space: str) -> dict[str, Any]: ...
def set_policy(self, space: str, *, claims: str) -> dict[str, Any]: ...
def pending(self, space: str, *, limit: int = 200) -> list[dict[str, Any]]: ...
@@ -212,22 +214,23 @@ class LocalDialect:
*,
caption: str = "",
) -> dict[str, Any]:
- # Attach = store blob + a normal comment event carrying the ref. Comment
+ # Attach = store blob + an attributed attachment-comment event. Comment
# authority IS attach authority (workers attach on their slice only).
if self.attachments is None:
raise BoardError("no attachment store is attached to this board")
ref = self.attachments.put(data, filename)
- return self.store.comment(
+ return self.store.attach_ref(
space,
self.actor,
item_id,
caption or f"attached {filename}",
- refs=[ref],
+ ref,
)
- def attachment(self, stored: str) -> tuple[bytes, str]:
+ def attachment(self, space: str, stored: str) -> tuple[bytes, str]:
if self.attachments is None:
raise BoardError("no attachment store is attached to this board")
+ self.store.require_attachment_access(space, self.actor, stored)
path = self.attachments.path_for(stored)
return path.read_bytes(), self.attachments.mime_for(stored)
@@ -458,8 +461,10 @@ class RemoteDialect:
},
)
- def attachment(self, stored: str) -> tuple[bytes, str]:
- response = self._client.get("/v1/board/attachment", params={"name": stored})
+ def attachment(self, space: str, stored: str) -> tuple[bytes, str]:
+ response = self._client.get(
+ "/v1/board/attachment", params={"space": space, "name": stored}
+ )
if response.status_code >= 400:
self._unwrap(response) # raises with the server's message
return response.content, response.headers.get(
diff --git a/coworker/teams/store.py b/coworker/teams/store.py
index 547a1933..188a9ee0 100644
--- a/coworker/teams/store.py
+++ b/coworker/teams/store.py
@@ -31,6 +31,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional
+from .attachments import stored_name, validate_stored_name
from .model import (
EDGES,
LINK_KINDS,
@@ -51,6 +52,7 @@ GENESIS = "genesis"
# external. "lead-only" turns claims off; assignment stays with the lead/user. A lead
# on an open board can still reserve individual items by assigning them to itself.
CLAIM_POLICIES = ("open", "lead-only")
+ATTACHMENT_REFS_MIGRATION = "attachment_refs_v1"
# Event kinds. Chat lands later with the chat surface; the record shape already fits.
# Journal entries live in their own case-keyed store (teams.journal) — cases outlive
@@ -137,6 +139,13 @@ class TeamStore:
dst INTEGER NOT NULL,
UNIQUE (space, src, kind, dst)
);
+ CREATE TABLE IF NOT EXISTS team_attachment_refs (
+ space TEXT NOT NULL,
+ stored TEXT NOT NULL,
+ item_id INTEGER NOT NULL,
+ event_seq INTEGER NOT NULL,
+ PRIMARY KEY (space, stored, item_id)
+ );
CREATE TABLE IF NOT EXISTS team_meta (
space TEXT PRIMARY KEY,
head_hash TEXT NOT NULL,
@@ -150,8 +159,25 @@ class TeamStore:
space TEXT PRIMARY KEY,
claims TEXT NOT NULL DEFAULT 'open'
);
+ CREATE TABLE IF NOT EXISTS team_migrations (
+ name TEXT PRIMARY KEY
+ );
""")
- self._conn.commit()
+ migrated = self._conn.execute(
+ "SELECT 1 FROM team_migrations WHERE name = ?",
+ (ATTACHMENT_REFS_MIGRATION,),
+ ).fetchone()
+ if migrated is None:
+ try:
+ self._backfill_legacy_attachment_refs()
+ self._conn.execute(
+ "INSERT INTO team_migrations (name) VALUES (?)",
+ (ATTACHMENT_REFS_MIGRATION,),
+ )
+ self._conn.commit()
+ except Exception:
+ self._conn.rollback()
+ raise
# ------------------------------------------------------------------ events core
@@ -423,6 +449,11 @@ class TeamStore:
with self._lock:
self._conn.execute("DELETE FROM team_items WHERE space = ?", (space,))
self._conn.execute("DELETE FROM team_links WHERE space = ?", (space,))
+ self._conn.execute(
+ "DELETE FROM team_attachment_refs"
+ " WHERE space = ? AND event_seq != 0",
+ (space,),
+ )
rows = self._conn.execute(
"SELECT seq, ts, kind, actor, item_id, payload FROM team_events"
" WHERE space = ? ORDER BY seq",
@@ -580,6 +611,84 @@ class TeamStore:
item["seq"] = seq
return item
+ def require_attachment_access(
+ self, space: str, actor: Actor, stored: str
+ ) -> None:
+ """Require an actor-visible item to carry an authoritative attachment."""
+ stored = validate_stored_name(stored)
+ with self._lock:
+ rows = self._conn.execute(
+ "SELECT item.* FROM team_items AS item"
+ " JOIN team_attachment_refs AS attachment"
+ " ON attachment.space = item.space"
+ " AND attachment.item_id = item.id"
+ " WHERE attachment.space = ? AND attachment.stored = ?"
+ " ORDER BY item.id",
+ (space, stored),
+ ).fetchall()
+ worker_slice = None
+ claims_open = None
+ if actor.role == Role.WORKER:
+ worker_slice = self._worker_slice(space, actor.id)
+ claims_open = self.policy(space)["claims"] == "open"
+ for row in rows:
+ item = _row_to_item(row)
+ if not self._item_visible_to(
+ space,
+ actor,
+ item,
+ worker_slice=worker_slice,
+ claims_open=claims_open,
+ ):
+ continue
+ return
+ raise BoardNotFoundError("attachment not found")
+
+ def attach_ref(
+ self,
+ space: str,
+ actor: Actor,
+ item_id: int,
+ body: str,
+ ref: str,
+ *,
+ taint: bool = False,
+ ) -> dict[str, Any]:
+ """Attach one stored blob through an attributed comment event.
+
+ The dedicated payload field is the authoritative provenance marker;
+ arbitrary artifact refs on normal comments and transitions never grant
+ attachment-byte access.
+ """
+ if not (body or "").strip():
+ raise BoardError("comment body is required")
+ stored = stored_name(ref)
+ if stored is None:
+ raise BoardError(f"not an attachment ref: {ref!r}")
+ stored = validate_stored_name(stored)
+ with self._lock:
+ item = self._item(space, item_id)
+ if actor.role == Role.WORKER and item_id not in self._worker_slice(
+ space, actor.id
+ ):
+ raise AuthorityError(
+ f"worker {actor.id} may only comment on its assigned items"
+ " and items linked to them"
+ )
+ return self.append_event(
+ space,
+ ITEM_COMMENTED,
+ actor,
+ item_id=item_id,
+ case_id=item["case_id"] or None,
+ payload={
+ "body": body,
+ "refs": [ref],
+ "attachments": [stored],
+ },
+ taint=taint,
+ )
+
def transition(
self,
space: str,
@@ -812,9 +921,9 @@ class TeamStore:
item_id: Optional[int],
payload: dict[str, Any],
) -> None:
- """Fold one event into the projections. The ONLY writer of team_items and
- team_links — shared by live appends and rebuild(), so replay always
- reproduces the materialized state."""
+ """Fold one event into the projections. The ONLY writer of item, link,
+ and attachment-reference projections — shared by live appends and
+ rebuild(), so replay always reproduces the materialized state."""
if kind == ITEM_CREATED:
self._conn.execute(
"""
@@ -851,6 +960,9 @@ class TeamStore:
self._merge_refs(space, item_id, payload.get("refs"))
elif kind == ITEM_COMMENTED:
self._merge_refs(space, item_id, payload.get("refs"))
+ self._merge_attachment_refs(
+ space, item_id, payload.get("attachments"), seq
+ )
elif kind == ITEM_ASSIGNED:
self._conn.execute(
"UPDATE team_items SET assignee = ?, updated_seq = ?"
@@ -865,7 +977,8 @@ class TeamStore:
)
# Comment bodies and journal entries have no materialized state: their
# projections read straight off the (indexed) log. Only the artifact
- # refs a comment carries fold onto the item.
+ # refs a comment carries fold onto the item; authoritative attachment
+ # markers also fold into their indexed projection.
def _merge_refs(
self, space: str, item_id: Optional[int], refs: Optional[list]
@@ -885,6 +998,51 @@ class TeamStore:
(json.dumps(merged), space, item_id),
)
+ def _merge_attachment_refs(
+ self,
+ space: str,
+ item_id: Optional[int],
+ attachments: Optional[list],
+ seq: int,
+ ) -> None:
+ if not attachments or item_id is None:
+ return
+ for stored in attachments:
+ self._conn.execute(
+ "INSERT OR IGNORE INTO team_attachment_refs"
+ " (space, stored, item_id, event_seq) VALUES (?, ?, ?, ?)",
+ (space, validate_stored_name(str(stored)), item_id, seq),
+ )
+
+ def _backfill_legacy_attachment_refs(self) -> None:
+ """Snapshot pre-provenance refs once when the projection is introduced.
+
+ Old attach events were indistinguishable from generic comment refs. Rows
+ grandfathered at upgrade use event_seq=0 so rebuild preserves that fixed
+ compatibility boundary; refs added after the migration are never inferred.
+ """
+ rows = self._conn.execute(
+ "SELECT space, id, refs FROM team_items"
+ ).fetchall()
+ for row in rows:
+ try:
+ refs = json.loads(row["refs"] or "[]")
+ except (TypeError, json.JSONDecodeError):
+ continue
+ for ref in refs:
+ stored = stored_name(str(ref))
+ if stored is None:
+ continue
+ try:
+ stored = validate_stored_name(stored)
+ except BoardError:
+ continue
+ self._conn.execute(
+ "INSERT OR IGNORE INTO team_attachment_refs"
+ " (space, stored, item_id, event_seq) VALUES (?, ?, ?, 0)",
+ (row["space"], stored, row["id"]),
+ )
+
def _check_transition_authority(
self, actor: Actor, item: dict[str, Any], current: ItemState, target: ItemState
) -> None:
@@ -1047,7 +1205,12 @@ class TeamStore:
(new, prev, record["hash"], row["seq"]),
)
prev = record["hash"]
- for table in ("team_items", "team_links", "team_settings"):
+ for table in (
+ "team_items",
+ "team_links",
+ "team_attachment_refs",
+ "team_settings",
+ ):
self._conn.execute(
f"UPDATE {table} SET space = ? WHERE space = ?", (new, old)
)
diff --git a/coworker/teams/tools.py b/coworker/teams/tools.py
index c704e270..e004a037 100644
--- a/coworker/teams/tools.py
+++ b/coworker/teams/tools.py
@@ -165,12 +165,12 @@ def board_tools(
except (BoardError, ValueError) as error:
return {"error": str(error)}
return _call(
- store.comment,
+ store.attach_ref,
space,
actor,
item,
caption or f"attached {source.name}",
- refs=[ref],
+ ref,
taint=taint(),
)
diff --git a/tests/test_team_open_surface.py b/tests/test_team_open_surface.py
index 2ed8994d..6cde40d5 100644
--- a/tests/test_team_open_surface.py
+++ b/tests/test_team_open_surface.py
@@ -2,6 +2,7 @@
seam (local and remote), token-bound identity on `/v1/board`, and the MCP/CLI
front doors."""
+import base64
import json
import pytest
@@ -551,8 +552,12 @@ def test_attach_over_the_wire_and_fetch(api):
# and the lead can fetch the bytes back
from coworker.teams.attachments import stored_name
- data, mime = lead.attachment(stored_name(result["ref"]))
+ stored = stored_name(result["ref"])
+ data, mime = lead.attachment("proj", stored)
assert data == PNG and mime == "image/png"
+ assert nia.attachment("proj", stored) == (PNG, "image/png")
+ with pytest.raises(BoardError, match="attachment not found"):
+ lead.attachment("another-space", stored)
# a worker cannot attach to an item outside its slice
other = lead.create_item("proj", title="Not nia's", criteria="c")
@@ -561,6 +566,300 @@ def test_attach_over_the_wire_and_fetch(api):
nia.attach("proj", other["id"], PNG, "sneaky.png")
+def test_board_attachment_read_hides_foreign_worker_reference(api):
+ client, manager, app = api
+ from fastapi.testclient import TestClient
+ from coworker.teams.attachments import stored_name
+
+ lead_token = _tokens(manager).mint("lead-1", "lead")
+ nia_token = _tokens(manager).mint("nia", "worker")
+ lead = {"Authorization": f"Bearer {lead_token}"}
+ nia = {"Authorization": f"Bearer {nia_token}"}
+
+ item_response = client.post(
+ "/v1/board/items",
+ headers=lead,
+ json={"space": "proj", "title": "Webb evidence", "criteria": "c"},
+ )
+ assert item_response.status_code == 200
+ item = item_response.json()
+ assert client.post(
+ "/v1/board/items/assign",
+ headers=lead,
+ json={"space": "proj", "id": item["id"], "assignee": "webb"},
+ ).status_code == 200
+ attached = client.post(
+ "/v1/board/items/attach",
+ headers=lead,
+ json={
+ "space": "proj",
+ "id": item["id"],
+ "filename": "private.png",
+ "data_b64": base64.b64encode(PNG).decode("ascii"),
+ },
+ )
+ assert attached.status_code == 200
+
+ stored = stored_name(attached.json()["ref"])
+ denied = client.get(
+ "/v1/board/attachment",
+ headers=nia,
+ params={"space": "proj", "name": stored},
+ )
+
+ assert denied.status_code == 404
+ assert denied.json() == {"error": "attachment not found"}
+
+ remote = RemoteDialect(
+ "http://board.test",
+ nia_token,
+ client=TestClient(app, base_url="http://board.test"),
+ )
+ with pytest.raises(BoardError, match="attachment not found"):
+ remote.attachment("proj", stored)
+ remote.close()
+
+
+def test_board_attachment_read_requires_token(api):
+ client, _, _ = api
+
+ response = client.get(
+ "/v1/board/attachment",
+ params={"space": "proj", "name": f"{'0' * 64}.png"},
+ )
+
+ assert response.status_code == 401
+ assert "board token required" in response.json()["error"]
+
+
+def test_board_attachment_read_rejects_malformed_name(api):
+ client, manager, _ = api
+ lead = {
+ "Authorization": f"Bearer {_tokens(manager).mint('lead-1', 'lead')}"
+ }
+
+ response = client.get(
+ "/v1/board/attachment",
+ headers=lead,
+ params={"space": "proj", "name": "../../private.png"},
+ )
+
+ assert response.status_code == 400
+ assert "not an attachment name" in response.json()["error"]
+
+
+def test_board_attachment_read_hides_unreferenced_blob(api):
+ client, manager, _ = api
+ from coworker.teams.attachments import stored_name
+
+ lead = {
+ "Authorization": f"Bearer {_tokens(manager).mint('lead-1', 'lead')}"
+ }
+ ref = manager.attachment_store.put(PNG, "orphan.png")
+
+ response = client.get(
+ "/v1/board/attachment",
+ headers=lead,
+ params={"space": "proj", "name": stored_name(ref)},
+ )
+
+ assert response.status_code == 404
+ assert response.json() == {"error": "attachment not found"}
+
+
+def test_board_attachment_read_hides_missing_referenced_blob(api):
+ client, manager, _ = api
+ from coworker.teams.attachments import stored_name
+
+ lead = {
+ "Authorization": f"Bearer {_tokens(manager).mint('lead-1', 'lead')}"
+ }
+ item = client.post(
+ "/v1/board/items",
+ headers=lead,
+ json={"space": "proj", "title": "Evidence", "criteria": "c"},
+ ).json()
+ attached = client.post(
+ "/v1/board/items/attach",
+ headers=lead,
+ json={
+ "space": "proj",
+ "id": item["id"],
+ "filename": "missing.png",
+ "data_b64": base64.b64encode(PNG).decode("ascii"),
+ },
+ ).json()
+ stored = stored_name(attached["ref"])
+ manager.attachment_store.path_for(stored).unlink()
+
+ response = client.get(
+ "/v1/board/attachment",
+ headers=lead,
+ params={"space": "proj", "name": stored},
+ )
+
+ assert response.status_code == 404
+ assert response.json() == {"error": "attachment not found"}
+
+
+def test_local_attachment_read_tracks_worker_visibility(tmp_path):
+ from coworker.teams.attachments import stored_name
+
+ lead = local_dialect(tmp_path, actor="lead-1", role="lead")
+ worker = LocalDialect(
+ lead.store, lead.journal, NIA, attachments=lead.attachments
+ )
+ claimable = lead.create_item("proj", title="Available", criteria="c")
+ result = lead.attach("proj", claimable["id"], PNG, "available.png")
+ stored = stored_name(result["payload"]["refs"][0])
+
+ assert worker.attachment("proj", stored) == (PNG, "image/png")
+
+ lead.set_policy("proj", claims="lead-only")
+ with pytest.raises(BoardError, match="attachment not found"):
+ worker.attachment("proj", stored)
+
+ assigned = lead.create_item("proj", title="Assigned", criteria="c")
+ lead.assign("proj", assigned["id"], "nia")
+ assigned_ref = lead.attach(
+ "proj", assigned["id"], PNG, "assigned.png"
+ )["payload"]["refs"][0]
+ assert worker.attachment("proj", stored_name(assigned_ref)) == (
+ PNG,
+ "image/png",
+ )
+
+ with pytest.raises(BoardError, match="attachment not found"):
+ lead.attachment("another-space", stored)
+
+
+def test_local_attachment_read_allows_a_visible_deduplicated_reference(tmp_path):
+ from coworker.teams.attachments import stored_name
+
+ lead = local_dialect(tmp_path, actor="lead-1", role="lead")
+ worker = LocalDialect(
+ lead.store, lead.journal, NIA, attachments=lead.attachments
+ )
+ foreign = lead.create_item("proj", title="Webb evidence", criteria="c")
+ lead.assign("proj", foreign["id"], "webb")
+ foreign_ref = lead.attach("proj", foreign["id"], PNG, "foreign.png")["payload"][
+ "refs"
+ ][0]
+ with pytest.raises(BoardError, match="attachment not found"):
+ worker.attachment("proj", stored_name(foreign_ref))
+
+ mine = worker.create_item("proj", title="Nia evidence", criteria="c")
+ own_ref = worker.attach("proj", mine["id"], PNG, "mine.png")["payload"]["refs"][
+ 0
+ ]
+
+ assert stored_name(own_ref) == stored_name(foreign_ref)
+ assert worker.attachment("proj", stored_name(own_ref)) == (PNG, "image/png")
+
+ lead.store.rebuild("proj")
+ assert worker.attachment("proj", stored_name(own_ref)) == (PNG, "image/png")
+
+ assert lead.store.rekey_space("proj", "moved") is True
+ assert worker.attachment("moved", stored_name(own_ref)) == (PNG, "image/png")
+
+
+def test_local_attachment_read_rejects_forged_comment_and_transition_refs(tmp_path):
+ from coworker.teams.attachments import stored_name
+
+ lead = local_dialect(tmp_path, actor="lead-1", role="lead")
+ worker = LocalDialect(
+ lead.store, lead.journal, NIA, attachments=lead.attachments
+ )
+ foreign = lead.create_item("proj", title="Webb evidence", criteria="c")
+ lead.assign("proj", foreign["id"], "webb")
+ comment_ref = lead.attach(
+ "proj", foreign["id"], PNG, "foreign-comment.png"
+ )["payload"]["refs"][0]
+ transition_ref = lead.attach(
+ "proj", foreign["id"], PNG + b"transition", "foreign-transition.png"
+ )["payload"]["refs"][0]
+
+ mine = lead.create_item("proj", title="Nia task", criteria="c")
+ lead.assign("proj", mine["id"], "nia")
+ worker.comment("proj", mine["id"], "found this", refs=[comment_ref])
+ worker.transition(
+ "proj",
+ mine["id"],
+ "in_progress",
+ refs=[transition_ref],
+ )
+
+ with pytest.raises(BoardError, match="attachment not found"):
+ worker.attachment("proj", stored_name(comment_ref))
+ with pytest.raises(BoardError, match="attachment not found"):
+ worker.attachment("proj", stored_name(transition_ref))
+
+
+def test_legacy_attachment_refs_are_grandfathered_across_rebuild(tmp_path):
+ import sqlite3
+
+ from coworker.teams.attachments import AttachmentStore, stored_name
+
+ db_path = tmp_path / "teams.db"
+ attachments = AttachmentStore(tmp_path / "attachments")
+ store = TeamStore(db_path)
+ item = store.create_item("proj", LEAD, title="Legacy", criteria="c")
+ ref = attachments.put(PNG, "legacy.png")
+ # Before provenance markers, attach was an ordinary comment carrying a ref.
+ store.comment("proj", LEAD, item["id"], "attached legacy.png", refs=[ref])
+ store.close()
+ with sqlite3.connect(db_path) as connection:
+ # Simulate an old DB—or an interrupted upgrade whose projection table
+ # exists but whose atomic migration marker was never committed.
+ connection.execute(
+ "DELETE FROM team_migrations WHERE name = 'attachment_refs_v1'"
+ )
+
+ reopened = TeamStore(db_path)
+ lead = LocalDialect(reopened, None, LEAD, attachments=attachments)
+ stored = stored_name(ref)
+
+ assert lead.attachment("proj", stored) == (PNG, "image/png")
+ later = reopened.create_item("proj", LEAD, title="Later", criteria="c")
+ forged_ref = attachments.put(PNG + b"later", "later.png")
+ reopened.comment(
+ "proj", LEAD, later["id"], "ordinary ref", refs=[forged_ref]
+ )
+ reopened.close()
+
+ reopened = TeamStore(db_path)
+ lead = LocalDialect(reopened, None, LEAD, attachments=attachments)
+ with pytest.raises(BoardError, match="attachment not found"):
+ lead.attachment("proj", stored_name(forged_ref))
+ reopened.rebuild("proj")
+ assert lead.attachment("proj", stored) == (PNG, "image/png")
+ assert reopened.rekey_space("proj", "moved") is True
+ assert lead.attachment("moved", stored) == (PNG, "image/png")
+ reopened.close()
+
+
+def test_local_attachment_read_allows_a_directly_linked_item(tmp_path):
+ from coworker.teams.attachments import stored_name
+
+ lead = local_dialect(tmp_path, actor="lead-1", role="lead")
+ worker = LocalDialect(
+ lead.store, lead.journal, NIA, attachments=lead.attachments
+ )
+ mine = lead.create_item("proj", title="Nia task", criteria="c")
+ lead.assign("proj", mine["id"], "nia")
+ dependency = lead.create_item("proj", title="Dependency", criteria="c")
+ lead.assign("proj", dependency["id"], "webb")
+ ref = lead.attach("proj", dependency["id"], PNG, "dependency.png")["payload"][
+ "refs"
+ ][0]
+
+ with pytest.raises(BoardError, match="attachment not found"):
+ worker.attachment("proj", stored_name(ref))
+
+ lead.link("proj", dependency["id"], "blocks", mine["id"])
+ assert worker.attachment("proj", stored_name(ref)) == (PNG, "image/png")
+
+
def test_attach_rejects_bad_payloads_over_the_wire(api):
client, manager, app = api
lead_token = _tokens(manager).mint("lead-1", "lead")
@@ -733,6 +1032,75 @@ def test_cli_worker_cannot_show_a_foreign_item(tmp_path, capsys):
assert "Private Webb task" not in output.err
+def test_cli_worker_cannot_download_a_foreign_attachment(tmp_path, capsys):
+ from coworker.teams.attachments import stored_name
+ from coworker.teams.cli import main
+
+ lead = local_dialect(tmp_path, actor="lead-1", role="lead")
+ foreign = lead.create_item("proj", title="Private Webb task", criteria="c")
+ lead.assign("proj", foreign["id"], "webb")
+ ref = lead.attach("proj", foreign["id"], PNG, "private.png")["payload"]["refs"][
+ 0
+ ]
+ output = tmp_path / "stolen.png"
+
+ result = main(
+ [
+ "board",
+ "attachment",
+ stored_name(ref),
+ "--out",
+ str(output),
+ "--db",
+ str(tmp_path),
+ "--space",
+ "proj",
+ "--actor",
+ "nia",
+ "--role",
+ "worker",
+ ]
+ )
+
+ assert result == 1
+ assert not output.exists()
+ assert "attachment not found" in capsys.readouterr().err
+
+
+def test_cli_authorized_attachment_download(tmp_path, capsys):
+ from coworker.teams.attachments import stored_name
+ from coworker.teams.cli import main
+
+ lead = local_dialect(tmp_path, actor="lead-1", role="lead")
+ item = lead.create_item("proj", title="Evidence", criteria="c")
+ ref = lead.attach("proj", item["id"], PNG, "evidence.png")["payload"]["refs"][
+ 0
+ ]
+ output = tmp_path / "downloaded.png"
+
+ result = main(
+ [
+ "board",
+ "attachment",
+ stored_name(ref),
+ "--out",
+ str(output),
+ "--db",
+ str(tmp_path),
+ "--space",
+ "proj",
+ "--actor",
+ "lead-1",
+ "--role",
+ "lead",
+ ]
+ )
+
+ assert result == 0
+ assert output.read_bytes() == PNG
+ assert str(output) in capsys.readouterr().out
+
+
def test_cli_token_mint_and_list(tmp_path, capsys):
from coworker.teams.cli import main
diff --git a/tests/test_team_wake.py b/tests/test_team_wake.py
index a3a0bb9d..5d5e6fd1 100644
--- a/tests/test_team_wake.py
+++ b/tests/test_team_wake.py
@@ -413,6 +413,91 @@ def test_item_detail_timeline_and_blocker_fact(manager):
assert blocked["blocker"] == "need the staging tfvars"
+def test_session_attachment_read_is_scoped_to_its_board(manager):
+ from coworker.sessions import SessionRecord
+ from coworker.teams import BoardError
+ from coworker.teams.attachments import stored_name
+
+ space = str(manager.default_workspace)
+ manager.session_store.save(
+ SessionRecord(
+ session_id="sid",
+ workspace=space,
+ model="m",
+ mode="interactive",
+ messages=[],
+ agent="cowork",
+ )
+ )
+ other = manager.team_store.create_item(
+ "other-space", LEAD, title="Other board", criteria="c"
+ )
+ ref = manager.attachment_store.put(
+ b"\x89PNG\r\n\x1a\nprivate", "private.png"
+ )
+ manager.team_store.attach_ref(
+ "other-space", LEAD, other["id"], "private", ref
+ )
+
+ with pytest.raises(BoardError, match="attachment not found"):
+ manager.board_attachment("sid", stored_name(ref))
+
+
+def test_session_attachment_route_uses_the_session_board(manager, monkeypatch):
+ from fastapi.testclient import TestClient
+
+ from coworker.server.app import create_app
+ from coworker.sessions import SessionRecord
+ from coworker.teams.attachments import stored_name
+
+ monkeypatch.delenv("COWORKER_API_TOKEN", raising=False)
+ space = str(manager.default_workspace)
+ manager.session_store.save(
+ SessionRecord(
+ session_id="sid",
+ workspace=space,
+ model="m",
+ mode="interactive",
+ messages=[],
+ agent="cowork",
+ )
+ )
+ other = manager.team_store.create_item(
+ "other-space", LEAD, title="Other board", criteria="c"
+ )
+ ref = manager.attachment_store.put(
+ b"\x89PNG\r\n\x1a\nprivate", "private.png"
+ )
+ manager.team_store.attach_ref(
+ "other-space", LEAD, other["id"], "private", ref
+ )
+ client = TestClient(create_app(manager))
+
+ response = client.get(
+ "/v1/sessions/sid/board/attachment",
+ params={"name": stored_name(ref)},
+ )
+ assert response.status_code == 404
+ assert response.json() == {"error": "attachment not found"}
+
+ item = manager.team_store.create_item(
+ space, LEAD, title="This board", criteria="c"
+ )
+ visible = manager.attachment_store.put(
+ b"\x89PNG\r\n\x1a\nvisible", "visible.png"
+ )
+ manager.team_store.attach_ref(space, LEAD, item["id"], "visible", visible)
+ allowed = client.get(
+ "/v1/sessions/sid/board/attachment",
+ params={"name": stored_name(visible)},
+ )
+ client.close()
+
+ assert allowed.status_code == 200
+ assert allowed.content == b"\x89PNG\r\n\x1a\nvisible"
+ assert allowed.headers["content-type"] == "image/png"
+
+
def test_feed_interest_follows_the_assignment_relation(store):
"""Owner ruling 2026-08-17: no per-event addressing — a worker is subscribed
to everything on its slice. Send-backs, comment ANSWERS (the silently broken