Files
leocrm/app/plugins/builtins/permissions/public_routes.py
T
Agent Zero abbe7a18fc fix(audit): P0-P3 audit fixes — 838 ruff errors → 0, 30 F821 bugs fixed, 118 files changed
- P0: hooks.py 3-tuple fix, trigger_dispatcher Contract, contacts/plugin unregister_actions_by_owner
- P0: 5 test files — check_permission mocks removed, hardcoded DB credential → env var
- P1: attachment_service DmsFile via Contract helper, restore_registry/history_hooks dedup
- P1: mail/plugin restore unregister, mcp_client datetime.now(UTC), saved_views/filters patterns
- P1: ProtectedRoute fail-closed, 13 test assertion fixes (bcrypt, DB-URLs, SECRET_KEYs)
- P2: deprecated notifications → post_system_message (3 files), forgejo Base, report_generator lazy import
- P2: webhooks permissions, deps.py/roles.py plugin perms removed, import_export default
- P2: address/tags/entity_links patterns removed, worker.py Contract-Umgehungen fixed
- P2: 28 frontend TODOs (hardcoded constants, deprecated notification API)
- P3: dead code, duplicates, deprecated imports, private attr, __import__ inline
- P3: 8 frontend TODOs (LucideIcons, inline styles, XSS, i18n)
- ruff: 838 → 0 (612 auto-fix + 246 manual + 27 F821 regression fix)
- F821: 30 → 0 (AutomationDefinition, DmsFile, user_id, Path, Any, String)
- Contract-Umgehungen: 2 neue gefunden (worker.py:169, worker.py:280) und gefixt
2026-08-16 01:17:18 +02:00

120 lines
4.2 KiB
Python

"""Public share routes — token-based access to shared files, no auth required."""
from __future__ import annotations
import uuid
from datetime import UTC, datetime
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.responses import StreamingResponse
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.db import get_db
from app.core.storage import get_storage_backend
from app.plugins.builtins.dms.contracts import DmsContract
from app.plugins.builtins.permissions.models import ShareLink
DmsFile = DmsContract.DmsFile
router = APIRouter(prefix="/api/v1/public/share", tags=["public-share"])
@router.get("/{token}", status_code=status.HTTP_200_OK)
async def get_share_info(token: str, db: AsyncSession = Depends(get_db)):
"""Get share link info by token (public, no auth required).
Returns file metadata without requiring authentication.
If the share link has a password, the client must provide it via POST.
"""
share = await _get_share_link(db, token)
file = await _get_file(db, share.file_id, share.tenant_id)
return {
"file_name": file.name,
"file_size": file.size_bytes,
"mime_type": file.mime_type,
"access_level": share.access_level,
"requires_password": share.password_hash is not None,
"expires_at": share.expires_at.isoformat() if share.expires_at else None,
}
@router.post("/{token}/verify", status_code=status.HTTP_200_OK)
async def verify_share_password(
token: str,
password: str,
db: AsyncSession = Depends(get_db),
):
"""Verify password for a password-protected share link."""
share = await _get_share_link(db, token)
if share.password_hash is None:
return {"valid": True}
from app.core.auth import verify_password
if not verify_password(password, share.password_hash):
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail={"detail": "Invalid password", "code": "invalid_password"},
)
return {"valid": True}
@router.get("/{token}/download", status_code=status.HTTP_200_OK)
async def download_shared_file(token: str, db: AsyncSession = Depends(get_db)):
"""Download file via share link token (public, no auth required)."""
share = await _get_share_link(db, token)
file = await _get_file(db, share.file_id, share.tenant_id)
storage = get_storage_backend()
if not await storage.exists(file.storage_path):
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={"detail": "File not found on disk", "code": "file_missing"},
)
stream = await storage.get_stream(file.storage_path)
return StreamingResponse(
stream,
media_type=file.mime_type,
headers={
"Content-Disposition": f'attachment; filename="{file.name}"',
"Content-Length": str(file.size_bytes),
},
)
async def _get_share_link(db: AsyncSession, token: str) -> ShareLink:
"""Get share link by token and validate expiry."""
result = await db.execute(
select(ShareLink).where(ShareLink.token == token)
)
share = result.scalar_one_or_none()
if share is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={"detail": "Share link not found", "code": "share_not_found"},
)
if share.expires_at is not None and share.expires_at < datetime.now(UTC):
raise HTTPException(
status_code=status.HTTP_410_GONE,
detail={"detail": "Share link expired", "code": "share_expired"},
)
return share
async def _get_file(db: AsyncSession, file_id: uuid.UUID, tenant_id: uuid.UUID) -> DmsFile:
"""Get file by ID within tenant scope."""
result = await db.execute(
select(DmsFile)
.where(DmsFile.id == file_id)
.where(DmsFile.tenant_id == tenant_id)
.where(DmsFile.deleted_at.is_(None))
)
file = result.scalar_one_or_none()
if file is None:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail={"detail": "File not found", "code": "file_not_found"},
)
return file