fix(project): 보안·권한·데이터 버그 수정 및 성능 개선

보안
- 첨부 /inline: 업로드한 쪽이 정한 content-type 을 그대로 띄워 HTML/SVG
  첨부로 저장형 XSS 가능 → 안전한 이미지 형식만 인라인, 나머지는 다운로드.
  nosniff + CSP sandbox 헤더 추가.
- 설명란 sanitizer: URL 금지 목록이 "jav	ascript:" 로 우회됨 →
  허용 목록(http/https/mailto/tel/상대경로, img 는 data: 이미지)으로 변경.

권한
- 업무 생성 시 parent_task_id 로 권한 없는 프로젝트에 하위 업무 생성 가능 → 거부.
- 세션 수정/순서/삭제 API 가 세션이 URL 프로젝트 소속인지 안 봄 → 404.
- 업무 생성·수정·연결 시 세션이 해당 프로젝트 것인지 검증.
- 멤버/세션/업무/활동 조회 API 와 프로젝트 화면을 멤버·owner·admin 만.
  users/tasks 전체 조회는 볼 수 있는 프로젝트 업무만.

데이터
- 연결(멀티호밍) 업무를 연결된 프로젝트에서 열어 저장하면 세션 선택이 비어
  stage_id=null 이 전송돼 원래 세션·완료 상태가 지워짐 → home_stage_id 사용,
  빈 세션은 보내지 않음.
- mergeTask 가 같은 id 의 첫 행만 고쳐 연결 업무 카드가 중복/사라짐 → 모든
  맥락 행을 고치되 맥락별 세션 필드는 보존. 새 업무가 다음 동기화까지 안
  보이던 문제도 수정.
- 삭제·세션 이름변경·첨부 추가가 실시간 반영 안 됨 → 트리거 카운터
  (마이그레이션 007, 미적용 시 MAX 폴백). 화면 열자마자 기준값을 잡아
  첫 8초 사이 변경 누락도 해결. 동기화 시 이 프로젝트 행을 통째로 교체.
- 사이드바 "내 업무" 개수가 화면마다 다르던 것 → count_my_open 하나로 통일.
- 업무/프로젝트/댓글 삭제 시 디스크 첨부 파일 정리.

성능
- 라우터 핸들러 async def → def (동기 psycopg 가 이벤트 루프를 막음).
- 프로젝트 화면 N+1 → 업무·세션 각각 쿼리 1회.
- live-version 풀스캔 → PK 한 줄 조회. 탭 숨김 시 폴링 중지.
- 동기화 API 3개 → /snapshot 1개, 배지 숫자는 /my-tasks/open-count.
- 순서 변경 UPDATE N번 → unnest 1번. 첨부는 한도+1 바이트만 읽음.

기타
- 마이그레이션 003 번호 중복 → project_db_003b_task_times.sql.
- CLAUDE.md 의 옛 권한 설명 정정, PROJECT_MODULE.md 갱신. 캐시 버전 20260923b.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-09-23 12:59:37 +09:00
parent b0062504b6
commit ca9beab729
11 changed files with 631 additions and 207 deletions
+209 -69
View File
@@ -13,9 +13,12 @@
from __future__ import annotations
import logging
from datetime import date, datetime, time
import time
from datetime import date, datetime
from datetime import time as dtime
from typing import Any
from psycopg import errors as psycopg_errors
from psycopg.rows import dict_row
from psycopg_pool import ConnectionPool
@@ -36,6 +39,7 @@ class ProjectStore:
open=False,
)
self._pool.open(wait=False)
self._live_retry_at = 0.0 # latest_version: 007 카운터 테이블 재시도 시각
def close(self) -> None:
self._pool.close()
@@ -166,12 +170,26 @@ class ProjectStore:
raise KeyError(project_id)
return self._serialize(row)
def delete_project(self, *, project_id: int) -> None:
"""프로젝트(서브프로젝트·단계·업무 CASCADE) 삭제."""
def delete_project(self, *, project_id: int) -> list[int]:
"""프로젝트(서브프로젝트·단계·업무 CASCADE) 삭제.
같이 지워진 업무 id 목록을 돌려준다 — DB 행은 CASCADE 로 사라지지만
디스크의 첨부 폴더(DATA_DIR/project/<task_id>)는 라우터가 치워야 한다.
"""
with self._pool.connection() as conn:
cur = conn.execute("DELETE FROM projects WHERE id = %s", (project_id,))
if cur.rowcount == 0:
raise KeyError(project_id)
with conn.transaction():
rows = conn.execute(
"WITH RECURSIVE tree AS ("
" SELECT id FROM projects WHERE id = %s "
" UNION ALL "
" SELECT p.id FROM projects p JOIN tree ON p.parent_id = tree.id"
") SELECT t.id FROM tasks t WHERE t.project_id IN (SELECT id FROM tree)",
(project_id,),
).fetchall()
cur = conn.execute("DELETE FROM projects WHERE id = %s", (project_id,))
if cur.rowcount == 0:
raise KeyError(project_id)
return [int(r["id"]) for r in rows]
# ════════════════════════════════════════════════════════════
# 멤버
@@ -237,6 +255,23 @@ class ProjectStore:
).fetchall()
return [self._serialize(r) for r in rows]
def list_stages_for_projects(self, *, project_ids: list[int]) -> dict[int, list[dict[str, Any]]]:
"""여러 프로젝트의 세션을 한 번에 — {project_id: [stage, ...]} (세션 없는 프로젝트도 빈 목록)."""
ids = [int(i) for i in project_ids]
out: dict[int, list[dict[str, Any]]] = {i: [] for i in ids}
if not ids:
return out
with self._pool.connection() as conn:
rows = conn.execute(
"SELECT * FROM project_stages WHERE project_id = ANY(%s) "
"ORDER BY project_id, sort_order ASC, id ASC",
(ids,),
).fetchall()
for r in rows:
s = self._serialize(r)
out.setdefault(s["project_id"], []).append(s)
return out
def add_stage(
self, *, project_id: int, name: str, is_done_stage: bool = False,
color: str | None = None, created_by: str = "",
@@ -266,6 +301,31 @@ class ProjectStore:
).fetchone()
return self._serialize(row) if row else None
@staticmethod
def _check_stage_in_project(conn: Any, stage_id: Any, project_id: int) -> int | None:
"""세션이 그 프로젝트 것인지 확인하고 int 로 돌려준다(None 은 그대로).
확인 안 하면 다른 프로젝트의 세션 id 를 넣어 업무를 엉뚱한 세션에
묶거나(보드에서 사라짐) 남의 세션 완료 여부로 완료 처리가 될 수 있다.
"""
if stage_id in (None, ""):
return None
try:
sid = int(stage_id)
except (TypeError, ValueError):
raise ValueError("세션 값이 올바르지 않습니다.")
row = conn.execute(
"SELECT 1 FROM project_stages WHERE id = %s AND project_id = %s",
(sid, project_id),
).fetchone()
if not row:
raise ValueError("이 프로젝트의 세션이 아닙니다.")
return sid
def stage_in_project(self, *, stage_id: Any, project_id: int) -> int | None:
with self._pool.connection() as conn:
return self._check_stage_in_project(conn, stage_id, project_id)
def delete_stage(self, *, stage_id: int) -> None:
with self._pool.connection() as conn:
cur = conn.execute("DELETE FROM project_stages WHERE id = %s", (stage_id,))
@@ -360,48 +420,84 @@ class ProjectStore:
def _list_tasks_for_project_with_links(
self, *, project_id: int, assignee_email: str | None, limit: int,
) -> list[dict[str, Any]]:
"""`list_tasks` 의 "이 프로젝트 + 여기 연결된 업무" 경로.
"""`list_tasks` 의 "이 프로젝트 + 여기 연결된 업무" 경로."""
return self.list_tasks_for_projects(
project_ids=[project_id], assignee_email=assignee_email, limit=limit,
)
`t.*` 뒤에 같은 이름(`stage_id`)을 다시 셀렉트해 덮어쓴다 — psycopg 의
dict_row 는 중복 컬럼명이 있으면 마지막 값으로 덮어쓰므로, "이 프로젝트
맥락에서의 세션"(연결이면 link.stage_id, 기본홈이면 t.stage_id)이
최종값이 된다. 원래 소속 프로젝트 배지(`project_name`/`project_color`)는
`t.project_id` 기준 그대로 둬 "다른 프로젝트에서 온 업무"임을 알 수 있게
한다.
def list_tasks_for_projects(
self, *, project_ids: list[int], assignee_email: str | None = None,
limit: int = 20000,
) -> list[dict[str, Any]]:
"""여러 프로젝트의 최상위 업무(+ 각 프로젝트에 연결된 업무)를 쿼리 한 번에.
프로젝트 화면은 접근 가능한 모든 프로젝트의 업무를 그리는데, 예전엔
프로젝트마다 쿼리를 따로 날렸다(N+1). 행마다 붙는 값:
context_project_id : 어느 프로젝트 맥락의 행인지(연결 업무는 연결된 쪽)
is_linked : 다른 프로젝트에서 연결돼 온 행인지
stage_id : 그 맥락에서의 세션(연결이면 link.stage_id — 없으면 NULL)
home_stage_id : 원래 소속 세션(tasks.stage_id). 업무 편집 팝업의
"세션" 선택은 항상 이 값을 쓴다.
`t.*` 뒤에 같은 이름(`stage_id`)을 다시 셀렉트해 덮어쓴다 — dict_row 는
중복 컬럼명이면 마지막 값을 쓴다. 원래 소속 배지(`project_name`/`color`)는
`t.project_id` 기준 그대로 둬 "다른 프로젝트에서 온 업무"임을 보인다.
"""
clauses = [
"t.parent_task_id IS NULL",
"(t.project_id = %(pid)s OR link.project_id = %(pid)s)",
]
params: dict[str, Any] = {"pid": project_id, "limit": int(limit)}
ids = [int(i) for i in project_ids]
if not ids:
return []
params: dict[str, Any] = {"ids": ids, "limit": int(limit)}
extra = ""
if assignee_email:
clauses.append("t.assignee_email = %(assignee)s")
extra = "AND t.assignee_email = %(assignee)s"
params["assignee"] = store.norm_str(assignee_email, lower=True)
where = "WHERE " + " AND ".join(clauses)
with self._pool.connection() as conn:
rows = conn.execute(
f"""
SELECT t.*, p.name AS project_name, p.color AS project_color,
(SELECT COUNT(*) FROM task_comments c WHERE c.task_id = t.id) AS comment_count,
{self._SUBTASK_COUNTS_SQL},
(link.id IS NOT NULL) AS is_linked,
COALESCE(es.name, s.name) AS stage_name,
COALESCE(es.is_done_stage, s.is_done_stage) AS is_done_stage,
COALESCE(link.stage_id, t.stage_id) AS stage_id
FROM tasks t
x.context_project_id,
x.is_linked,
t.stage_id AS home_stage_id,
CASE WHEN x.is_linked THEN es.name ELSE s.name END AS stage_name,
CASE WHEN x.is_linked THEN es.is_done_stage ELSE s.is_done_stage END AS is_done_stage,
CASE WHEN x.is_linked THEN x.link_stage_id ELSE t.stage_id END AS stage_id
FROM (
SELECT id AS task_id, project_id AS context_project_id,
FALSE AS is_linked, NULL::bigint AS link_stage_id
FROM tasks
WHERE parent_task_id IS NULL AND project_id = ANY(%(ids)s)
UNION ALL
SELECT l.task_id, l.project_id, TRUE, l.stage_id
FROM task_project_links l
JOIN tasks lt ON lt.id = l.task_id
WHERE l.project_id = ANY(%(ids)s)
AND lt.parent_task_id IS NULL
AND lt.project_id <> l.project_id
) x
JOIN tasks t ON t.id = x.task_id
JOIN projects p ON p.id = t.project_id
LEFT JOIN project_stages s ON s.id = t.stage_id
LEFT JOIN task_project_links link
ON link.task_id = t.id AND link.project_id = %(pid)s
AND t.project_id <> %(pid)s
LEFT JOIN project_stages es ON es.id = link.stage_id
{where}
ORDER BY t.sort_order ASC, t.id ASC LIMIT %(limit)s
LEFT JOIN project_stages es ON es.id = x.link_stage_id
WHERE TRUE {extra}
ORDER BY x.context_project_id, t.sort_order ASC, t.id ASC
LIMIT %(limit)s
""",
params,
).fetchall()
return [self._serialize(r) for r in rows]
def count_my_open(self, *, assignee_email: str) -> int:
"""사이드바 "내 업무" 배지 — 내가 담당인 미완료 업무 수(하위 업무 포함,
내 업무 화면 목록과 같은 기준)."""
with self._pool.connection() as conn:
row = conn.execute(
"SELECT COUNT(*) AS n FROM tasks "
"WHERE assignee_email = %s AND completed_at IS NULL",
(store.norm_str(assignee_email, lower=True),),
).fetchone()
return int(row["n"] or 0)
def list_my_tasks(self, *, assignee_email: str, limit: int = 1000) -> list[dict[str, Any]]:
""""내 업무" 화면 전용 — 내가 담당자인 업무를 레벨(최상위/하위) 상관없이
전부 반환한다. 하위 업무 행에는 부모 업무 정보(`parent_title` 등)를 같이
@@ -475,9 +571,15 @@ class ProjectStore:
).fetchone()
if not parent:
raise KeyError(f"상위 업무를 찾을 수 없습니다: {parent_task_id}")
project_id = parent["project_id"]
# 권한은 URL 의 project_id 로 검사했으므로, 부모가 다른 프로젝트
# 업무면 거부한다(예전엔 부모 프로젝트로 조용히 바꿔 권한 없는
# 프로젝트에 하위 업무를 만들 수 있었다).
if int(parent["project_id"]) != int(project_id):
raise ValueError("상위 업무가 이 프로젝트에 속하지 않습니다.")
stage_id = None
elif stage_id is None:
elif stage_id not in (None, ""):
stage_id = self._check_stage_in_project(conn, stage_id, project_id)
else:
# stage 미지정 시 프로젝트의 첫 세션으로
st = conn.execute(
"SELECT id FROM project_stages WHERE project_id = %s "
@@ -568,7 +670,9 @@ class ProjectStore:
# 를 그대로 다시 보내는데, 여기서 무조건 판정하면 방금 "완료로 표시"로
# 켠 completed_at 을(단계는 그대로인데) 다시 꺼버리는 버그가 있었다.
if "stage_id" in fields:
new_stage = fields["stage_id"]
new_stage = self.stage_in_project(
stage_id=fields["stage_id"], project_id=prev["project_id"]
)
sets.append("stage_id = %s")
params.append(new_stage)
if new_stage != prev.get("stage_id"):
@@ -611,11 +715,22 @@ class ProjectStore:
out["_newly_completed"] = newly_completed
return out
def delete_task(self, *, task_id: int) -> None:
def delete_task(self, *, task_id: int) -> list[int]:
"""업무(+하위 업무 CASCADE) 삭제. 지워진 업무 id 목록 반환 — 첨부 폴더 정리용."""
with self._pool.connection() as conn:
cur = conn.execute("DELETE FROM tasks WHERE id = %s", (task_id,))
if cur.rowcount == 0:
raise KeyError(task_id)
with conn.transaction():
rows = conn.execute(
"WITH RECURSIVE sub AS ("
" SELECT id FROM tasks WHERE id = %s "
" UNION ALL "
" SELECT t.id FROM tasks t JOIN sub ON t.parent_task_id = sub.id"
") SELECT id FROM sub",
(task_id,),
).fetchall()
cur = conn.execute("DELETE FROM tasks WHERE id = %s", (task_id,))
if cur.rowcount == 0:
raise KeyError(task_id)
return [int(r["id"]) for r in rows]
def _stage_is_done(self, stage_id: Any) -> bool:
if stage_id is None:
@@ -753,16 +868,26 @@ class ProjectStore:
).fetchone()
return self._serialize(out)
def delete_comment(self, *, comment_id: int, requester: str, is_admin: bool) -> None:
def delete_comment(
self, *, comment_id: int, requester: str, is_admin: bool
) -> list[dict[str, Any]]:
"""댓글 삭제. 댓글에 딸린 첨부 행은 CASCADE 로 같이 지워지므로, 디스크
파일을 치울 수 있게 그 첨부(task_id, stored_name) 목록을 돌려준다."""
with self._pool.connection() as conn:
row = conn.execute(
"SELECT author_email FROM task_comments WHERE id = %s", (comment_id,)
).fetchone()
if not row:
raise KeyError(comment_id)
if not is_admin and row["author_email"] != store.norm_str(requester, lower=True):
raise PermissionError("본인 댓글만 삭제할 수 있습니다.")
conn.execute("DELETE FROM task_comments WHERE id = %s", (comment_id,))
with conn.transaction():
row = conn.execute(
"SELECT author_email FROM task_comments WHERE id = %s", (comment_id,)
).fetchone()
if not row:
raise KeyError(comment_id)
if not is_admin and row["author_email"] != store.norm_str(requester, lower=True):
raise PermissionError("본인 댓글만 삭제할 수 있습니다.")
files = conn.execute(
"SELECT task_id, stored_name FROM task_attachments WHERE comment_id = %s",
(comment_id,),
).fetchall()
conn.execute("DELETE FROM task_comments WHERE id = %s", (comment_id,))
return [dict(f) for f in files]
# ════════════════════════════════════════════════════════════
# 첨부 (task_attachments) — 메타만 저장. 파일은 라우터가 디스크 처리.
@@ -847,25 +972,25 @@ class ProjectStore:
def reorder_projects(self, *, ordered_ids: list[int]) -> None:
"""홈 화면 프로젝트 카드 드래그 순서 변경. 최상위 프로젝트(parent_id
IS NULL)만 대상 — 서브프로젝트 정렬(부모 안에서의 순서)은 건드리지 않는다."""
# 순서 재배정은 전부 UPDATE 한 번으로 — unnest(...) WITH ORDINALITY 가
# 배열 순서(1부터)를 매겨준다. 예전엔 항목 수만큼 UPDATE 를 날렸다.
with self._pool.connection() as conn:
with conn.transaction():
for i, pid in enumerate(ordered_ids):
conn.execute(
"UPDATE projects SET sort_order = %s "
"WHERE id = %s AND parent_id IS NULL",
(i, int(pid)),
)
conn.execute(
"UPDATE projects p SET sort_order = v.ord - 1 "
"FROM unnest(%s::bigint[]) WITH ORDINALITY AS v(id, ord) "
"WHERE p.id = v.id AND p.parent_id IS NULL",
([int(i) for i in ordered_ids],),
)
def reorder_stages(self, *, project_id: int, ordered_ids: list[int]) -> None:
"""주어진 순서대로 sort_order 재배정. 해당 프로젝트 단계만 갱신."""
with self._pool.connection() as conn:
with conn.transaction():
for i, sid in enumerate(ordered_ids):
conn.execute(
"UPDATE project_stages SET sort_order = %s "
"WHERE id = %s AND project_id = %s",
(i, int(sid), project_id),
)
conn.execute(
"UPDATE project_stages s SET sort_order = v.ord - 1 "
"FROM unnest(%s::bigint[]) WITH ORDINALITY AS v(id, ord) "
"WHERE s.id = v.id AND s.project_id = %s",
([int(i) for i in ordered_ids], project_id),
)
def reorder_tasks(self, *, stage_id: int, ordered_ids: list[int]) -> None:
"""보드 카드 드래그로 같은 세션 안에서 순서 바꾸기. sort_order 는
@@ -873,13 +998,12 @@ class ProjectStore:
무방 — 화면은 항상 세션으로 먼저 필터링한 뒤 이 값으로 정렬한다),
여기서는 이 세션 소속 업무만 골라 0부터 다시 매긴다."""
with self._pool.connection() as conn:
with conn.transaction():
for i, tid in enumerate(ordered_ids):
conn.execute(
"UPDATE tasks SET sort_order = %s "
"WHERE id = %s AND stage_id = %s",
(i, int(tid), stage_id),
)
conn.execute(
"UPDATE tasks t SET sort_order = v.ord - 1 "
"FROM unnest(%s::bigint[]) WITH ORDINALITY AS v(id, ord) "
"WHERE t.id = v.id AND t.stage_id = %s",
([int(i) for i in ordered_ids], stage_id),
)
# ════════════════════════════════════════════════════════════
# 알림센터 (project_notifications)
@@ -1035,6 +1159,22 @@ class ProjectStore:
# 실시간 새로고침 — 프로젝트/업무/댓글/멤버/단계 중 가장 최근 변경 시각
# ════════════════════════════════════════════════════════════
def latest_version(self) -> str:
"""열어둔 화면이 8초마다 묻는 "뭔가 바뀌었나" 값.
마이그레이션 007 이 있으면 트리거가 올려주는 카운터 한 줄(PK)만 읽는다
— 삭제·세션 이름변경·첨부 추가까지 감지된다. 없으면 예전 MAX() 방식.
"""
if time.monotonic() >= self._live_retry_at:
try:
with self._pool.connection() as conn:
row = conn.execute(
"SELECT version FROM project_live_version WHERE id = 1"
).fetchone()
return f"v{row['version']}" if row else ""
except psycopg_errors.UndefinedTable:
# 5분 뒤 다시 시도 — 재기동 없이 마이그레이션을 적용해도 따라간다.
logger.warning("project_live_version 없음 — project_db_007 마이그레이션 적용 필요(MAX 방식으로 폴백)")
self._live_retry_at = time.monotonic() + 300
with self._pool.connection() as conn:
row = conn.execute(
"SELECT GREATEST("
@@ -1060,7 +1200,7 @@ class ProjectStore:
for k, v in list(out.items()):
if isinstance(v, datetime):
out[k] = v.astimezone(KST).isoformat(timespec="seconds")
elif isinstance(v, time):
elif isinstance(v, dtime):
out[k] = v.strftime("%H:%M")
elif isinstance(v, date):
out[k] = v.isoformat()