From 178155df6bf4294800480bcd404077c1e7f8ee90 Mon Sep 17 00:00:00 2001 From: Hyungi Ahn Date: Thu, 9 Apr 2026 13:28:24 +0900 Subject: [PATCH] =?UTF-8?q?fix(tkqc):=20=EC=82=AC=EC=A7=84=20silent=20data?= =?UTF-8?q?=20loss=20=EC=B0=A8=EB=8B=A8=20+=20=EA=B4=80=EB=A6=AC=ED=95=A8?= =?UTF-8?q?=20=EC=82=AC=EC=A7=84=20=EB=B3=B4=EC=B6=A9=20=EA=B8=B0=EB=8A=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 근본 원인: 2026-04-01 보안 패치(f09c86e)에서 system3-api Dockerfile에 USER appuser 추가했으나, named volume(tkqc-package_uploads)이 root 소유로 남아있어 appuser(999)가 /app/uploads 에 쓰기 실패. 하지만 file_service.py 가 except → return None 으로 silent failure 처리해서 system2는 200 OK 로 인식. 결과: 4/1 이후 qc_issues.id=185~191 사진이 전부 photo_path=NULL. 조치: 1. system3 Dockerfile: entrypoint.sh 추가 → 시작 시 chown 후 gosu appuser 강등 (named volume 이 restart 후에도 root로 돌아가는 문제 영구 해결) 2. file_service.py: save_base64_image 실패 시 RuntimeError raise (silent 금지) 3. system2 workIssueController: sendToMProject 실패/예외 시 system 알림 발송 4. 관리함 (desktop + mobile): 이슈 상세/편집 모달에 원본 사진 보충 UI 추가 - 빈 슬롯(photo_path{N}=NULL)에만 자동 채움, 기존 사진 유지 - ManagementUpdateRequest 스키마에 photo/photo2~5 필드 추가 - update_issue_management 엔드포인트에 사진 저장 루프 추가 런타임 chown 으로 immediate data loss 는 이미 차단됨 (09:28 KST). 이 커밋은 재발 방지 + 데이터 복구 UI 제공. Co-Authored-By: Claude Opus 4.6 (1M context) --- .../api/controllers/workIssueController.js | 24 ++++++ system3-nonconformance/api/Dockerfile | 13 +++- .../api/database/schemas.py | 6 ++ system3-nonconformance/api/entrypoint.sh | 20 +++++ system3-nonconformance/api/routers/issues.py | 25 +++++- .../api/services/file_service.py | 5 +- .../web/issues-management.html | 2 +- system3-nonconformance/web/m/management.html | 11 ++- .../web/static/js/m/m-management.js | 78 +++++++++++++++++++ .../web/static/js/pages/issues-management.js | 65 +++++++++++++--- 10 files changed, 230 insertions(+), 19 deletions(-) create mode 100644 system3-nonconformance/api/entrypoint.sh diff --git a/system2-report/api/controllers/workIssueController.js b/system2-report/api/controllers/workIssueController.js index 67516b9..9a7895c 100644 --- a/system2-report/api/controllers/workIssueController.js +++ b/system2-report/api/controllers/workIssueController.js @@ -257,12 +257,36 @@ exports.createReport = async (req, res) => { if (result.success && result.mProjectId) { await workIssueModel.updateMProjectId(reportId, result.mProjectId); console.log(`[System3 연동] m_project_id=${result.mProjectId} 업데이트 완료`); + } else { + // ⚠ System3 연동 실패 감지 — silent data loss 방지 (2026-04-09 사고 교훈) + console.error(`[System3 연동 실패] report_id=${reportId} error=${result.error || 'unknown'}`); + notify.send({ + type: 'system', + title: 'tkqc 연동 실패', + message: `부적합 신고 #${reportId} (사진 ${photoBase64List.length}장) 전달 실패 — ${result.error || 'unknown'}`, + link_url: `/pages/safety/issue-detail.html?id=${reportId}`, + reference_type: 'work_issue_reports', + reference_id: reportId, + created_by: req.user.id || req.user.user_id + }).catch(e => console.error('[알림 전송 실패]', e.message)); } } else { console.log(`[System3 연동] 부적합 아님, 건너뜀`); } } catch (e) { console.error('[System3 연동 실패]', e.message, e.stack); + // 예외 케이스도 알림 + try { + notify.send({ + type: 'system', + title: 'tkqc 연동 예외', + message: `부적합 신고 #${reportId} 전달 중 예외: ${e.message}`, + link_url: `/pages/safety/issue-detail.html?id=${reportId}`, + reference_type: 'work_issue_reports', + reference_id: reportId, + created_by: req.user.id || req.user.user_id + }).catch(() => {}); + } catch (_) {} } } catch (error) { console.error('신고 생성 에러:', error); diff --git a/system3-nonconformance/api/Dockerfile b/system3-nonconformance/api/Dockerfile index 1ff2ae4..fdb7697 100644 --- a/system3-nonconformance/api/Dockerfile +++ b/system3-nonconformance/api/Dockerfile @@ -2,9 +2,10 @@ FROM python:3.11-slim WORKDIR /app -# 시스템 패키지 설치 +# 시스템 패키지 설치 (gosu: entrypoint 에서 root→appuser 강등용) RUN apt-get update && apt-get install -y \ gcc \ + gosu \ && rm -rf /var/lib/apt/lists/* # Python 의존성 설치 @@ -17,12 +18,16 @@ RUN groupadd -r appuser && useradd -r -g appuser appuser # 애플리케이션 파일 복사 COPY --chown=appuser:appuser . . -# uploads 디렉토리 생성 +# uploads 디렉토리 생성 (entrypoint 가 볼륨 마운트 후 재-chown) RUN mkdir -p /app/uploads && chown appuser:appuser /app/uploads +# entrypoint 실행권한 +RUN chmod +x /app/entrypoint.sh + # 포트 노출 EXPOSE 8000 -# 실행 명령 -USER appuser +# 실행 (root 로 시작 → entrypoint 에서 chown → gosu 로 appuser 강등) +# USER 지시어는 entrypoint 에서 직접 처리하므로 생략한다. +ENTRYPOINT ["/app/entrypoint.sh"] CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] diff --git a/system3-nonconformance/api/database/schemas.py b/system3-nonconformance/api/database/schemas.py index 556d776..874b7e4 100644 --- a/system3-nonconformance/api/database/schemas.py +++ b/system3-nonconformance/api/database/schemas.py @@ -240,6 +240,12 @@ class ManagementUpdateRequest(BaseModel): completion_photo3: Optional[str] = None # Base64 - 완료 사진 3 completion_photo4: Optional[str] = None # Base64 - 완료 사진 4 completion_photo5: Optional[str] = None # Base64 - 완료 사진 5 + # 원본(부적합) 사진 보충 — NULL 슬롯에만 채워넣도록 클라이언트에서 제어 (2026-04-09) + photo: Optional[str] = None # Base64 - 원본 사진 1 + photo2: Optional[str] = None # Base64 - 원본 사진 2 + photo3: Optional[str] = None # Base64 - 원본 사진 3 + photo4: Optional[str] = None # Base64 - 원본 사진 4 + photo5: Optional[str] = None # Base64 - 원본 사진 5 review_status: Optional[ReviewStatus] = None class OpinionRequest(BaseModel): diff --git a/system3-nonconformance/api/entrypoint.sh b/system3-nonconformance/api/entrypoint.sh new file mode 100644 index 0000000..765b028 --- /dev/null +++ b/system3-nonconformance/api/entrypoint.sh @@ -0,0 +1,20 @@ +#!/bin/sh +# entrypoint.sh — 볼륨 권한 보정 후 appuser 로 강등 실행 +# +# Why: Dockerfile 의 `chown /app/uploads` 는 이미지 레이어에만 반영되고, +# docker-compose 의 named volume 은 최초 생성 시점의 소유자를 유지한다. +# 재배포해도 볼륨은 root 소유로 남아 appuser(999) 가 write 불가. +# → 컨테이너 시작 시마다 root 로 chown 하고 gosu 로 appuser 강등. +# +# 2026-04-09: 이 보정 누락으로 tkqc 사진이 silent 하게 유실됐다 (qc_issues.id=185~191). +set -e + +UPLOAD_DIR="/app/uploads" + +if [ -d "$UPLOAD_DIR" ]; then + chown -R appuser:appuser "$UPLOAD_DIR" || { + echo "[entrypoint] WARNING: chown $UPLOAD_DIR 실패 — 이미 appuser 소유이거나 read-only 볼륨일 수 있음" >&2 + } +fi + +exec gosu appuser "$@" diff --git a/system3-nonconformance/api/routers/issues.py b/system3-nonconformance/api/routers/issues.py index 4536aff..8a2afa2 100644 --- a/system3-nonconformance/api/routers/issues.py +++ b/system3-nonconformance/api/routers/issues.py @@ -372,9 +372,30 @@ async def update_issue_management( except Exception as e: raise HTTPException(status_code=400, detail=f"완료 사진 저장 실패: {str(e)}") - # 나머지 필드 처리 (완료 사진 제외) + # 원본(부적합) 사진 보충 처리 — 클라이언트가 빈 슬롯에만 채우도록 제어함 + # (2026-04-09: tkreport→tkqc 연동 중 유실된 사진 복구 용도로 추가) + photo_fields = [] + for i in range(1, 6): + photo_field = f"photo{i if i > 1 else ''}" + path_field = f"photo_path{i if i > 1 else ''}" + + if photo_field in update_data and update_data[photo_field]: + photo_fields.append(photo_field) + try: + # 기존 사진이 있으면 교체 (클라이언트가 의도적으로 지정한 경우) + existing_path = getattr(issue, path_field, None) + if existing_path: + delete_file(existing_path) + + # 새 사진 저장 (prefix "image" — inbox/신규 생성과 동일) + new_path = save_base64_image(update_data[photo_field], "image") + setattr(issue, path_field, new_path) + except Exception as e: + raise HTTPException(status_code=400, detail=f"사진 저장 실패: {str(e)}") + + # 나머지 필드 처리 (사진 필드 제외) for field, value in update_data.items(): - if field not in completion_photo_fields: + if field not in completion_photo_fields and field not in photo_fields: try: setattr(issue, field, value) except Exception as e: diff --git a/system3-nonconformance/api/services/file_service.py b/system3-nonconformance/api/services/file_service.py index 9c5aca0..5308029 100644 --- a/system3-nonconformance/api/services/file_service.py +++ b/system3-nonconformance/api/services/file_service.py @@ -122,7 +122,10 @@ def save_base64_image(base64_string: str, prefix: str = "image") -> Optional[str except Exception as e: print(f"이미지 저장 실패: {e}") - return None + # ⚠ silent failure 금지 — 저장 실패는 반드시 상위로 전파해서 + # system2/클라이언트가 "성공"으로 오인하지 않도록 한다. + # (2026-04-09: named volume 권한 이슈로 사진 유실 사고 재발 방지) + raise RuntimeError(f"Image save failed: {e}") from e def delete_file(filepath: str): """파일 삭제""" diff --git a/system3-nonconformance/web/issues-management.html b/system3-nonconformance/web/issues-management.html index 4b8fa42..36f6ffc 100644 --- a/system3-nonconformance/web/issues-management.html +++ b/system3-nonconformance/web/issues-management.html @@ -349,6 +349,6 @@ - + diff --git a/system3-nonconformance/web/m/management.html b/system3-nonconformance/web/m/management.html index 58069ea..cd90489 100644 --- a/system3-nonconformance/web/m/management.html +++ b/system3-nonconformance/web/m/management.html @@ -92,6 +92,15 @@ + +
+ +
+ +
+

※ 비어있는 슬롯에만 자동 채움. 기존 사진은 유지됩니다.

+