simple-module-sharing 0.0.46__tar.gz → 0.0.48__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/PKG-INFO +7 -7
  2. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/README.md +2 -2
  3. simple_module_sharing-0.0.48/package.json +7 -0
  4. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/pyproject.toml +5 -5
  5. simple_module_sharing-0.0.48/sharing/contracts/__init__.py +21 -0
  6. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/contracts/schemas.py +22 -2
  7. simple_module_sharing-0.0.48/sharing/contracts/subjects.py +84 -0
  8. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/core/audience.py +12 -0
  9. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/core/constants.py +30 -7
  10. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/core/policy.py +10 -3
  11. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/core/service.py +65 -14
  12. simple_module_sharing-0.0.48/sharing/core/subjects.py +139 -0
  13. simple_module_sharing-0.0.48/sharing/locales/de.json +62 -0
  14. simple_module_sharing-0.0.48/sharing/locales/en.json +62 -0
  15. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/module.py +22 -32
  16. simple_module_sharing-0.0.48/sharing/pages/api.generated.ts +355 -0
  17. simple_module_sharing-0.0.48/sharing/pages/i18n.generated.ts +122 -0
  18. simple_module_sharing-0.0.48/sharing/ui/components/ShareDialog.tsx +208 -0
  19. simple_module_sharing-0.0.48/sharing/ui/hooks/useShares.ts +186 -0
  20. simple_module_sharing-0.0.48/sharing/ui/index.ts +2 -0
  21. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/web/deps.py +5 -1
  22. simple_module_sharing-0.0.48/sharing/web/endpoints/api.py +116 -0
  23. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/web/endpoints/views.py +10 -5
  24. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/web/present.py +20 -2
  25. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/tests/_sharing_support.py +24 -2
  26. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/tests/core/cleanup/test_sharing_tenant_cleanup.py +1 -1
  27. simple_module_sharing-0.0.48/tests/core/service/test_role_candidates_i18n.py +81 -0
  28. simple_module_sharing-0.0.48/tests/core/service/test_sharing_candidates.py +138 -0
  29. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/tests/core/service/test_sharing_custom_roles.py +7 -19
  30. simple_module_sharing-0.0.48/tests/core/service/test_sharing_subjects.py +55 -0
  31. simple_module_sharing-0.0.48/tests/core/service/test_subject_policy.py +157 -0
  32. simple_module_sharing-0.0.48/tests/core/service/test_subject_providers.py +147 -0
  33. simple_module_sharing-0.0.48/tests/web/endpoints/test_sharing_candidates.py +181 -0
  34. simple_module_sharing-0.0.48/tests/web/endpoints/test_sharing_candidates_long_email.py +54 -0
  35. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/tests/web/endpoints/test_sharing_http.py +37 -0
  36. simple_module_sharing-0.0.48/tests/web/endpoints/test_subject_providers.py +180 -0
  37. simple_module_sharing-0.0.48/tests-js/ShareDialog.test.tsx +107 -0
  38. simple_module_sharing-0.0.48/tests-js/ShareDialog_subjects.test.tsx +65 -0
  39. simple_module_sharing-0.0.48/tests-js/ShareDialog_translations.test.tsx +48 -0
  40. simple_module_sharing-0.0.48/tests-js/useShares.test.tsx +172 -0
  41. simple_module_sharing-0.0.48/tests-js/useShares_subjects.test.tsx +59 -0
  42. simple_module_sharing-0.0.46/package.json +0 -18
  43. simple_module_sharing-0.0.46/sharing/contracts/__init__.py +0 -6
  44. simple_module_sharing-0.0.46/sharing/core/services.py +0 -22
  45. simple_module_sharing-0.0.46/sharing/core/settings.py +0 -17
  46. simple_module_sharing-0.0.46/sharing/locales/de.json +0 -34
  47. simple_module_sharing-0.0.46/sharing/locales/en.json +0 -34
  48. simple_module_sharing-0.0.46/sharing/web/endpoints/api.py +0 -69
  49. simple_module_sharing-0.0.46/tests/conftest.py +0 -4
  50. simple_module_sharing-0.0.46/tsconfig.json +0 -10
  51. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/.gitignore +0 -0
  52. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/LICENSE +0 -0
  53. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/__init__.py +0 -0
  54. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/contracts/cleanup.py +0 -0
  55. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/core/__init__.py +0 -0
  56. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/core/tenant_cleanup.py +0 -0
  57. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/core/user_cleanup.py +0 -0
  58. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/models.py +0 -0
  59. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/pages/Admin.tsx +0 -0
  60. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/py.typed +0 -0
  61. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/ui/components/ShareTable.tsx +0 -0
  62. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/ui/types.ts +0 -0
  63. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/web/__init__.py +0 -0
  64. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/sharing/web/endpoints/__init__.py +0 -0
  65. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/tests/core/audience/test_sharing_tenant_audience.py +0 -0
  66. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/tests/core/cleanup/test_sharing_resource_cleanup.py +0 -0
  67. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/tests/core/service/test_sharing_service.py +0 -0
  68. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/tests-js/sharing_Admin.test.tsx +0 -0
  69. {simple_module_sharing-0.0.46 → simple_module_sharing-0.0.48}/tests-js/sharing_Admin_errors.test.tsx +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: simple_module_sharing
3
- Version: 0.0.46
3
+ Version: 0.0.48
4
4
  Summary: Generic resource shares (owner / shared-with-user) for simple_module resource-scoped access
5
5
  Project-URL: Homepage, https://github.com/antosubash/simple_module_python
6
6
  Project-URL: Repository, https://github.com/antosubash/simple_module_python
@@ -11,17 +11,17 @@ License-Expression: MIT
11
11
  License-File: LICENSE
12
12
  Keywords: access-control,permissions,sharing,simple-module
13
13
  Requires-Python: >=3.12
14
- Requires-Dist: simple-module-core==0.0.46
15
- Requires-Dist: simple-module-db==0.0.46
16
- Requires-Dist: simple-module-hosting==0.0.46
17
- Requires-Dist: simple-module-inertia==0.0.46
14
+ Requires-Dist: simple-module-core==0.0.48
15
+ Requires-Dist: simple-module-db==0.0.48
16
+ Requires-Dist: simple-module-hosting==0.0.48
17
+ Requires-Dist: simple-module-inertia==0.0.48
18
18
  Description-Content-Type: text/markdown
19
19
 
20
20
  # simple_module_sharing
21
21
 
22
22
  A generic share table for
23
23
  [simple_module](https://github.com/antosubash/simple_module_python) apps:
24
- give one user `view` or `edit` access to one row of another module, with an
24
+ give a user, tenant role or registered subject `view` or `edit` access to one row of another module, with an
25
25
  optional expiry, without that module shipping a bespoke share model. It plugs
26
26
  into the framework's resource-scoped access (`ResourcePolicy`,
27
27
  `OwnedResourcePolicy`, `RequiresResource`), so detail routes, lists and counts
@@ -66,7 +66,7 @@ def register_resource_types(self, registry):
66
66
  | `GET /admin/sharing/` | Admin list of every share in the tenant | `sharing.view` |
67
67
 
68
68
  Shares are tenant-scoped, expired shares never match, and grantees are
69
- validated through the user directory. See `docs/modules/sharing.md`.
69
+ validated through registered subject providers; user recipients use the user directory. See `docs/modules/sharing.md`.
70
70
 
71
71
  ## License
72
72
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  A generic share table for
4
4
  [simple_module](https://github.com/antosubash/simple_module_python) apps:
5
- give one user `view` or `edit` access to one row of another module, with an
5
+ give a user, tenant role or registered subject `view` or `edit` access to one row of another module, with an
6
6
  optional expiry, without that module shipping a bespoke share model. It plugs
7
7
  into the framework's resource-scoped access (`ResourcePolicy`,
8
8
  `OwnedResourcePolicy`, `RequiresResource`), so detail routes, lists and counts
@@ -47,7 +47,7 @@ def register_resource_types(self, registry):
47
47
  | `GET /admin/sharing/` | Admin list of every share in the tenant | `sharing.view` |
48
48
 
49
49
  Shares are tenant-scoped, expired shares never match, and grantees are
50
- validated through the user directory. See `docs/modules/sharing.md`.
50
+ validated through registered subject providers; user recipients use the user directory. See `docs/modules/sharing.md`.
51
51
 
52
52
  ## License
53
53
 
@@ -0,0 +1,7 @@
1
+ {
2
+ "name": "@simple-module-py/sharing",
3
+ "private": true,
4
+ "dependencies": {
5
+ "lucide-react": "^1.43.0"
6
+ }
7
+ }
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "simple_module_sharing"
3
- version = "0.0.46"
3
+ version = "0.0.48"
4
4
  description = "Generic resource shares (owner / shared-with-user) for simple_module resource-scoped access"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -9,10 +9,10 @@ requires-python = ">=3.12"
9
9
  authors = [{ name = "Anto Subash", email = "antosubash@live.com" }]
10
10
  keywords = ["simple-module", "sharing", "permissions", "access-control"]
11
11
  dependencies = [
12
- "simple_module_core==0.0.46",
13
- "simple_module_db==0.0.46",
14
- "simple_module_hosting==0.0.46",
15
- "simple_module_inertia==0.0.46",
12
+ "simple_module_core==0.0.48",
13
+ "simple_module_db==0.0.48",
14
+ "simple_module_hosting==0.0.48",
15
+ "simple_module_inertia==0.0.48",
16
16
  ]
17
17
 
18
18
  [project.entry-points.simple_module]
@@ -0,0 +1,21 @@
1
+ """Sharing contracts — public interface for other modules."""
2
+
3
+ from sharing.contracts.cleanup import forget_resource
4
+ from sharing.contracts.schemas import ShareCandidate, ShareGrant, ShareOut
5
+ from sharing.contracts.subjects import (
6
+ SubjectContext,
7
+ SubjectProvider,
8
+ SubjectRegistry,
9
+ get_subject_registry,
10
+ )
11
+
12
+ __all__ = [
13
+ "ShareCandidate",
14
+ "ShareGrant",
15
+ "ShareOut",
16
+ "SubjectContext",
17
+ "SubjectProvider",
18
+ "SubjectRegistry",
19
+ "forget_resource",
20
+ "get_subject_registry",
21
+ ]
@@ -8,19 +8,39 @@ from datetime import datetime
8
8
  from simple_module_core.resources import ACTION_VIEW
9
9
  from sqlmodel import Field, SQLModel
10
10
 
11
- from sharing.core.constants import RESOURCE_ID_MAX, RESOURCE_TYPE_MAX, ROLE_MAX, SUBJECT_ID_MAX
11
+ from sharing.core.constants import (
12
+ RESOURCE_ID_MAX,
13
+ RESOURCE_TYPE_MAX,
14
+ ROLE_MAX,
15
+ SUBJECT_ID_MAX,
16
+ SUBJECT_TYPE_MAX,
17
+ SUBJECT_USER,
18
+ )
12
19
 
13
20
 
14
21
  class ShareGrant(SQLModel):
15
- """Grant (or update) one user's access to one resource."""
22
+ """Grant (or update) one subject's access to one resource."""
16
23
 
17
24
  resource_type: str = Field(min_length=1, max_length=RESOURCE_TYPE_MAX)
18
25
  resource_id: str = Field(min_length=1, max_length=RESOURCE_ID_MAX)
19
26
  subject_id: str = Field(min_length=1, max_length=SUBJECT_ID_MAX)
27
+ subject_type: str = Field(default=SUBJECT_USER, min_length=1, max_length=SUBJECT_TYPE_MAX)
20
28
  role: str = Field(default=ACTION_VIEW, max_length=ROLE_MAX)
21
29
  expires_at: datetime | None = None
22
30
 
23
31
 
32
+ class ShareCandidate(SQLModel):
33
+ id: str
34
+ display_name: str
35
+ email: str = ""
36
+ subject_type: str = SUBJECT_USER
37
+
38
+
39
+ class ShareSubjectType(SQLModel):
40
+ subject_type: str
41
+ label_key: str
42
+
43
+
24
44
  class ShareOut(SQLModel):
25
45
  id: uuid.UUID
26
46
  resource_type: str
@@ -0,0 +1,84 @@
1
+ """Subject provider contracts; membership predicates are synchronous SQL builders."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Awaitable, Callable, Collection, Mapping
7
+ from dataclasses import dataclass
8
+ from typing import Any
9
+
10
+ from simple_module_core.principals import PRINCIPALS_KEY, PrincipalRegistry
11
+ from simple_module_core.resources import ResourcePrincipal
12
+ from simple_module_core.user_directory import UserDirectory
13
+ from sqlalchemy.ext.asyncio import AsyncSession
14
+
15
+ from sharing.contracts.schemas import ShareCandidate
16
+ from sharing.core.audience import Audience, OpenAudience
17
+
18
+ SUBJECTS_KEY = "sharing.subjects"
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class SubjectContext:
23
+ db: AsyncSession
24
+ directory: UserDirectory
25
+ audience: Audience | OpenAudience
26
+ principal: ResourcePrincipal
27
+ translate: Callable[[str], str] | None = None
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class SubjectProvider:
32
+ """A trusted module's subject implementation.
33
+
34
+ Validation/search/labels must enforce visibility in the active tenant and
35
+ mask private data. ``labels`` is batched; ``membership`` builds SQL without
36
+ I/O (use a subquery for live memberships), never per-resource lookups.
37
+ """
38
+
39
+ name: str
40
+ label_key: str
41
+ validate: Callable[[SubjectContext, str], Awaitable[str | None]]
42
+ candidates: Callable[[SubjectContext, str, str], Awaitable[list[ShareCandidate]]]
43
+ labels: Callable[[SubjectContext, Collection[str]], Awaitable[Mapping[str, str]]]
44
+ membership: Callable[[ResourcePrincipal, Any], Any]
45
+
46
+
47
+ class SubjectRegistry:
48
+ """Host/worker-local providers; duplicate names fail at registration."""
49
+
50
+ def __init__(self) -> None:
51
+ self._providers: dict[str, SubjectProvider] = {}
52
+
53
+ def register(self, provider: SubjectProvider) -> None:
54
+ if not re.fullmatch(r"[a-z][a-z0-9_]{0,15}", provider.name):
55
+ raise ValueError("Subject type must be a lowercase identifier of at most 16 characters")
56
+ if provider.name in self._providers:
57
+ raise ValueError(f"Subject type {provider.name!r} is registered twice")
58
+ self._providers[provider.name] = provider
59
+
60
+ def get(self, name: str) -> SubjectProvider | None:
61
+ return self._providers.get(name)
62
+
63
+ def all(self) -> list[SubjectProvider]:
64
+ return list(self._providers.values())
65
+
66
+
67
+ def get_subject_registry(host: Any) -> SubjectRegistry:
68
+ """The same registry during ``register_principal_builder`` and HTTP requests.
69
+
70
+ A custom module depends on Sharing, then registers against the supplied
71
+ PrincipalRegistry in its principal-builder hook. No process-global state.
72
+ """
73
+ if isinstance(host, PrincipalRegistry):
74
+ builder = host
75
+ else:
76
+ factory = host.state.sm.db.session_factory
77
+ builder = factory.kw.get("info", {}).get(PRINCIPALS_KEY)
78
+ if builder is None:
79
+ raise RuntimeError("No principal registry bound to this host")
80
+ if SUBJECTS_KEY not in builder.resource_context:
81
+ from sharing.core.subjects import default_subject_registry
82
+
83
+ builder.resource_context[SUBJECTS_KEY] = default_subject_registry()
84
+ return builder.resource_context[SUBJECTS_KEY]
@@ -26,6 +26,15 @@ class Audience:
26
26
  self.app = app
27
27
  self.db = db
28
28
 
29
+ async def search_ids(self) -> set[str] | None:
30
+ """All active-tenant members, or no restriction on a single-tenant host."""
31
+ if tenancy_mode(self.app) is not TenancyMode.MULTI:
32
+ return None
33
+ tenant_id = current_tenant_id.get()
34
+ if tenant_id is None:
35
+ return set()
36
+ return await tenant_member_ids(self.app, self.db, tenant_id, None) or set()
37
+
29
38
  async def visible(self, user_ids: Collection[str]) -> set[str]:
30
39
  wanted = {uid for uid in user_ids if uid}
31
40
  if not wanted or tenancy_mode(self.app) is not TenancyMode.MULTI:
@@ -40,5 +49,8 @@ class Audience:
40
49
  class OpenAudience:
41
50
  """Everyone is visible (single-tenant use, or tests without an app)."""
42
51
 
52
+ async def search_ids(self) -> set[str] | None:
53
+ return None
54
+
43
55
  async def visible(self, user_ids: Collection[str]) -> set[str]:
44
56
  return {uid for uid in user_ids if uid}
@@ -4,6 +4,8 @@ from __future__ import annotations
4
4
 
5
5
  from typing import Final
6
6
 
7
+ from simple_module_core.deprecation import deprecate
8
+ from simple_module_core.permissions import PermissionCatalogue
7
9
  from simple_module_core.resources import ACTION_EDIT, ACTION_VIEW
8
10
 
9
11
  MODULE_NAME: Final = "Sharing"
@@ -11,17 +13,37 @@ MODULE_PACKAGE: Final = "sharing"
11
13
  LOCALE_NAMESPACE: Final = "sharing"
12
14
 
13
15
  PERM_GROUP: Final = "Sharing"
14
- PERM_SHARE: Final = "sharing.share"
15
- """Use the grant/revoke API at all; the resource's own policy still decides."""
16
- PERM_VIEW: Final = "sharing.view"
17
- """See every share in the tenant (the admin page)."""
18
- PERM_MANAGE: Final = "sharing.manage"
19
- """Revoke any share in the tenant."""
16
+
17
+
18
+ class Permissions(PermissionCatalogue, group=PERM_GROUP, label_key="sharing.permission_group"):
19
+ # Use the grant/revoke API; the resource's policy still decides.
20
+ SHARE = "sharing.share"
21
+ # See every share in the tenant (the admin page).
22
+ VIEW = "sharing.view"
23
+ # Revoke any share in the tenant.
24
+ MANAGE = "sharing.manage"
25
+ # Discover directory users outside multi-tenant mode.
26
+ DIRECTORY_SEARCH = "sharing.directory_search"
27
+
28
+
29
+ deprecate(
30
+ "sharing PERM_* constants",
31
+ remove_in="0.0.50",
32
+ use="sharing.core.constants.Permissions",
33
+ )
34
+ PERM_SHARE: Final = Permissions.SHARE
35
+ PERM_MANAGE: Final = Permissions.MANAGE
36
+
20
37
  USER_ROLE: Final = "user"
21
38
 
22
39
  PAGE_ADMIN: Final = "Sharing/Admin"
23
40
 
24
41
  API_PREFIX: Final = "/api/sharing"
42
+ CANDIDATES_URL: Final = f"{API_PREFIX}/candidates"
43
+ CANDIDATES_RATE: Final = "60/minute"
44
+ CANDIDATES_DAILY_RATE: Final = "500/day"
45
+ CANDIDATES_MIN_QUERY: Final = 3
46
+ CANDIDATES_MAX: Final = 20
25
47
  VIEW_PREFIX: Final = "/admin/sharing"
26
48
  # Trailing slash: the index route is registered at "/" under the prefix.
27
49
  ADMIN_URL: Final = f"{VIEW_PREFIX}/"
@@ -48,7 +70,8 @@ SUBJECT_ID_MAX: Final = 255
48
70
  ROLE_MAX: Final = 32
49
71
 
50
72
  SUBJECT_USER: Final = "user"
51
- """The only subject kind so far; the column leaves room for groups or tenants."""
73
+ SUBJECT_TENANT_ROLE: Final = "tenant_role"
74
+ ERR_UNKNOWN_SUBJECT: Final = "Unknown subject type"
52
75
 
53
76
  # A role is the action it grants plus everything it implies.
54
77
  ROLE_IMPLIES: Final[dict[str, tuple[str, ...]]] = {
@@ -22,7 +22,8 @@ from simple_module_core.resources import ResourcePrincipal
22
22
  from sqlalchemy import String, cast, func, inspect, or_
23
23
  from sqlmodel import exists, select
24
24
 
25
- from sharing.core.constants import ROLE_IMPLIES, SUBJECT_USER
25
+ from sharing.core.constants import ROLE_IMPLIES
26
+ from sharing.core.subjects import subjects_for
26
27
  from sharing.models import ResourceShare
27
28
 
28
29
 
@@ -94,12 +95,18 @@ def share_exists_for(
94
95
  granting_roles = roles_granting(action, roles=roles)
95
96
  if not granting_roles or principal.user_id is None:
96
97
  return None
98
+ subjects = [
99
+ (ResourceShare.subject_type == provider.name)
100
+ & provider.membership(principal, ResourceShare.subject_id)
101
+ for provider in subjects_for(principal).all()
102
+ ]
103
+ if not subjects:
104
+ return None
97
105
  return exists(
98
106
  select(ResourceShare.id).where(
99
107
  ResourceShare.resource_type == resource_type,
100
108
  ResourceShare.resource_id == key,
101
- ResourceShare.subject_type == SUBJECT_USER,
102
- ResourceShare.subject_id == principal.user_id,
109
+ or_(*subjects),
103
110
  ResourceShare.role.in_(granting_roles),
104
111
  active_share_clause(),
105
112
  )
@@ -2,13 +2,14 @@
2
2
 
3
3
  Every grant is checked three ways: the resource type is registered, the
4
4
  granter passes the owning module's policy for ``share`` on that row, and the
5
- grantee is someone the user directory knows. Rows are tenant-scoped by
5
+ subject is validated by its registered provider. Rows are tenant-scoped by
6
6
  ``MultiTenantMixin``; revoking hard-deletes.
7
7
  """
8
8
 
9
9
  from __future__ import annotations
10
10
 
11
11
  import uuid
12
+ from collections.abc import Callable
12
13
  from typing import Any
13
14
 
14
15
  from simple_module_core.datetimes import aware as _aware
@@ -25,20 +26,25 @@ from sqlalchemy.exc import IntegrityError
25
26
  from sqlalchemy.ext.asyncio import AsyncSession
26
27
  from sqlmodel import select
27
28
 
28
- from sharing.contracts.schemas import ShareGrant
29
+ from sharing.contracts.schemas import ShareCandidate, ShareGrant
30
+ from sharing.contracts.subjects import SubjectContext, SubjectRegistry
29
31
  from sharing.core.audience import Audience, OpenAudience
30
32
  from sharing.core.constants import (
33
+ CANDIDATES_MAX,
34
+ CANDIDATES_MIN_QUERY,
31
35
  ERR_BAD_ROLE,
32
36
  ERR_EXPIRED,
33
37
  ERR_FORBIDDEN,
34
38
  ERR_NOT_FOUND,
35
39
  ERR_SELF,
36
40
  ERR_UNKNOWN_GRANTEE,
41
+ ERR_UNKNOWN_SUBJECT,
37
42
  ERR_UNKNOWN_TYPE,
38
- PERM_MANAGE,
39
43
  SUBJECT_USER,
44
+ Permissions,
40
45
  )
41
46
  from sharing.core.policy import resolve_roles, row_id
47
+ from sharing.core.subjects import subjects_for
42
48
  from sharing.models import ResourceShare
43
49
 
44
50
 
@@ -58,11 +64,28 @@ class SharingService:
58
64
  registry: ResourceTypeRegistry,
59
65
  directory: UserDirectory,
60
66
  audience: Audience | OpenAudience | None = None,
67
+ subjects: SubjectRegistry | None = None,
68
+ *,
69
+ translate: Callable[[str], str] | None = None,
61
70
  ) -> None:
62
71
  self.db = db
63
72
  self.registry = registry
64
73
  self.directory = directory
65
74
  self.audience = audience or OpenAudience()
75
+ self.subjects = subjects
76
+ self.translate = translate
77
+
78
+ def context(self, principal: ResourcePrincipal) -> SubjectContext:
79
+ return SubjectContext(self.db, self.directory, self.audience, principal, self.translate)
80
+
81
+ def subject_registry(self, principal: ResourcePrincipal) -> SubjectRegistry:
82
+ return self.subjects if self.subjects is not None else subjects_for(principal)
83
+
84
+ def _subject(self, principal: ResourcePrincipal, name: str):
85
+ provider = self.subject_registry(principal).get(name)
86
+ if provider is None:
87
+ raise SharingError(422, ERR_UNKNOWN_SUBJECT)
88
+ return provider
66
89
 
67
90
  def _type(self, name: str) -> ResourceType:
68
91
  resource_type = self.registry.get(name)
@@ -94,20 +117,20 @@ class SharingService:
94
117
  if data.expires_at is not None and _aware(data.expires_at) <= utcnow():
95
118
  raise SharingError(422, ERR_EXPIRED)
96
119
  row = await self._authorize(principal, resource_type, data.resource_id)
97
- grantee = (await self.directory.get_many(self.db, [data.subject_id])).get(data.subject_id)
98
- # One error for "no such user" and "not in your tenant": no enumeration.
99
- if grantee is None or grantee.id not in await self.audience.visible([grantee.id]):
120
+ provider = self._subject(principal, data.subject_type)
121
+ subject_id = await provider.validate(self.context(principal), data.subject_id)
122
+ if subject_id is None:
100
123
  raise SharingError(422, ERR_UNKNOWN_GRANTEE)
101
- if grantee.id == principal.user_id:
124
+ if data.subject_type == SUBJECT_USER and subject_id == principal.user_id:
102
125
  raise SharingError(422, ERR_SELF)
103
126
  resource_id = row_id(row)
104
- share = await self._existing(data.resource_type, resource_id, grantee.id)
127
+ share = await self._existing(data.resource_type, resource_id, subject_id, data.subject_type)
105
128
  if share is None:
106
129
  share = ResourceShare(
107
130
  resource_type=data.resource_type,
108
131
  resource_id=resource_id,
109
- subject_type=SUBJECT_USER,
110
- subject_id=grantee.id,
132
+ subject_type=data.subject_type,
133
+ subject_id=subject_id,
111
134
  role=data.role,
112
135
  granted_by=principal.user_id or "",
113
136
  expires_at=data.expires_at,
@@ -118,7 +141,9 @@ class SharingService:
118
141
  await self.db.flush()
119
142
  except IntegrityError:
120
143
  # Another grant may have won the unique-key race.
121
- share = await self._existing(data.resource_type, resource_id, grantee.id)
144
+ share = await self._existing(
145
+ data.resource_type, resource_id, subject_id, data.subject_type
146
+ )
122
147
  if share is None:
123
148
  raise
124
149
  share.role = data.role
@@ -127,11 +152,13 @@ class SharingService:
127
152
  await self.db.flush()
128
153
  return share
129
154
 
130
- async def _existing(self, rtype: str, rid: str, subject_id: str) -> ResourceShare | None:
155
+ async def _existing(
156
+ self, rtype: str, rid: str, subject_id: str, subject_type: str = SUBJECT_USER
157
+ ) -> ResourceShare | None:
131
158
  stmt = select(ResourceShare).where(
132
159
  ResourceShare.resource_type == rtype,
133
160
  ResourceShare.resource_id == rid,
134
- ResourceShare.subject_type == SUBJECT_USER,
161
+ ResourceShare.subject_type == subject_type,
135
162
  ResourceShare.subject_id == subject_id,
136
163
  )
137
164
  return (await self.db.execute(stmt)).scalars().first()
@@ -145,7 +172,9 @@ class SharingService:
145
172
  )
146
173
  if share is None:
147
174
  raise SharingError(404, ERR_NOT_FOUND)
148
- if not principal.has(PERM_MANAGE) and share.subject_id != principal.user_id:
175
+ if not principal.has(Permissions.MANAGE) and not (
176
+ share.subject_type == SUBJECT_USER and share.subject_id == principal.user_id
177
+ ):
149
178
  resource_type = self.registry.get(share.resource_type)
150
179
  if resource_type is None:
151
180
  raise SharingError(404, ERR_NOT_FOUND)
@@ -168,5 +197,27 @@ class SharingService:
168
197
  )
169
198
  return list((await self.db.execute(stmt)).scalars())
170
199
 
200
+ async def candidates(
201
+ self,
202
+ principal: ResourcePrincipal,
203
+ rtype: str,
204
+ resource_id: str,
205
+ query: str,
206
+ subject_type: str = SUBJECT_USER,
207
+ ) -> list[ShareCandidate]:
208
+ resource_type = self._type(rtype)
209
+ row = await self._authorize(principal, resource_type, resource_id)
210
+ provider = self._subject(principal, subject_type)
211
+ term = query.strip()
212
+ if len(term) < CANDIDATES_MIN_QUERY:
213
+ return []
214
+ owner_col = getattr(resource_type.policy, "owner_col", None)
215
+ owner_id = str(getattr(row, getattr(owner_col, "key", "owner_id"), ""))
216
+ found = await provider.candidates(self.context(principal), term, owner_id)
217
+ return [
218
+ candidate.model_copy(update={"subject_type": subject_type})
219
+ for candidate in found[:CANDIDATES_MAX]
220
+ ]
221
+
171
222
 
172
223
  __all__ = ["SharingError", "SharingService"]
@@ -0,0 +1,139 @@
1
+ """Built-in subjects. User discovery keeps its existing audience and masking rules."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import unicodedata
6
+ from collections.abc import Collection, Mapping
7
+
8
+ from simple_module_core.resources import ResourcePrincipal
9
+ from simple_module_core.tenancy import TenantRole, tenant_role
10
+ from simple_module_core.user_directory import resolve_user_labels
11
+ from simple_module_db.tenancy import current_tenant_id
12
+ from sqlalchemy import false
13
+
14
+ from sharing.contracts.schemas import ShareCandidate
15
+ from sharing.contracts.subjects import (
16
+ SUBJECTS_KEY,
17
+ SubjectContext,
18
+ SubjectProvider,
19
+ SubjectRegistry,
20
+ )
21
+ from sharing.core.constants import CANDIDATES_MAX, SUBJECT_TENANT_ROLE, SUBJECT_USER, Permissions
22
+
23
+
24
+ async def _valid_user(ctx: SubjectContext, subject_id: str) -> str | None:
25
+ user = (await ctx.directory.get_many(ctx.db, [subject_id])).get(subject_id)
26
+ if user and user.is_active and user.id in await ctx.audience.visible([user.id]):
27
+ return user.id
28
+ return None
29
+
30
+
31
+ async def _user_candidates(ctx: SubjectContext, term: str, owner_id: str) -> list[ShareCandidate]:
32
+ audience_ids = await ctx.audience.search_ids()
33
+ found = await ctx.directory.search(
34
+ ctx.db,
35
+ term,
36
+ limit=CANDIDATES_MAX,
37
+ include_ids=audience_ids,
38
+ exclude_ids=[uid for uid in (owner_id, ctx.principal.user_id) if uid],
39
+ active_only=True,
40
+ exact_email=audience_ids is None and not ctx.principal.has(Permissions.DIRECTORY_SEARCH),
41
+ )
42
+ candidates = []
43
+ for user in found:
44
+ local, separator, domain = user.email.rpartition("@")
45
+ email = f"{local[:1]}•••@{domain}" if separator else "•••"
46
+ # Names may themselves contain an email; never echo those verbatim.
47
+ label = user.label if "@" not in user.label else email
48
+ candidates.append(ShareCandidate(id=user.id, display_name=label, email=email))
49
+ return candidates
50
+
51
+
52
+ async def _user_labels(ctx: SubjectContext, ids: Collection[str]) -> Mapping[str, str]:
53
+ return await resolve_user_labels(ctx.directory, ctx.db, await ctx.audience.visible(ids))
54
+
55
+
56
+ def _tenant_bound(principal: ResourcePrincipal) -> bool:
57
+ return bool(principal.tenant_id and principal.tenant_id == current_tenant_id.get())
58
+
59
+
60
+ async def _role_visible(ctx: SubjectContext) -> bool:
61
+ principal = ctx.principal
62
+ return bool(
63
+ _tenant_bound(principal)
64
+ and any(tenant_role(role) in principal.roles for role in TenantRole)
65
+ and principal.user_id
66
+ and principal.user_id in await ctx.audience.visible([principal.user_id])
67
+ )
68
+
69
+
70
+ async def _valid_role(ctx: SubjectContext, subject_id: str) -> str | None:
71
+ if subject_id in {role.value for role in TenantRole} and await _role_visible(ctx):
72
+ return subject_id
73
+ return None
74
+
75
+
76
+ def _fold(text: str) -> str:
77
+ """Case- and diacritic-insensitive form: ``Eigentümer`` and ``eigentumer`` match."""
78
+ decomposed = unicodedata.normalize("NFKD", text.casefold())
79
+ return "".join(ch for ch in decomposed if not unicodedata.combining(ch))
80
+
81
+
82
+ async def _role_candidates(ctx: SubjectContext, term: str, owner_id: str) -> list[ShareCandidate]:
83
+ if not await _role_visible(ctx):
84
+ return []
85
+ term = _fold(term)
86
+ return [
87
+ ShareCandidate(
88
+ id=role.value, display_name=tenant_role(role), subject_type=SUBJECT_TENANT_ROLE
89
+ )
90
+ for role in TenantRole
91
+ if term in role.value
92
+ or (
93
+ ctx.translate is not None
94
+ and term in _fold(ctx.translate(f"sharing.subjects.{role.value}"))
95
+ )
96
+ ]
97
+
98
+
99
+ async def _role_labels(ctx: SubjectContext, ids: Collection[str]) -> Mapping[str, str]:
100
+ if not await _role_visible(ctx):
101
+ return {}
102
+ return {role.value: tenant_role(role) for role in TenantRole if role.value in ids}
103
+
104
+
105
+ def _role_membership(principal: ResourcePrincipal, subject_id):
106
+ if not _tenant_bound(principal):
107
+ return false()
108
+ return subject_id.in_(
109
+ [role.value for role in TenantRole if tenant_role(role) in principal.roles]
110
+ )
111
+
112
+
113
+ def default_subject_registry() -> SubjectRegistry:
114
+ registry = SubjectRegistry()
115
+ registry.register(
116
+ SubjectProvider(
117
+ name=SUBJECT_USER,
118
+ label_key="sharing.subjects.user",
119
+ validate=_valid_user,
120
+ candidates=_user_candidates,
121
+ labels=_user_labels,
122
+ membership=lambda principal, subject_id: subject_id == principal.user_id,
123
+ )
124
+ )
125
+ registry.register(
126
+ SubjectProvider(
127
+ name=SUBJECT_TENANT_ROLE,
128
+ label_key="sharing.subjects.tenant_role",
129
+ validate=_valid_role,
130
+ candidates=_role_candidates,
131
+ labels=_role_labels,
132
+ membership=_role_membership,
133
+ )
134
+ )
135
+ return registry
136
+
137
+
138
+ def subjects_for(principal: ResourcePrincipal) -> SubjectRegistry:
139
+ return principal.context.get(SUBJECTS_KEY) or default_subject_registry()