Files
resolutionflow/backend/app/api/endpoints/shares.py
chihlasm b3dba57bc5 feat: tenant isolation Phase 0 — app-layer filters, UUID audit, CI gate (#132)
* docs: add tenant data isolation design spec

Complete architecture plan for multi-tenant data isolation across
all layers (PostgreSQL RLS, application-layer filtering, schema
migration, testing strategy, and phased rollout checklist).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: add background job isolation policy to tenant isolation spec

Documents policy for all 5 existing background jobs:
- Knowledge Flywheel and PSA Retry flagged for account_id threading
- Chat Retention already follows correct pattern (model for others)
- Maintenance Schedule Firing needs account_id in queries + Session creation
- AI Conversation Expiry approved as cross-tenant with justification

Adds approved cross-tenant query registry and Phase 2 checklist items.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: add tenant isolation Phase 0 implementation plan

8 tasks covering: CRITICAL copilot hotfix, tenant_filter() helper,
get_tenant_context dependency, analytics/category/AI session gap fixes,
full UUID endpoint audit, TargetList dead code audit, teams orphan
check, and CI grep check for missing tenant filters.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: add tenant_filter() helper and get_tenant_context dependency

tenant_filter(model, account_id) is the canonical app-layer tenant
scoping expression. Every query on a tenant table must use it.
build_tree_access_filter and build_step_visibility_filter updated
to call tenant_filter() internally for the account_id match.

get_tenant_context is a FastAPI dependency that returns account_id
or raises 403 if the user has no account — prevents raw access to
current_user.account_id and centralises the null check.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: scope analytics/flows/{tree_id} to requesting account

Any authenticated user could read flow analytics (session counts,
completion rates, CSAT) for any tree UUID. Now returns 404 if the
tree doesn't belong to the requesting account.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: scope category tree_count to requesting account

tree_count on GET /categories/{id} was including trees from all
accounts, leaking cross-tenant row counts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: restrict AI session search to current user only

Search endpoint used OR(user_id, account_id), exposing other users'
problem_summary and problem_domain within the same account. Sessions
are user-scoped only — cross-user access requires explicit escalation
or sharing. List and search endpoints now behave consistently.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: add ownership check and 404 responses to ai-sessions endpoints

Cross-tenant isolation audit found:
- retry-psa-push had NO ownership check (CRITICAL) — any user could retry any session's PSA push
- save_task_lane used db.get() without ownership filter, returned 403 revealing existence
- get_session returned 403 instead of 404 for unauthorized access
- stream_documentation returned 403 instead of 404

All now use query-level user_id filtering and return 404 to avoid revealing existence.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: return 404 instead of 403 for cross-tenant session access

All session endpoints (get, update, complete, scratchpad, variables, export,
ticket-link) now return 404 instead of 403 when a user tries to access
another user's session. This prevents confirming existence of resources
across tenant boundaries.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: return 404 instead of 403 for cross-tenant tree access

get_tree and update_tree now return 404 when a user cannot access a tree
(private tree from another account). Prevents confirming resource existence
across tenant boundaries.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: return 404 instead of 403 for cross-tenant step access

get_step_or_404 now returns 404 when can_view_step or can_edit_step fails,
preventing confirmation of step existence across tenant boundaries.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: return 404 instead of 403 for cross-tenant upload access

get_upload_url and delete_upload now return 404 when the upload belongs to
a different account/user, preventing resource existence confirmation.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: return 404 instead of 403 for cross-tenant share access

revoke_share and create_share now return 404 when the caller is not the
owner, preventing resource existence confirmation across users.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: return 404 instead of 403 for cross-team tree access in maintenance schedules

_get_tree_or_403 now returns 404 when the user's team does not match,
preventing confirmation of tree existence across teams.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: return 404 instead of 403 for cross-account tag access

get_tag now returns 404 for account-specific tags that belong to another
account, preventing resource existence confirmation.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: return 404 instead of 403 for cross-account step category access

get_step_category now returns 404 for account-specific categories that
belong to another account, preventing resource existence confirmation.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: add cross-tenant isolation tests for Task 6 UUID audit

Tests cover:
- Tree GET/PUT returns 404 for cross-account access
- Session GET returns 404 for cross-user access
- AI session GET returns 404 for cross-user access
- AI session retry-psa-push requires ownership
- Upload URL returns 404 for cross-account access
- Share revoke returns 404 for cross-user access

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: return 404 (not 403) for get_documentation cross-user access; add missing Task 6 tests

get_documentation was revealing session existence via 403. Added pre-check
query filtering by session_id AND user_id before calling the engine.

Also add cross-tenant isolation tests for steps, tags, step_categories,
and maintenance_schedules endpoints fixed in Task 6 (TDD was skipped).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address Task 6 quality review — rename helper, restore 403 for intra-account, add docs test

- Rename _get_tree_or_403 → _get_tree_or_404 in maintenance_schedules.py
  (function now raises 404, old name was misleading)
- Restore HTTP 403 for intra-account permission failures in update_tree:
  same-account users who can see a tree but can't edit it got 404 (wrong);
  only cross-account lookups should return 404 to avoid confirming existence
- Apply same 403/404 distinction to update_tree_visibility
- Add test: get_documentation must return 404 for cross-user session access
- Add comment documenting owner-only design for documentation endpoints

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* chore: Task 7+8 — TargetList audit, CI tenant-filter grep check

Task 7: TargetList dead code audit
- Found active code references in 12+ files across backend and frontend
  (full CRUD API + frontend page + MaintenanceScheduleSection + BatchLaunchModal)
- Decision: migrate to account_id in Phase 1 (cannot drop)
- DB row count not available from code-server — must verify from VPS SSH
  before Phase 1 migration
- Teams orphan check query documented; must run from VPS SSH before Phase 1
- Results documented in spec Section 9

Task 8: CI tenant-filter enforcement check (warn mode)
- Create backend/scripts/check_tenant_filters.py
  Scans endpoint and service files for select() on tenant tables without
  tenant_filter/account_id/user_id in surrounding context. Currently
  reports 109 warnings (Phase 1 backlog). Exits 0 (warn mode).
- Add Check tenant filter enforcement step to backend CI job
  Add --fail flag after Phase 1 backlog clears to make it blocking.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: record Phase 0 audit results — 0 orphaned teams, 0 target_list rows

Both checks confirmed 2026-04-09 from production DB.
Phase 1 migration is safe to proceed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-09 00:42:19 -04:00

288 lines
9.5 KiB
Python

import secrets
from datetime import datetime, timezone
from typing import Annotated, Optional
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Request, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select
from sqlalchemy.orm import joinedload
from sqlalchemy.exc import IntegrityError
from app.core.database import get_db
from app.models.session import Session
from app.models.session_share import SessionShare, SessionShareView
from app.models.user import User
from app.models.account import Account
from app.schemas.session_share import ShareCreate, ShareResponse, SharePublicView
from app.api.deps import get_current_active_user, require_engineer_or_admin
from app.core.audit import log_audit
from app.core.rate_limit import limiter
router = APIRouter(tags=["shares"])
def build_share_response(share: SessionShare) -> ShareResponse:
return ShareResponse(
id=share.id,
session_id=share.session_id,
account_id=share.account_id,
share_token=share.share_token,
share_name=share.share_name,
visibility=share.visibility,
created_by=share.created_by,
created_at=share.created_at,
updated_at=share.updated_at,
expires_at=share.expires_at,
view_count=share.view_count,
last_viewed_at=share.last_viewed_at,
is_active=share.is_active,
)
# --- Session Share CRUD ---
@router.post(
"/sessions/{session_id}/shares",
response_model=ShareResponse,
status_code=status.HTTP_201_CREATED
)
async def create_share(
session_id: UUID,
share_data: ShareCreate,
db: Annotated[AsyncSession, Depends(get_db)],
current_user: Annotated[User, Depends(require_engineer_or_admin)]
):
"""Create a share link for a session.
Only the session owner can create shares.
Public shares require account.allow_public_shares policy.
"""
# Verify session exists and user owns it
result = await db.execute(
select(Session).where(Session.id == session_id)
)
session = result.scalar_one_or_none()
if not session:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Session not found"
)
if session.user_id != current_user.id and not current_user.is_super_admin:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Session not found"
)
# Require account_id for account-scoped shares
if share_data.visibility == "account" and not current_user.account_id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Cannot create account-scoped share without an account"
)
# Check account policy for public shares
if share_data.visibility == "public" and current_user.account_id:
account_result = await db.execute(
select(Account).where(Account.id == current_user.account_id)
)
account = account_result.scalar_one_or_none()
if account and not account.allow_public_shares:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Your organization does not allow public session sharing. Use account-only visibility."
)
# Generate token with collision retry
max_retries = 3
for attempt in range(max_retries):
try:
share_token = secrets.token_urlsafe(48)
share = SessionShare(
session_id=session_id,
account_id=current_user.account_id,
share_token=share_token,
share_name=share_data.share_name,
visibility=share_data.visibility,
created_by=current_user.id,
expires_at=share_data.expires_at,
)
db.add(share)
await db.flush()
await log_audit(db, current_user.id, "share.create", "session_share", share.id,
{"session_id": str(session_id), "visibility": share_data.visibility})
await db.commit()
await db.refresh(share)
return build_share_response(share)
except IntegrityError as e:
await db.rollback()
if "session_shares_share_token_key" in str(e) and attempt < max_retries - 1:
continue
raise
@router.get("/shares/my-shares", response_model=list[ShareResponse])
async def list_my_shares(
db: Annotated[AsyncSession, Depends(get_db)],
current_user: Annotated[User, Depends(get_current_active_user)],
skip: int = Query(0, ge=0),
limit: int = Query(50, ge=1, le=100)
):
"""List all shares created by the current user."""
result = await db.execute(
select(SessionShare)
.where(
SessionShare.created_by == current_user.id,
SessionShare.is_active == True
)
.order_by(SessionShare.created_at.desc())
.offset(skip)
.limit(limit)
)
shares = result.scalars().all()
return [build_share_response(s) for s in shares]
@router.delete("/shares/{share_id}", status_code=status.HTTP_204_NO_CONTENT)
async def revoke_share(
share_id: UUID,
db: Annotated[AsyncSession, Depends(get_db)],
current_user: Annotated[User, Depends(get_current_active_user)]
):
"""Revoke a share link (soft delete - sets is_active=False)."""
result = await db.execute(
select(SessionShare).where(SessionShare.id == share_id)
)
share = result.scalar_one_or_none()
if not share:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Share not found"
)
if share.created_by != current_user.id and not current_user.is_super_admin:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Share not found"
)
share.is_active = False
await log_audit(db, current_user.id, "share.revoke", "session_share", share.id,
{"session_id": str(share.session_id)})
await db.commit()
return None
# --- Public Share Access ---
async def _get_optional_user(request: Request, db: AsyncSession) -> Optional[User]:
"""Try to extract authenticated user from request, return None if not authenticated."""
auth_header = request.headers.get("Authorization", "")
if not auth_header.startswith("Bearer "):
return None
token = auth_header.replace("Bearer ", "")
try:
from app.core.security import decode_token
payload = decode_token(token)
if not payload or payload.get("type") != "access":
return None
user_id = payload.get("sub")
if not user_id:
return None
result = await db.execute(select(User).where(User.id == UUID(user_id)))
return result.scalar_one_or_none()
except Exception:
return None
@router.get("/share/{share_token}", response_model=SharePublicView)
@limiter.limit("30/minute")
async def access_share(
share_token: str,
request: Request,
db: Annotated[AsyncSession, Depends(get_db)],
):
"""Access a shared session via share token.
Public shares: No authentication required.
Account-only shares: Requires authentication + account membership.
"""
current_user = await _get_optional_user(request, db)
# Lookup share
result = await db.execute(
select(SessionShare)
.options(joinedload(SessionShare.session))
.where(SessionShare.share_token == share_token)
)
share = result.scalar_one_or_none()
# Validate share
if not share or not share.is_active:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Share not found or has been revoked"
)
if share.expires_at and share.expires_at < datetime.now(timezone.utc):
raise HTTPException(
status_code=status.HTTP_410_GONE,
detail="Share link has expired"
)
# Check visibility
if share.visibility == "account":
if not current_user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="This share requires authentication"
)
if current_user.account_id != share.account_id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="You don't have access to this session"
)
# Record view
session = share.session
view = SessionShareView(
share_id=share.id,
session_id=session.id,
viewer_id=current_user.id if current_user else None,
viewer_ip=request.client.host if request.client else None,
viewer_user_agent=request.headers.get("user-agent"),
)
db.add(view)
share.view_count += 1
share.last_viewed_at = datetime.now(timezone.utc)
await db.commit()
# Build read-only response
tree_snapshot = session.tree_snapshot or {}
return SharePublicView(
session_id=session.id,
tree_name=tree_snapshot.get("question", "Untitled Tree"),
tree_description=tree_snapshot.get("description"),
tree_structure=tree_snapshot,
path_taken=session.path_taken or [],
decisions=session.decisions or [],
custom_steps=session.custom_steps or [],
started_at=session.started_at,
completed_at=session.completed_at,
ticket_number=session.ticket_number,
client_name=session.client_name,
share_name=share.share_name,
visibility=share.visibility,
)