Skip to content

A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.

feat(api): add collaborator endpoints, profile update, user search and backfill migration

dextmorgnbb502379bd3a
diff --git a/flowsint-api/alembic/versions/a1f2b3c4d5e6_backfill_owner_roles.py b/flowsint-api/alembic/versions/a1f2b3c4d5e6_backfill_owner_roles.py
new file mode 100644
index 00000000..1b939cdf
--- /dev/null
+++ b/flowsint-api/alembic/versions/a1f2b3c4d5e6_backfill_owner_roles.py
@@ -0,0 +1,59 @@
+"""backfill owner roles for existing investigations
+
+Revision ID: a1f2b3c4d5e6
+Revises: bac5764d4496
+Create Date: 2026-04-11 00:00:00.000000
+
+"""
+from typing import Sequence, Union
+from uuid import uuid4
+
+from alembic import op
+import sqlalchemy as sa
+import json
+
+# revision identifiers, used by Alembic.
+revision: str = "a1f2b3c4d5e6"
+down_revision: Union[str, None] = "bac5764d4496"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ """Insert OWNER role entry for every investigation that lacks one."""
+ conn = op.get_bind()
+
+ # Find investigations with no entry in investigation_user_roles
+ rows = conn.execute(
+ sa.text(
+ """
+ SELECT i.id, i.owner_id
+ FROM investigations i
+ LEFT JOIN investigation_user_roles r
+ ON r.investigation_id = i.id AND r.user_id = i.owner_id
+ WHERE r.id IS NULL
+ AND i.owner_id IS NOT NULL
+ """
+ )
+ ).fetchall()
+
+ for inv_id, owner_id in rows:
+ conn.execute(
+ sa.text(
+ """
+ INSERT INTO investigation_user_roles (id, user_id, investigation_id, roles)
+ VALUES (:id, :user_id, :investigation_id, :roles)
+ """
+ ),
+ {
+ "id": str(uuid4()),
+ "user_id": str(owner_id),
+ "investigation_id": str(inv_id),
+ "roles": json.dumps(["owner"]),
+ },
+ )
+
+
+def downgrade() -> None:
+ """No-op: we don't remove the backfilled rows."""
+ pass
diff --git a/flowsint-api/app/api/routes/auth.py b/flowsint-api/app/api/routes/auth.py
index 52066fa9..82752080 100644
--- a/flowsint-api/app/api/routes/auth.py
+++ b/flowsint-api/app/api/routes/auth.py
@@ -1,7 +1,8 @@
-from fastapi import APIRouter, Depends, HTTPException
+from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
+from typing import List
from flowsint_core.core.services import (
create_auth_service,
@@ -9,8 +10,10 @@ from flowsint_core.core.services import (
ConflictError,
DatabaseError,
)
-from app.api.schemas.profile import ProfileCreate
+from flowsint_core.core.models import Profile
from flowsint_core.core.postgre_db import get_db
+from app.api.schemas.profile import ProfileCreate, ProfileRead, ProfileUpdate
+from app.api.deps import get_current_user
router = APIRouter()
@@ -39,3 +42,40 @@ def register(user: ProfileCreate, db: Session = Depends(get_db)):
except (DatabaseError, SQLAlchemyError) as e:
print(f"[ERROR] DB error during registration: {e}")
raise HTTPException(status_code=500, detail="Internal server error")
+
+
[email protected]("/me", response_model=ProfileRead)
+def get_me(current_user: Profile = Depends(get_current_user)):
+ return current_user
+
+
[email protected]("/me", response_model=ProfileRead)
+def update_me(
+ payload: ProfileUpdate,
+ db: Session = Depends(get_db),
+ current_user: Profile = Depends(get_current_user),
+):
+ for key, value in payload.model_dump(exclude_unset=True).items():
+ setattr(current_user, key, value)
+ db.commit()
+ db.refresh(current_user)
+ return current_user
+
+
[email protected]("/users/search", response_model=List[ProfileRead])
+def search_users(
+ q: str = Query(..., min_length=1),
+ db: Session = Depends(get_db),
+ current_user: Profile = Depends(get_current_user),
+):
+ """Search users by email prefix for the share dialog autocomplete."""
+ results = (
+ db.query(Profile)
+ .filter(
+ Profile.email.ilike(f"{q}%"),
+ Profile.id != current_user.id,
+ )
+ .limit(5)
+ .all()
+ )
+ return results
diff --git a/flowsint-api/app/api/routes/investigations.py b/flowsint-api/app/api/routes/investigations.py
index 36f79e62..11e549f9 100644
--- a/flowsint-api/app/api/routes/investigations.py
+++ b/flowsint-api/app/api/routes/investigations.py
@@ -10,6 +10,7 @@ from flowsint_core.core.services import (
create_investigation_service,
NotFoundError,
PermissionDeniedError,
+ ConflictError,
DatabaseError,
)
from app.api.deps import get_current_user
@@ -17,12 +18,24 @@ from app.api.schemas.investigation import (
InvestigationRead,
InvestigationCreate,
InvestigationUpdate,
+ CollaboratorAdd,
+ CollaboratorUpdate,
+ CollaboratorRead,
)
from app.api.schemas.sketch import SketchRead
router = APIRouter()
+def _inject_current_user_role(service, investigation, user_id) -> InvestigationRead:
+ """Build InvestigationRead with the current user's role attached."""
+ result = InvestigationRead.model_validate(investigation)
+ role_entry = service.get_user_role_for_investigation(user_id, investigation.id)
+ if role_entry and role_entry.roles:
+ result.current_user_role = role_entry.roles[0].value
+ return result
+
+
@router.get("", response_model=List[InvestigationRead])
def get_investigations(
db: Session = Depends(get_db),
@@ -30,10 +43,14 @@ def get_investigations(
):
"""Get all investigations accessible to the user based on their roles."""
service = create_investigation_service(db)
- allowed_roles = [Role.OWNER, Role.EDITOR, Role.VIEWER]
- return service.get_accessible_investigations(
+ allowed_roles = [Role.OWNER, Role.ADMIN, Role.EDITOR, Role.VIEWER]
+ investigations = service.get_accessible_investigations(
user_id=current_user.id, allowed_roles=allowed_roles
)
+ return [
+ _inject_current_user_role(service, inv, current_user.id)
+ for inv in investigations
+ ]
@router.post(
@@ -45,11 +62,12 @@ def create_investigation(
current_user: Profile = Depends(get_current_user),
):
service = create_investigation_service(db)
- return service.create(
+ investigation = service.create(
name=payload.name,
description=payload.description,
owner_id=current_user.id,
)
+ return _inject_current_user_role(service, investigation, current_user.id)
@router.get("/{investigation_id}", response_model=InvestigationRead)
@@ -60,7 +78,8 @@ def get_investigation_by_id(
):
service = create_investigation_service(db)
try:
- return service.get_by_id(investigation_id, current_user.id)
+ investigation = service.get_by_id(investigation_id, current_user.id)
+ return _inject_current_user_role(service, investigation, current_user.id)
except NotFoundError:
raise HTTPException(status_code=404, detail="Investigation not found")
except PermissionDeniedError:
@@ -93,13 +112,14 @@ def update_investigation(
):
service = create_investigation_service(db)
try:
- return service.update(
+ investigation = service.update(
investigation_id=investigation_id,
user_id=current_user.id,
name=payload.name,
description=payload.description,
status=payload.status,
)
+ return _inject_current_user_role(service, investigation, current_user.id)
except NotFoundError:
raise HTTPException(status_code=404, detail="Investigation not found")
except PermissionDeniedError:
@@ -122,3 +142,126 @@ def delete_investigation(
raise HTTPException(status_code=403, detail="Forbidden")
except DatabaseError:
raise HTTPException(status_code=500, detail="Failed to clean up graph data")
+
+
+# ── Collaborator endpoints ───────────────────────────────────────────
+
+
+ "/{investigation_id}/collaborators", response_model=List[CollaboratorRead]
+)
+def get_collaborators(
+ investigation_id: UUID,
+ db: Session = Depends(get_db),
+ current_user: Profile = Depends(get_current_user),
+):
+ service = create_investigation_service(db)
+ try:
+ entries = service.get_collaborators(investigation_id, current_user.id)
+ return [
+ CollaboratorRead(
+ id=e.id,
+ user_id=e.user_id,
+ roles=[r.value for r in e.roles],
+ user=e.user,
+ )
+ for e in entries
+ ]
+ except PermissionDeniedError:
+ raise HTTPException(status_code=403, detail="Forbidden")
+
+
+ "/{investigation_id}/collaborators",
+ response_model=CollaboratorRead,
+ status_code=status.HTTP_201_CREATED,
+)
+def add_collaborator(
+ investigation_id: UUID,
+ payload: CollaboratorAdd,
+ db: Session = Depends(get_db),
+ current_user: Profile = Depends(get_current_user),
+):
+ service = create_investigation_service(db)
+ try:
+ role = Role(payload.role.lower())
+ except ValueError:
+ raise HTTPException(status_code=400, detail="Invalid role")
+ try:
+ entry = service.add_collaborator(
+ investigation_id=investigation_id,
+ user_id=current_user.id,
+ target_email=payload.email,
+ role=role,
+ )
+ return CollaboratorRead(
+ id=entry.id,
+ user_id=entry.user_id,
+ roles=[r.value for r in entry.roles],
+ user=entry.user,
+ )
+ except NotFoundError as e:
+ raise HTTPException(status_code=404, detail=str(e.message))
+ except PermissionDeniedError:
+ raise HTTPException(status_code=403, detail="Forbidden")
+ except ConflictError:
+ raise HTTPException(status_code=409, detail="User is already a collaborator")
+
+
+ "/{investigation_id}/collaborators/{user_id}",
+ response_model=CollaboratorRead,
+)
+def update_collaborator_role(
+ investigation_id: UUID,
+ user_id: UUID,
+ payload: CollaboratorUpdate,
+ db: Session = Depends(get_db),
+ current_user: Profile = Depends(get_current_user),
+):
+ service = create_investigation_service(db)
+ try:
+ role = Role(payload.role.lower())
+ except ValueError:
+ raise HTTPException(status_code=400, detail="Invalid role")
+ try:
+ entry = service.update_collaborator_role(
+ investigation_id=investigation_id,
+ user_id=current_user.id,
+ target_user_id=user_id,
+ role=role,
+ )
+ return CollaboratorRead(
+ id=entry.id,
+ user_id=entry.user_id,
+ roles=[r.value for r in entry.roles],
+ user=entry.user,
+ )
+ except NotFoundError:
+ raise HTTPException(status_code=404, detail="Collaborator not found")
+ except PermissionDeniedError:
+ raise HTTPException(status_code=403, detail="Forbidden")
+
+
+ "/{investigation_id}/collaborators/{user_id}",
+ status_code=status.HTTP_204_NO_CONTENT,
+)
+def remove_collaborator(
+ investigation_id: UUID,
+ user_id: UUID,
+ db: Session = Depends(get_db),
+ current_user: Profile = Depends(get_current_user),
+):
+ service = create_investigation_service(db)
+ try:
+ service.remove_collaborator(
+ investigation_id=investigation_id,
+ user_id=current_user.id,
+ target_user_id=user_id,
+ )
+ return None
+ except NotFoundError:
+ raise HTTPException(status_code=404, detail="Collaborator not found")
+ except PermissionDeniedError:
+ raise HTTPException(status_code=403, detail="Forbidden")
diff --git a/flowsint-api/app/api/schemas/investigation.py b/flowsint-api/app/api/schemas/investigation.py
index d9b5d893..52b0d04d 100644
--- a/flowsint-api/app/api/schemas/investigation.py
+++ b/flowsint-api/app/api/schemas/investigation.py
@@ -25,20 +25,7 @@ class InvestigationRead(ORMBase):
owner: Optional[ProfileRead] = None
sketches: list[SketchRead] = []
analyses: list[AnalysisRead] = []
-
-
-class InvestigationProfileCreate(BaseModel):
- investigation_id: UUID4
- profile_id: UUID4
- role: Optional[str] = "member"
-
-
-class InvestigationProfileRead(ORMBase):
- id: int
- created_at: datetime
- investigation_id: UUID4
- profile_id: UUID4
- role: str
+ current_user_role: Optional[str] = None
class InvestigationUpdate(BaseModel):
@@ -46,3 +33,22 @@ class InvestigationUpdate(BaseModel):
description: Optional[str] = None
last_updated_at: datetime
status: str
+
+
+# ── Collaborator schemas ─────────────────────────────────────────────
+
+
+class CollaboratorAdd(BaseModel):
+ email: str
+ role: str # "admin", "editor", "viewer"
+
+
+class CollaboratorUpdate(BaseModel):
+ role: str # "admin", "editor", "viewer"
+
+
+class CollaboratorRead(ORMBase):
+ id: UUID4
+ user_id: UUID4
+ roles: list[str] = []
+ user: Optional[ProfileRead] = None
diff --git a/flowsint-api/app/api/schemas/profile.py b/flowsint-api/app/api/schemas/profile.py
index 62c473fa..1a286e0c 100644
--- a/flowsint-api/app/api/schemas/profile.py
+++ b/flowsint-api/app/api/schemas/profile.py
@@ -1,5 +1,5 @@
from .base import ORMBase
-from pydantic import UUID4, BaseModel, EmailStr
+from pydantic import UUID4, BaseModel, ConfigDict, EmailStr
from typing import Optional
@@ -13,3 +13,12 @@ class ProfileRead(ORMBase):
first_name: Optional[str]
last_name: Optional[str]
avatar_url: Optional[str]
+ email: Optional[str] = None
+
+
+class ProfileUpdate(BaseModel):
+ model_config = ConfigDict(extra="forbid")
+
+ first_name: Optional[str] = None
+ last_name: Optional[str] = None
+ avatar_url: Optional[str] = None