Refactor backend and frontend cleanup paths

This commit is contained in:
curo1305
2026-06-16 11:50:17 +02:00
parent 6b56763689
commit e97ca164d7
29 changed files with 1106 additions and 2280 deletions
+68 -137
View File
@@ -1,23 +1,7 @@
"""
Sharing API for DocuVault — Phase 4, Plan 04-04.
Implements SHARE-01 through SHARE-05:
POST /api/shares — grant share by recipient handle
GET /api/shares — list shares owned by current user for a document
GET /api/shares/received — virtual "Shared with me" folder (metadata only)
DELETE /api/shares/{share_id} — revoke share with IDOR protection
Security invariants:
T-04-04-02: DELETE asserts share.owner_id == current_user.id → 404 on mismatch
T-04-04-03: GET /received returns metadata only — extracted_text is never included
T-04-04-04: No quota table is touched anywhere in this module
T-04-04-05: UniqueConstraint(document_id, recipient_id) → IntegrityError → 409
"""
"""Document sharing endpoints."""
from __future__ import annotations
import uuid
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
from pydantic import BaseModel, field_validator
from sqlalchemy import select
@@ -33,9 +17,6 @@ from services.audit import write_audit_log
router = APIRouter(prefix="/api/shares", tags=["shares"])
# ── Request models ────────────────────────────────────────────────────────────
class ShareCreate(BaseModel):
document_id: str
recipient_handle: str
@@ -60,11 +41,47 @@ class SharePermissionPatch(BaseModel):
return v
# ── Helpers ───────────────────────────────────────────────────────────────────
def _parse_uuid(value: str, detail: str) -> uuid.UUID:
try:
return uuid.UUID(value)
except ValueError:
raise HTTPException(status_code=404, detail=detail)
async def _get_owned_document(
session: AsyncSession,
document_id: str,
owner_id: uuid.UUID,
) -> Document:
uid = _parse_uuid(document_id, "Document not found")
doc = await session.get(Document, uid)
if doc is None or doc.user_id != owner_id:
raise HTTPException(status_code=404, detail="Document not found")
return doc
# ── POST /api/shares ──────────────────────────────────────────────────────────
async def _get_owned_share(
session: AsyncSession,
share_id: str,
owner_id: uuid.UUID,
) -> Share:
sid = _parse_uuid(share_id, "Share not found")
share = await session.get(Share, sid)
if share is None or share.owner_id != owner_id:
raise HTTPException(status_code=404, detail="Share not found")
return share
def _share_to_dict(share: Share, recipient: User) -> dict:
return {
"id": str(share.id),
"document_id": str(share.document_id),
"owner_id": str(share.owner_id),
"recipient_id": str(share.recipient_id),
"recipient_handle": recipient.handle,
"permission": share.permission,
"created_at": share.created_at.isoformat() if share.created_at else None,
}
@router.post("", status_code=status.HTTP_201_CREATED)
@@ -74,22 +91,7 @@ async def grant_share(
session: AsyncSession = Depends(get_db),
current_user: User = Depends(get_regular_user),
) -> dict:
"""Grant document share to a user identified by their handle (SHARE-01, D-04).
T-04-04-06: Only document owner can grant; 404 prevents ID enumeration.
T-04-04-01: get_regular_user ensures admins cannot invoke this endpoint.
T-04-04-05: Duplicate share → IntegrityError → 409 (no unbounded inserts).
"""
# Parse document_id as UUID (T-03-11 pattern)
try:
uid = uuid.UUID(body.document_id)
except ValueError:
raise HTTPException(status_code=404, detail="Document not found")
# Ownership assertion — 404 prevents ID enumeration
doc = await session.get(Document, uid)
if doc is None or doc.user_id != current_user.id:
raise HTTPException(status_code=404, detail="Document not found")
doc = await _get_owned_document(session, body.document_id, current_user.id)
# Recipient lookup by exact handle (D-04)
result = await session.execute(
@@ -105,7 +107,7 @@ async def grant_share(
# Create the share row
share = Share(
document_id=uid,
document_id=doc.id,
owner_id=current_user.id,
recipient_id=recipient.id,
permission=body.permission,
@@ -126,25 +128,14 @@ async def grant_share(
event_type="share.granted",
user_id=current_user.id,
actor_id=current_user.id,
resource_id=uid,
resource_id=doc.id,
ip_address=get_client_ip(request),
metadata_={"recipient_id": str(recipient.id)},
)
await session.commit()
return {
"id": str(share.id),
"document_id": str(share.document_id),
"owner_id": str(share.owner_id),
"recipient_id": str(share.recipient_id),
"recipient_handle": recipient.handle,
"permission": share.permission,
"created_at": share.created_at.isoformat() if share.created_at else None,
}
# ── GET /api/shares ───────────────────────────────────────────────────────────
return _share_to_dict(share, recipient)
@router.get("")
@@ -153,46 +144,28 @@ async def list_shares(
session: AsyncSession = Depends(get_db),
current_user: User = Depends(get_regular_user),
) -> dict:
"""List shares owned by current user for a specific document (SHARE-01, D-05).
doc = await _get_owned_document(session, document_id, current_user.id)
Only the document owner can list shares — 404 on mismatch or bad UUID.
"""
try:
uid = uuid.UUID(document_id)
except ValueError:
raise HTTPException(status_code=404, detail="Document not found")
doc = await session.get(Document, uid)
if doc is None or doc.user_id != current_user.id:
raise HTTPException(status_code=404, detail="Document not found")
# Join Share with User to get recipient handles
stmt = (
select(Share, User)
.join(User, User.id == Share.recipient_id)
.where(Share.document_id == uid)
.where(Share.document_id == doc.id)
)
result = await session.execute(stmt)
rows = result.all()
items = []
for share, recipient in rows:
items.append(
{
"id": str(share.id),
"recipient_id": str(share.recipient_id),
"recipient_handle": recipient.handle,
"permission": share.permission,
"created_at": share.created_at.isoformat()
if share.created_at
else None,
}
)
items = [
{
"id": str(share.id),
"recipient_id": str(share.recipient_id),
"recipient_handle": recipient.handle,
"permission": share.permission,
"created_at": share.created_at.isoformat() if share.created_at else None,
}
for share, recipient in result.all()
]
return {"items": items}
# ── GET /api/shares/received ──────────────────────────────────────────────────
# CRITICAL: This endpoint MUST be defined BEFORE DELETE /api/shares/{share_id}.
# Defining it after would cause FastAPI to route GET /api/shares/received as
# DELETE with share_id="received" (path parameter conflict).
@@ -203,12 +176,6 @@ async def list_shared_with_me(
session: AsyncSession = Depends(get_db),
current_user: User = Depends(get_regular_user),
) -> dict:
"""Return documents shared WITH the current user (virtual "Shared with me" folder — D-06).
T-04-04-03: Only metadata is returned — extracted_text is never included.
T-04-04-04: No quota is modified.
Response: {items: [{id, filename, content_type, size_bytes, created_at, owner_handle}]}
"""
stmt = (
select(Document, User)
.join(Share, Share.document_id == Document.id)
@@ -219,26 +186,21 @@ async def list_shared_with_me(
result = await session.execute(stmt)
rows = result.all()
items = []
for doc, owner in rows:
# T-04-04-03: extracted_text is intentionally excluded here
items.append(
{
"id": str(doc.id),
"filename": doc.filename,
"content_type": doc.content_type,
"size_bytes": doc.size_bytes,
"created_at": doc.created_at.isoformat() if doc.created_at else None,
"owner_handle": owner.handle,
}
)
items = [
{
"id": str(doc.id),
"filename": doc.filename,
"content_type": doc.content_type,
"size_bytes": doc.size_bytes,
"created_at": doc.created_at.isoformat() if doc.created_at else None,
"owner_handle": owner.handle,
}
for doc, owner in rows
]
return {"items": items}
# ── PATCH /api/shares/{share_id} ─────────────────────────────────────────────
@router.patch("/{share_id}", status_code=200)
async def update_share_permission(
share_id: str,
@@ -247,20 +209,7 @@ async def update_share_permission(
session: AsyncSession = Depends(get_db),
current_user: User = Depends(get_regular_user),
) -> dict:
"""Update the permission on an existing share (SHARE-03, D-09).
T-06.2-02-01 IDOR protection: 404 on owner mismatch — mirrors revoke_share exactly.
T-06.2-02-02: SharePermissionPatch validator prevents arbitrary string passthrough.
"""
try:
sid = uuid.UUID(share_id)
except ValueError:
raise HTTPException(status_code=404, detail="Share not found")
share = await session.get(Share, sid)
if share is None or share.owner_id != current_user.id:
raise HTTPException(status_code=404, detail="Share not found")
share = await _get_owned_share(session, share_id, current_user.id)
share.permission = body.permission
await write_audit_log(
@@ -277,9 +226,6 @@ async def update_share_permission(
return {"id": str(share.id), "permission": share.permission}
# ── DELETE /api/shares/{share_id} ─────────────────────────────────────────────
@router.delete("/{share_id}", status_code=status.HTTP_204_NO_CONTENT)
async def revoke_share(
share_id: str,
@@ -287,27 +233,12 @@ async def revoke_share(
session: AsyncSession = Depends(get_db),
current_user: User = Depends(get_regular_user),
) -> None:
"""Revoke a share. Only the share owner may revoke (SHARE-04, D-07).
T-04-04-02 IDOR protection: asserts share.owner_id == current_user.id.
Returns 404 (not 403) on mismatch to prevent share ID enumeration.
"""
try:
sid = uuid.UUID(share_id)
except ValueError:
raise HTTPException(status_code=404, detail="Share not found")
share = await session.get(Share, sid)
# CRITICAL IDOR check: 404 on mismatch (not 403) — prevents ID enumeration
if share is None or share.owner_id != current_user.id:
raise HTTPException(status_code=404, detail="Share not found")
share = await _get_owned_share(session, share_id, current_user.id)
document_id = share.document_id
recipient_id = share.recipient_id
await session.delete(share)
# Audit log before commit (D-14 — within the same transaction)
await write_audit_log(
session=session,
event_type="share.revoked",