A modern platform for visual, flexible, and extensible graph-based investigations. For cybersecurity analysts and investigators.
fix(api): require sketch permission before launching an enricher
dextmorgn80ecb58bbb14
diff --git a/flowsint-api/app/api/routes/enrichers.py b/flowsint-api/app/api/routes/enrichers.pyindex f0e46a17..23b9c956 100644--- a/flowsint-api/app/api/routes/enrichers.py+++ b/flowsint-api/app/api/routes/enrichers.py@@ -10,6 +10,8 @@ from flowsint_core.core.graph import create_graph_servicefrom flowsint_core.core.models import Profilefrom flowsint_core.core.postgre_db import get_dbfrom flowsint_core.core.services import (+ NotFoundError,+ PermissionDeniedError,create_enricher_service,create_enricher_template_service,)@@ -59,7 +61,12 @@ async def launch_enricher(current_user: Profile = Depends(get_current_user),db: Session = Depends(get_db),) -> Dict[str, str]:+ enricher_service = create_enricher_service(db)try:+ # Before anything reads the graph: an enricher writes its findings into+ # this sketch, so the caller needs update rights on its investigation.+ enricher_service.get_sketch_for_launch(payload.sketch_id, current_user.id)+# Retrieve nodes from Neo4J by their element IDstype_registry = create_type_registry_service(db)resolver = type_registry.build_type_resolver(current_user.id)@@ -109,6 +116,10 @@ async def launch_enricher(except HTTPException:raise+ except NotFoundError as e:+ raise HTTPException(status_code=404, detail=str(e))+ except PermissionDeniedError:+ raise HTTPException(status_code=403, detail="Forbidden")except Exception as e:print(e)raise HTTPException(diff --git a/flowsint-api/tests/test_enrichers.py b/flowsint-api/tests/test_enrichers.pyindex 6d27c547..314e0798 100644--- a/flowsint-api/tests/test_enrichers.py+++ b/flowsint-api/tests/test_enrichers.py@@ -7,7 +7,14 @@ import pytestfrom app.api.routes import enrichers as enrichers_routefrom flowsint_core.core.auth import create_access_token-from flowsint_core.core.models import EnricherTemplate, Profile+from flowsint_core.core.models import (+ EnricherTemplate,+ Investigation,+ InvestigationUserRole,+ Profile,+ Sketch,+)+from flowsint_core.core.types import Roledef _seed_template_owner(db_session, secrets):@@ -97,26 +104,43 @@ def sent_task(monkeypatch):return captured-def _launch(client, db_session, body):- user = Profile(id=uuid.uuid4(), email="[email protected]", hashed_password="x")- db_session.add(user)+def _seed_user(db_session, roles):+ """A user, their own investigation and sketch, and the role row that decides+ what they may do there. `roles=()` seeds no role row at all, which is how a+ stranger stands towards someone else's investigation."""+ user = Profile(+ id=uuid.uuid4(), email=f"{uuid.uuid4()}@example.com", hashed_password="x"+ )+ investigation = Investigation(id=uuid.uuid4(), name="Case", owner_id=user.id)+ sketch = Sketch(+ id=uuid.uuid4(),+ title="Board",+ owner_id=user.id,+ investigation_id=investigation.id,+ )+ db_session.add_all([user, investigation, sketch])+ if roles:+ db_session.add(+ InvestigationUserRole(+ user_id=user.id, investigation_id=investigation.id, roles=list(roles)+ )+ )db_session.commit()headers = {"Authorization": f"Bearer {create_access_token({'sub': user.email})}"}- return client.post(- "/api/enrichers/some_enricher/launch", json=body, headers=headers- )+ return headers, str(sketch.id)+++def _launch(client, db_session, params=None, roles=(Role.OWNER,), sketch_id=None):+ headers, own_sketch_id = _seed_user(db_session, roles)+ body = {"node_ids": ["4:abc:1"], "sketch_id": sketch_id or own_sketch_id}+ if params is not None:+ body["params"] = params+ res = client.post("/api/enrichers/some_enricher/launch", json=body, headers=headers)+ return res, body["sketch_id"]def test_launch_forwards_params_as_task_kwargs(client, db_session, sent_task):- res = _launch(- client,- db_session,- {- "node_ids": ["4:abc:1"],- "sketch_id": str(uuid.uuid4()),- "params": {"api_key": "abc123"},- },- )+ res, _ = _launch(client, db_session, params={"api_key": "abc123"})assert res.status_code == 200assert res.json() == {"id": "task-123"}@@ -125,27 +149,66 @@ def test_launch_forwards_params_as_task_kwargs(client, db_session, sent_task):def test_launch_without_params_sends_an_empty_dict(client, db_session, sent_task):- res = _launch(- client,- db_session,- {"node_ids": ["4:abc:1"], "sketch_id": str(uuid.uuid4())},- )+ res, _ = _launch(client, db_session)assert res.status_code == 200assert sent_task["kwargs"] == {"params": {}}def test_launch_keeps_the_positional_args_unchanged(client, db_session, sent_task):- sketch_id = str(uuid.uuid4())-- _launch(- client,- db_session,- {"node_ids": ["4:abc:1"], "sketch_id": sketch_id, "params": {"k": "v"}},- )+ _, sketch_id = _launch(client, db_session, params={"k": "v"})enricher_name, entities, sent_sketch_id, owner_id = sent_task["args"]assert enricher_name == "some_enricher"assert entities == [{"address": "8.8.8.8"}]assert sent_sketch_id == sketch_idassert uuid.UUID(owner_id)+++def test_launch_succeeds_for_an_editor(client, db_session, sent_task):+ res, _ = _launch(client, db_session, roles=(Role.EDITOR,))++ assert res.status_code == 200+++def test_launch_is_forbidden_without_a_role_on_the_investigation(+ client, db_session, sent_task+):+ res, _ = _launch(client, db_session, roles=())++ assert res.status_code == 403+ assert res.json()["detail"] == "Forbidden"+ assert sent_task == {}+++def test_launch_is_forbidden_for_a_viewer(client, db_session, sent_task):+ res, _ = _launch(client, db_session, roles=(Role.VIEWER,))++ assert res.status_code == 403+ assert sent_task == {}+++def test_launch_is_forbidden_against_another_users_sketch(+ client, db_session, sent_task+):+ _, victim_sketch_id = _seed_user(db_session, (Role.OWNER,))++ res, _ = _launch(client, db_session, sketch_id=victim_sketch_id)++ assert res.status_code == 403+ assert sent_task == {}+++def test_launch_is_rejected_for_an_unknown_sketch(client, db_session, sent_task):+ res, _ = _launch(client, db_session, sketch_id=str(uuid.uuid4()))++ assert res.status_code == 404+ assert res.json()["detail"] == "Sketch not found"+ assert sent_task == {}+++def test_launch_is_rejected_for_a_malformed_sketch_id(client, db_session, sent_task):+ res, _ = _launch(client, db_session, sketch_id="not-a-uuid")++ assert res.status_code == 404+ assert sent_task == {}diff --git a/flowsint-core/src/flowsint_core/core/services/enricher_service.py b/flowsint-core/src/flowsint_core/core/services/enricher_service.pyindex 25196d5e..1613acf0 100644--- a/flowsint-core/src/flowsint_core/core/services/enricher_service.py+++ b/flowsint-core/src/flowsint_core/core/services/enricher_service.py@@ -9,8 +9,15 @@ from pydantic import ValidationErrorfrom sqlalchemy.orm import Sessionfrom ...templates.types import TemplateSecret, params_schema_from_secrets-from ..repositories import CustomTypeRepository, EnricherTemplateRepository+from ..models import Sketch+from ..repositories import (+ CustomTypeRepository,+ EnricherTemplateRepository,+ InvestigationRepository,+ SketchRepository,+)from .base import BaseService+from .exceptions import NotFoundErrordef template_params_schema(content: Any) -> List[Dict[str, Any]]:@@ -42,11 +49,34 @@ class EnricherService(BaseService):db: Session,custom_type_repo: CustomTypeRepository,enricher_template_repo: EnricherTemplateRepository,+ sketch_repo: SketchRepository,+ investigation_repo: InvestigationRepository,**kwargs: Any,):super().__init__(db, **kwargs)self._custom_type_repo = custom_type_repoself._enricher_template_repo = enricher_template_repo+ self._sketch_repo = sketch_repo+ self._investigation_repo = investigation_repo++ def get_sketch_for_launch(self, sketch_id: str, user_id: UUID) -> Sketch:+ """Resolve the target sketch, denying anyone without update rights on+ its investigation. Mirrors FlowService.get_sketch_for_launch: launching+ an enricher writes nodes into the sketch, so it is an update."""+ try:+ # The payload carries sketch_id as a free string. SketchRepository+ # binds it as a UUID, so parse here: a value that is not a UUID+ # names no sketch and has to be denied, not surfaced as a 500.+ parsed_id = UUID(sketch_id)+ except ValueError:+ raise NotFoundError("Sketch not found")++ sketch = self._sketch_repo.get_by_id(parsed_id)+ if not sketch:+ raise NotFoundError("Sketch not found")++ self._check_permission(user_id, sketch.investigation_id, ["update"])+ return sketch# enricher_registry is flowsint_enrichers' EnricherRegistry. That package# ships no py.typed marker, so naming the class would resolve to Any@@ -103,4 +133,6 @@ def create_enricher_service(db: Session) -> EnricherService:db=db,custom_type_repo=CustomTypeRepository(db),enricher_template_repo=EnricherTemplateRepository(db),+ sketch_repo=SketchRepository(db),+ investigation_repo=InvestigationRepository(db),)diff --git a/flowsint-core/tests/services/test_enricher_service.py b/flowsint-core/tests/services/test_enricher_service.pyindex b865c83f..830a3ab1 100644--- a/flowsint-core/tests/services/test_enricher_service.py+++ b/flowsint-core/tests/services/test_enricher_service.py@@ -5,11 +5,23 @@ from unittest.mock import MagicMockfrom flowsint_core.core.repositories import (CustomTypeRepository,EnricherTemplateRepository,+ InvestigationRepository,+ SketchRepository,)from flowsint_core.core.services.enricher_service import EnricherServicefrom tests.factories import EnricherTemplateFactory, ProfileFactory+def _service(db_session):+ return EnricherService(+ db=db_session,+ custom_type_repo=CustomTypeRepository(db_session),+ enricher_template_repo=EnricherTemplateRepository(db_session),+ sketch_repo=SketchRepository(db_session),+ investigation_repo=InvestigationRepository(db_session),+ )++def _content(secrets):return {"name": "example",@@ -28,17 +40,10 @@ class TestGetAllEnrichers:ProfileFactory._meta.sqlalchemy_session = db_sessionEnricherTemplateFactory._meta.sqlalchemy_session = db_session- def _make_service(self, db_session):- return EnricherService(- db=db_session,- custom_type_repo=CustomTypeRepository(db_session),- enricher_template_repo=EnricherTemplateRepository(db_session),- )-def _list(self, db_session, user):registry = MagicMock()registry.list.return_value = []- return self._make_service(db_session).get_all_enrichers(None, user.id, registry)+ return _service(db_session).get_all_enrichers(None, user.id, registry)def test_template_secrets_become_params_schema(self, db_session):self._setup(db_session)@@ -134,12 +139,7 @@ class TestTemplateVisibility:registry = MagicMock()registry.list.return_value = []registry.list_by_input_type.return_value = []- service = EnricherService(- db=db_session,- custom_type_repo=CustomTypeRepository(db_session),- enricher_template_repo=EnricherTemplateRepository(db_session),- )- return service.get_all_enrichers(category, user.id, registry)+ return _service(db_session).get_all_enrichers(category, user.id, registry)def test_another_owners_public_template_is_listed(self, db_session):self._setup(db_session)