Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
193 changes: 193 additions & 0 deletions medcat-trainer/webapp/api/api/extensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
"""
MedCAT Trainer extension API.

Stable contract used by enterprise / third-party plugins. The OSS app itself
emits these signals and consults the registries from a small number of
explicit sites (see :mod:`api.signals`, :mod:`api.views`, :mod:`api.permissions`).

Plugins are discovered via the ``mct.plugins`` Python entry-point group; each
entry point points at a Django ``AppConfig`` subclass. Plugin URL configs are
mounted at ``/api/ee/<app_label>/`` when the ``AppConfig`` sets
``is_mct_plugin = True``. See :mod:`core.settings` and :mod:`core.urls`.

The shape of this module is contract-tested by ``test_extensions.py`` and the
``contract-tests`` CI job; changes that break the documented shape are
breaking changes.
"""
from __future__ import annotations

from collections.abc import Callable, Iterable
from typing import Any, Optional

from django.dispatch import Signal

# ---------------------------------------------------------------------------
# Signals
# ---------------------------------------------------------------------------
#
# All signals MUST include at least the documented kwargs. Extra kwargs may
# be added over time but documented kwargs are stable.

#: Sent immediately before a document is submitted to training.
#: kwargs: ``project`` (ProjectAnnotateEntities), ``document`` (Document),
#: ``user`` (User or None).
pre_document_submit = Signal()

#: Sent immediately after a document is submitted to training.
#: kwargs: ``project``, ``document``, ``user``.
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess type information is consistent with the one above, but do we perhaps want to be explicit about it?

post_document_submit = Signal()

#: Sent after an :class:`AnnotatedEntity` row is created.
#: kwargs: ``annotation`` (AnnotatedEntity), ``project``, ``document``,
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here as well, type information for project and document isn't included.

#: ``user`` (or None).
annotation_created = Signal()

#: Sent after an :class:`AnnotatedEntity` row is updated.
#: kwargs: ``annotation``, ``project``, ``document``, ``user``.
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, typing not included

annotation_updated = Signal()

#: Sent after an :class:`AnnotatedEntity` row is deleted.
#: kwargs: ``annotation`` (instance prior to delete), ``project``, ``document``.
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typing not included

annotation_deleted = Signal()

#: Sent after a :class:`ProjectGroup` row is created.
#: kwargs: ``project_group``.
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typing not included

project_group_created = Signal()

#: Sent after a :class:`ProjectGroup` row is updated.
#: kwargs: ``project_group``.
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typing not included

project_group_updated = Signal()

#: Sent after the OIDC user resolver returns a Django user.
#: kwargs: ``user``, ``id_token`` (dict), ``created`` (bool).
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typing not included (for first 2)

user_oidc_resolved = Signal()


# ---------------------------------------------------------------------------
# Permission hook registry
# ---------------------------------------------------------------------------
#
# Permission hooks are grant-only: a hook returning ``True`` grants the
# permission; ``None`` or ``False`` abstains and the OSS default decision is
# used. Hooks MUST NOT be used to deny access that the OSS code would
# otherwise grant.

PermissionHook = Callable[..., Optional[bool]]
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Theser have an unknown argument signature. Is there a reason not to force args User and ProjectAnnotateEntites? That's what's being passed in api.permissions.is_project_admin, right? Or is that just because the method it's used in doesn't have typing? Perhaps at the very least define as 2 arguments as [Any, Any]?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

good point - have typed and limited to the two args used

_permission_hooks: dict[str, list[PermissionHook]] = {}


def register_permission_hook(name: str, fn: PermissionHook) -> None:
"""Register a grant-only permission hook for ``name``.

Hooks are called in registration order until one returns ``True``.
Any value other than ``True`` (including ``None`` and ``False``) abstains.
"""
if not callable(fn):
raise TypeError("permission hook must be callable")
_permission_hooks.setdefault(name, []).append(fn)


def get_permission_hooks(name: str) -> Iterable[PermissionHook]:
return tuple(_permission_hooks.get(name, ()))


def clear_permission_hooks(name: Optional[str] = None) -> None:
"""Clear hooks. Intended for tests."""
if name is None:
_permission_hooks.clear()
else:
_permission_hooks.pop(name, None)


# ---------------------------------------------------------------------------
# Menu / route / feature registries (frontend bootstrap)
# ---------------------------------------------------------------------------

_menu_extensions: list[dict[str, Any]] = []
_plugin_routes: list[dict[str, Any]] = []
_features: set[str] = set()


def register_menu_extension(item: dict[str, Any]) -> None:
"""Register a top-nav menu item exposed via ``GET /api/bootstrap/``.

``item`` MUST contain ``id`` (str) and ``label`` (str). It SHOULD
contain ``route`` (str) or ``href`` (str). Additional keys pass through
verbatim to the frontend.
"""
if not isinstance(item, dict):
raise TypeError("menu extension item must be a dict")
if "id" not in item or "label" not in item:
raise ValueError("menu extension item requires 'id' and 'label'")
_menu_extensions.append(dict(item))
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suppose this is meant to pass a copy of the dict so changes to it somewhere else won't affect the registered extension. However, the shallow copy could still leave dict values (which could only be additional keys/values as per spec) vulnerable to outside changes.
Though probably not a massive issue, just something to keep in mind. If it's an issue copy.deepcopy could be used to avoid this.



def get_menu_extensions() -> list[dict[str, Any]]:
return [dict(it) for it in _menu_extensions]
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same note here regarding shallow copy

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done



def register_route(route: dict[str, Any]) -> None:
"""Register a frontend route descriptor exposed via ``GET /api/bootstrap/``.

``route`` MUST contain ``path`` (str) and ``component`` (str — module
specifier or registered component name resolved by the frontend).
"""
if not isinstance(route, dict):
raise TypeError("route must be a dict")
if "path" not in route or "component" not in route:
raise ValueError("route requires 'path' and 'component'")
_plugin_routes.append(dict(route))
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same note here regarding shallow copy

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done



def get_routes() -> list[dict[str, Any]]:
return [dict(r) for r in _plugin_routes]
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same note here regarding shallow copy



def register_feature(name: str) -> None:
"""Declare a license-gated feature as enabled."""
if not isinstance(name, str) or not name:
raise ValueError("feature name must be a non-empty string")
_features.add(name)


def get_features() -> list[str]:
return sorted(_features)


def clear_registries() -> None:
"""Reset menu / route / feature registries. Intended for tests."""
_menu_extensions.clear()
_plugin_routes.clear()
_features.clear()


# ---------------------------------------------------------------------------
# Plugin discovery state
# ---------------------------------------------------------------------------

#: Populated by :mod:`core.settings` at import time with the dotted ``AppConfig``
#: paths of installed MCT plugins. Read-only at runtime.
discovered_plugin_apps: list[str] = []


__all__ = [
"pre_document_submit",
"post_document_submit",
"annotation_created",
"annotation_updated",
"annotation_deleted",
"project_group_created",
"project_group_updated",
"user_oidc_resolved",
"register_permission_hook",
"get_permission_hooks",
"clear_permission_hooks",
"register_menu_extension",
"get_menu_extensions",
"register_route",
"get_routes",
"register_feature",
"get_features",
"clear_registries",
"discovered_plugin_apps",
]
10 changes: 10 additions & 0 deletions medcat-trainer/webapp/api/api/oidc_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from django.contrib.auth import get_user_model
import secrets

from .extensions import user_oidc_resolved


def get_user_by_email(request, id_token):
"""
Resolve or create a Django user from OIDC claims.
Expand Down Expand Up @@ -41,4 +44,11 @@ def get_user_by_email(request, id_token):
user.is_staff = is_staff

user.save()

user_oidc_resolved.send(
sender=User,
user=user,
id_token=id_token,
created=created,
)
return user
18 changes: 13 additions & 5 deletions medcat-trainer/webapp/api/api/permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,19 +18,27 @@ def is_project_admin(user, project):
"""
Check if a user is an admin of a project.
A user is a project admin if:
1. They are a member of the project, OR
2. They are an administrator of the project's group (if the project has a group)
3. They are a superuser/staff
1. They are a superuser/staff, OR
2. They are a member of the project, OR
3. They are an administrator of the project's group (if the project has a group), OR
4. A registered ``is_project_admin`` permission hook grants access.

Hooks are grant-only (see :mod:`api.extensions`): they may extend the set
of users considered admins (e.g. via OIDC group claims in an enterprise
plugin) but never narrow it.
"""
if user.is_superuser or user.is_staff:
return True

# Check if user is a member of the project
if project.members.filter(id=user.id).exists():
return True

# Check if user is an administrator of the project's group
if project.group and project.group.administrators.filter(id=user.id).exists():
return True

from .extensions import get_permission_hooks
for hook in get_permission_hooks('is_project_admin'):
if hook(user, project) is True:
return True

return False
54 changes: 52 additions & 2 deletions medcat-trainer/webapp/api/api/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,24 @@
from django.dispatch import receiver

from api.data_utils import dataset_from_file, delete_orphan_docs, upload_projects_export
from api.models import Dataset, ExportedProject, ModelPack, ProjectFields, ProjectAnnotateEntitiesFields, MetaTask, \
ProjectAnnotateEntities
from api.extensions import (
annotation_created,
annotation_deleted,
annotation_updated,
project_group_created,
project_group_updated,
)
from api.models import (
AnnotatedEntity,
Dataset,
ExportedProject,
MetaTask,
ModelPack,
ProjectAnnotateEntities,
ProjectAnnotateEntitiesFields,
ProjectFields,
ProjectGroup,
)
from core.settings import MEDIA_ROOT


Expand Down Expand Up @@ -95,3 +111,37 @@ def project_tasks_changed(sender, instance, action, **kwargs):


m2m_changed.connect(project_tasks_changed, sender=ProjectAnnotateEntitiesFields.tasks.through)


# ---------------------------------------------------------------------------
# Bridges from Django ORM signals to api.extensions semantic signals.
# These are part of the stable plugin contract (api/extensions.py).
# Keep these handlers cheap and side-effect-free.
# ---------------------------------------------------------------------------

@receiver(post_save, sender=AnnotatedEntity)
def _emit_annotation_saved(sender, instance, created, **kwargs):
sig = annotation_created if created else annotation_updated
sig.send(
sender=AnnotatedEntity,
annotation=instance,
project=getattr(instance, 'project', None),
document=getattr(instance, 'document', None),
user=getattr(instance, 'user', None),
)


@receiver(post_delete, sender=AnnotatedEntity)
def _emit_annotation_deleted(sender, instance, **kwargs):
annotation_deleted.send(
sender=AnnotatedEntity,
annotation=instance,
project=getattr(instance, 'project', None),
document=getattr(instance, 'document', None),
)


@receiver(post_save, sender=ProjectGroup)
def _emit_project_group_saved(sender, instance, created, **kwargs):
sig = project_group_created if created else project_group_updated
sig.send(sender=ProjectGroup, project_group=instance)
41 changes: 41 additions & 0 deletions medcat-trainer/webapp/api/api/tests/fixtures/bootstrap_schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://cogstack.org/medcat-trainer/bootstrap.json",
"title": "MedCAT Trainer bootstrap payload",
"type": "object",
"additionalProperties": false,
"required": ["features", "menu_extensions", "routes"],
"properties": {
"features": {
"type": "array",
"items": { "type": "string", "minLength": 1 }
},
"menu_extensions": {
"type": "array",
"items": {
"type": "object",
"required": ["id", "label"],
"properties": {
"id": { "type": "string", "minLength": 1 },
"label": { "type": "string", "minLength": 1 },
"route": { "type": "string" },
"href": { "type": "string" }
},
"additionalProperties": true
}
},
"routes": {
"type": "array",
"items": {
"type": "object",
"required": ["path", "component"],
"properties": {
"path": { "type": "string", "minLength": 1 },
"component": { "type": "string", "minLength": 1 },
"name": { "type": "string" }
},
"additionalProperties": true
}
}
}
}
Loading