sandloom-tenancy 0.7.0a1__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 (47) hide show
  1. sandloom_tenancy-0.7.0a1/.gitignore +4 -0
  2. sandloom_tenancy-0.7.0a1/CHANGELOG.md +37 -0
  3. sandloom_tenancy-0.7.0a1/LICENSE +202 -0
  4. sandloom_tenancy-0.7.0a1/NOTICE +8 -0
  5. sandloom_tenancy-0.7.0a1/PKG-INFO +53 -0
  6. sandloom_tenancy-0.7.0a1/README.md +34 -0
  7. sandloom_tenancy-0.7.0a1/pyproject.toml +38 -0
  8. sandloom_tenancy-0.7.0a1/sandloom_tenancy/__init__.py +87 -0
  9. sandloom_tenancy-0.7.0a1/sandloom_tenancy/access/__init__.py +151 -0
  10. sandloom_tenancy-0.7.0a1/sandloom_tenancy/admin.py +61 -0
  11. sandloom_tenancy-0.7.0a1/sandloom_tenancy/api/__init__.py +11 -0
  12. sandloom_tenancy-0.7.0a1/sandloom_tenancy/api/_errors.py +35 -0
  13. sandloom_tenancy-0.7.0a1/sandloom_tenancy/api/invitations.py +48 -0
  14. sandloom_tenancy-0.7.0a1/sandloom_tenancy/api/organizations.py +360 -0
  15. sandloom_tenancy-0.7.0a1/sandloom_tenancy/api/platform.py +58 -0
  16. sandloom_tenancy-0.7.0a1/sandloom_tenancy/claims.py +37 -0
  17. sandloom_tenancy-0.7.0a1/sandloom_tenancy/contracts.py +170 -0
  18. sandloom_tenancy-0.7.0a1/sandloom_tenancy/contracts.snapshot.json +278 -0
  19. sandloom_tenancy-0.7.0a1/sandloom_tenancy/events.py +212 -0
  20. sandloom_tenancy-0.7.0a1/sandloom_tenancy/exceptions.py +34 -0
  21. sandloom_tenancy-0.7.0a1/sandloom_tenancy/migrations/env.py +17 -0
  22. sandloom_tenancy-0.7.0a1/sandloom_tenancy/migrations/script.py.mako +28 -0
  23. sandloom_tenancy-0.7.0a1/sandloom_tenancy/migrations/versions/.gitkeep +0 -0
  24. sandloom_tenancy-0.7.0a1/sandloom_tenancy/migrations/versions/0001_tenancy_tenancy_tables.py +82 -0
  25. sandloom_tenancy-0.7.0a1/sandloom_tenancy/migrations/versions/0002_tenancy_invitation_token_hash.py +92 -0
  26. sandloom_tenancy-0.7.0a1/sandloom_tenancy/migrations/versions/0003_tenancy_drop_duplicate_member_index.py +36 -0
  27. sandloom_tenancy-0.7.0a1/sandloom_tenancy/migrations/versions/0004_tenancy_keyset_order_indexes.py +46 -0
  28. sandloom_tenancy-0.7.0a1/sandloom_tenancy/migrations/versions/0005_tenancy_member_versions.py +41 -0
  29. sandloom_tenancy-0.7.0a1/sandloom_tenancy/migrations/versions/0006_tenancy_timestamps_default_to_clock_timestamp.py +40 -0
  30. sandloom_tenancy-0.7.0a1/sandloom_tenancy/models/__init__.py +25 -0
  31. sandloom_tenancy-0.7.0a1/sandloom_tenancy/models/invitation.py +89 -0
  32. sandloom_tenancy-0.7.0a1/sandloom_tenancy/models/membership.py +83 -0
  33. sandloom_tenancy-0.7.0a1/sandloom_tenancy/models/organization.py +33 -0
  34. sandloom_tenancy-0.7.0a1/sandloom_tenancy/module.snapshot.json +639 -0
  35. sandloom_tenancy-0.7.0a1/sandloom_tenancy/roles.py +27 -0
  36. sandloom_tenancy-0.7.0a1/sandloom_tenancy/routes.snapshot.json +253 -0
  37. sandloom_tenancy-0.7.0a1/sandloom_tenancy/schemas/__init__.py +25 -0
  38. sandloom_tenancy-0.7.0a1/sandloom_tenancy/schemas/membership.py +39 -0
  39. sandloom_tenancy-0.7.0a1/sandloom_tenancy/schemas/organization.py +103 -0
  40. sandloom_tenancy-0.7.0a1/sandloom_tenancy/schemas/platform.py +15 -0
  41. sandloom_tenancy-0.7.0a1/sandloom_tenancy/services/__init__.py +15 -0
  42. sandloom_tenancy-0.7.0a1/sandloom_tenancy/services/invitation_service.py +339 -0
  43. sandloom_tenancy-0.7.0a1/sandloom_tenancy/services/listing.py +42 -0
  44. sandloom_tenancy-0.7.0a1/sandloom_tenancy/services/membership_service.py +440 -0
  45. sandloom_tenancy-0.7.0a1/sandloom_tenancy/services/operations.py +92 -0
  46. sandloom_tenancy-0.7.0a1/sandloom_tenancy/services/organization_service.py +308 -0
  47. sandloom_tenancy-0.7.0a1/sandloom_tenancy/services/platform_service.py +76 -0
@@ -0,0 +1,4 @@
1
+ # Build artifacts from `uv build` — not committed.
2
+ dist/
3
+ build/
4
+ *.egg-info/
@@ -0,0 +1,37 @@
1
+ # Changelog — sandloom-tenancy
2
+
3
+ All notable changes to the `sandloom-tenancy` distribution are documented here.
4
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
5
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+ Per-package entries are aggregated in the repository-level [docs/changelog.md](../../docs/changelog.md).
7
+
8
+ ## [Unreleased]
9
+
10
+ ## [0.7.0a1] — 2026-10-28
11
+
12
+ Initial public alpha preparation; earlier version headings describe internal development.
13
+
14
+ - Breaking (packaging): an ecosystem module distribution. The import package
15
+ is `sandloom_tenancy` (formerly `sandloom.tenancy`); it registers the
16
+ `sandloom.modules` entry point `tenancy = "sandloom_tenancy"` and depends on
17
+ `sandloom>=0.7,<0.8` instead of `sandloom-framework` + `sandloom-shared`.
18
+ Its contract DTOs, stubs and event schemas stay in `sandloom.shared`
19
+ (shipped with `sandloom`, SANDLOOM-C012).
20
+ `email-validator` is now its own dependency.
21
+
22
+ ## [0.7.0] — 2026-10-13
23
+
24
+ First prepared release version; public publication is pending. While the framework is `0.x`, every Sandloom
25
+ distribution is released in lockstep with the framework release line
26
+ (see [Versioning & Stability](../../docs/contributing/versioning.md));
27
+ the change list since 0.6.0 is in [CHANGELOG.md](../../CHANGELOG.md)
28
+ and the current source API upgrade steps are in
29
+ [Upgrading to Public API 1.0](../../docs/guides/upgrading-1.0.md).
30
+ The historical 0.7 migration guide remains in the preparation archive.
31
+
32
+ ### Fixed
33
+ - Source distributions include the package sources and build independently of the monorepo.
34
+
35
+ ### Added
36
+ - Tenancy module: organizations, membership (owner/admin/member) and
37
+ invitations, shipped as a standalone wheel over `sandloom-framework` + `sandloom-shared`.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,8 @@
1
+ Sandloom
2
+ Copyright 2026 Vasyl Cherniavskyi
3
+
4
+ The original Sandloom framework code, documentation and examples are licensed
5
+ under the Apache License, Version 2.0. See LICENSE for the full terms.
6
+
7
+ Third-party components and assets retain their own copyright notices and
8
+ licenses. This notice does not replace or modify those terms.
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.5
2
+ Name: sandloom-tenancy
3
+ Version: 0.7.0a1
4
+ Summary: Sandloom tenancy module: organizations, membership, invitations.
5
+ Project-URL: Homepage, https://sandloom.dev/
6
+ Project-URL: Documentation, https://sandloom.dev/docs/
7
+ Project-URL: Repository, https://github.com/Sandloom-dev/sandloom
8
+ Project-URL: Issues, https://github.com/Sandloom-dev/sandloom/issues
9
+ Project-URL: Changelog, https://github.com/Sandloom-dev/sandloom/blob/main/packages/sandloom-tenancy/CHANGELOG.md
10
+ Author: Vasyl Cherniavskyi
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ License-File: NOTICE
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Requires-Python: >=3.11
16
+ Requires-Dist: email-validator<3,>=2.3.0
17
+ Requires-Dist: sandloom<0.8,>=0.7.0a1
18
+ Description-Content-Type: text/markdown
19
+
20
+ # sandloom-tenancy
21
+
22
+ The Sandloom tenancy module: organizations, membership (owner/admin/member) and
23
+ invitations. Import package `sandloom_tenancy`; it registers the
24
+ `sandloom.modules` entry point `tenancy = "sandloom_tenancy"`, so its module
25
+ name is `tenancy` (tables `tenancy_*`, migration chain
26
+ `alembic_version_tenancy`, channels and contracts `tenancy.*`). Depends on
27
+ `sandloom>=0.7.0a1,<0.8` and email-validator; on no other module.
28
+
29
+ ```bash
30
+ pip install "sandloom[redis,celery]==0.7.0a1" sandloom-tenancy==0.7.0a1
31
+ ```
32
+
33
+ `sandloom.main:app` composes it once installed; an app selects it with
34
+ `SANDLOOM_MODULES=tenancy` (or `sandloom new <app> --with tenancy`). Other
35
+ modules call it through its contracts; their DTOs, stubs and event schemas
36
+ live in `sandloom.shared` and ship with `sandloom`.
37
+
38
+ Source of truth lives in the monorepo at `src/sandloom_tenancy`; this package
39
+ builds the wheel and source archive.
40
+
41
+ ## Project links
42
+
43
+ [Source](https://github.com/Sandloom-dev/sandloom) ·
44
+ [Documentation](https://sandloom.dev/docs/) ·
45
+ [Changelog](https://github.com/Sandloom-dev/sandloom/blob/main/packages/sandloom-tenancy/CHANGELOG.md)
46
+
47
+ This is the initial `0.7.0a1` alpha distribution. The canonical source
48
+ repository is private and awaiting transfer; the documentation website is
49
+ not deployed yet. The project links above are the planned public locations.
50
+
51
+ ## License
52
+
53
+ Apache-2.0. Copyright 2026 Vasyl Cherniavskyi. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,34 @@
1
+ # sandloom-tenancy
2
+
3
+ The Sandloom tenancy module: organizations, membership (owner/admin/member) and
4
+ invitations. Import package `sandloom_tenancy`; it registers the
5
+ `sandloom.modules` entry point `tenancy = "sandloom_tenancy"`, so its module
6
+ name is `tenancy` (tables `tenancy_*`, migration chain
7
+ `alembic_version_tenancy`, channels and contracts `tenancy.*`). Depends on
8
+ `sandloom>=0.7.0a1,<0.8` and email-validator; on no other module.
9
+
10
+ ```bash
11
+ pip install "sandloom[redis,celery]==0.7.0a1" sandloom-tenancy==0.7.0a1
12
+ ```
13
+
14
+ `sandloom.main:app` composes it once installed; an app selects it with
15
+ `SANDLOOM_MODULES=tenancy` (or `sandloom new <app> --with tenancy`). Other
16
+ modules call it through its contracts; their DTOs, stubs and event schemas
17
+ live in `sandloom.shared` and ship with `sandloom`.
18
+
19
+ Source of truth lives in the monorepo at `src/sandloom_tenancy`; this package
20
+ builds the wheel and source archive.
21
+
22
+ ## Project links
23
+
24
+ [Source](https://github.com/Sandloom-dev/sandloom) ·
25
+ [Documentation](https://sandloom.dev/docs/) ·
26
+ [Changelog](https://github.com/Sandloom-dev/sandloom/blob/main/packages/sandloom-tenancy/CHANGELOG.md)
27
+
28
+ This is the initial `0.7.0a1` alpha distribution. The canonical source
29
+ repository is private and awaiting transfer; the documentation website is
30
+ not deployed yet. The project links above are the planned public locations.
31
+
32
+ ## License
33
+
34
+ Apache-2.0. Copyright 2026 Vasyl Cherniavskyi. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,38 @@
1
+ [project]
2
+ name = "sandloom-tenancy"
3
+ version = "0.7.0a1"
4
+ classifiers = ["Development Status :: 3 - Alpha"]
5
+ description = "Sandloom tenancy module: organizations, membership, invitations."
6
+ readme = "README.md"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE", "NOTICE"]
9
+ authors = [{ name = "Vasyl Cherniavskyi" }]
10
+ requires-python = ">=3.11"
11
+ # An ecosystem module like any third party's: a compatible framework range,
12
+ # never an exact pin. Contract calls to other modules are bound at runtime
13
+ # and use the consumer's own generated stubs: no module depends on another.
14
+ dependencies = [
15
+ "sandloom>=0.7.0a1,<0.8",
16
+ "email-validator>=2.3.0,<3",
17
+ ]
18
+
19
+ [project.urls]
20
+ Homepage = "https://sandloom.dev/"
21
+ Documentation = "https://sandloom.dev/docs/"
22
+ Repository = "https://github.com/Sandloom-dev/sandloom"
23
+ Issues = "https://github.com/Sandloom-dev/sandloom/issues"
24
+ Changelog = "https://github.com/Sandloom-dev/sandloom/blob/main/packages/sandloom-tenancy/CHANGELOG.md"
25
+
26
+ # The module name (`tenancy`: tables, migration chain, channels, contracts) and
27
+ # its import path; SANDLOOM_MODULES may name it by either.
28
+ [project.entry-points."sandloom.modules"]
29
+ tenancy = "sandloom_tenancy"
30
+
31
+ [build-system]
32
+ requires = [
33
+ "hatchling>=1.27",
34
+ ]
35
+ build-backend = "hatchling.build"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["sandloom_tenancy"]
@@ -0,0 +1,87 @@
1
+ """Tenancy module: organizations, membership, invitations.
2
+
3
+ Registered via the core plugin system. Exposes the membership READ contract
4
+ through the service registry as `tenancy.membership.v1`
5
+ (:class:`~sandloom_tenancy.contracts.MembershipReadContract`: ``get_role``,
6
+ ``is_member``, ``has_role_at_least``, ``get_member_state``,
7
+ ``list_user_organization_ids``, ``list_member_user_ids``) so other
8
+ modules can resolve membership without importing tenancy internals. The write
9
+ side (add / change role / remove) is deliberately NOT part of any contract.
10
+
11
+ Contract semantics: the methods take NO session — every call runs in tenancy's
12
+ own read-only Unit of Work on tenancy's database, identically in-process and
13
+ over internal RPC (``SERVICE_BINDINGS``). The ``tenant_ids`` claims contributor
14
+ is likewise exposed as ``tenancy.claims.v1`` so an identity service deployed
15
+ alone still mints tokens with the allowlist; it is critical, so if tenancy
16
+ cannot answer, token issuance fails with 503 rather than minting a token
17
+ without ``tenant_ids``.
18
+
19
+ Staleness of the JWT ``tenant_ids`` allowlist
20
+ ---------------------------------------------
21
+ The claims contributor embeds the user's organization ids in the access token
22
+ at mint time. To stop a token minted before a member was removed / left (or
23
+ before an org was deleted) from still selecting that tenant, tenancy calls the
24
+ kernel's ``revoke_user_tokens_on_commit(user_id, reason=...,
25
+ require_immediate=True)`` for every affected user (role changes and ownership
26
+ transfers too) — the mark is written before the change commits, or the change
27
+ is refused with 503 (same path identity uses): the
28
+ framework token checks (``current_context`` / ``require(...)`` /
29
+ ``TenantScope``) then reject the stale access token with 401 and the client
30
+ refreshes, receiving a token whose ``tenant_ids`` reflects the change. A
31
+ request whose guards passed before the change committed still completes, so
32
+ authorization that must observe a removal with certainty still uses the live
33
+ contract — ``has_role_at_least`` / ``is_member`` (or the shared ``OrgRole``
34
+ atom).
35
+
36
+ A role CHANGE revokes the member's tokens too (owner decision): organization
37
+ roles are not token claims today (the contributor embeds only ``tenant_ids``)
38
+ and every role gate reads the role live, so a demotion is already effective on
39
+ the next request — the revocation ends the stale session and keeps a future
40
+ membership cache / role claims safe. The member re-authenticates.
41
+
42
+ Consumers of the member events apply ``version``-ed events with a version
43
+ guard and REFRESH on a version-less one (an instance from before the upgrade)
44
+ via ``get_member_state`` — see :mod:`sandloom.shared.membership`.
45
+
46
+ Member lifecycle events
47
+ -----------------------
48
+ Every way a member appears or changes is announced on the member channels —
49
+ ``tenancy.member_added.v1`` (``add_member``, accepting an invitation, the
50
+ owner of a new organization), ``tenancy.member_role_changed.v1`` (role change,
51
+ both sides of an ownership transfer), ``tenancy.member_removed.v1`` — written
52
+ to the outbox in the change's own UoW. Each carries ``version``: a
53
+ per-``(organization_id, user_id)`` counter (``tenancy_member_versions``),
54
+ monotonic across removal and re-add, so consumers order and dedupe with a
55
+ version guard (delivery has no ordering guarantee). It is an optional field
56
+ added within v1 (additive; older version-less events still validate).
57
+ """
58
+
59
+ from sandloom.sdk import define_module
60
+ from sandloom.sdk.module import ModuleAPI
61
+
62
+ from .claims import tenancy_claims
63
+ from .services.operations import OPERATIONS
64
+
65
+ MEMBERSHIP_SERVICE_V1 = "tenancy.membership.v1"
66
+
67
+
68
+ def _setup(core: ModuleAPI) -> None:
69
+ # Tenant selection is authorization-sensitive: never mint an access token
70
+ # without the allowlist when the tenancy module is present.
71
+ core.add_claims_contributor(tenancy_claims, critical=True)
72
+ # Declared planner operations: planned (and their executor logged) at boot.
73
+ core.register_operations(*OPERATIONS)
74
+
75
+
76
+ # Discovered (sandloom.sdk define_module): the routers of ``api.__all__``, the
77
+ # producer classes of ``events`` and the read-only ``tenancy.membership.v1``
78
+ # provider of ``contracts`` (never the full MembershipService: its write
79
+ # methods would be callable by any module or internal RPC caller).
80
+ register = define_module(
81
+ __name__,
82
+ version="1.0.0",
83
+ capabilities=["database", "eventbus"],
84
+ setup=_setup,
85
+ )
86
+
87
+ __all__ = ["register", "MEMBERSHIP_SERVICE_V1"]
@@ -0,0 +1,151 @@
1
+ """Tenancy access: organization-role enforcement.
2
+
3
+ Authentication uses the canonical shared guard (`current_user_id`, a
4
+ projection of `sandloom.shared.authz.current_context`); the org-role check goes through
5
+ the
6
+ `tenancy.membership.v1` service contract — the same path the shared `OrgRole`
7
+ atom uses. `require_org_role` is kept as a dependency (rather than the
8
+ `require(OrgRole(...))` atom) only because it returns **404** for non-members to
9
+ avoid leaking organization existence — a distinction the single-boolean atom
10
+ cannot express.
11
+
12
+ The role is resolved LIVE from the membership table on every request (never
13
+ from the JWT ``tenant_ids`` claim), so a removed member or a deleted
14
+ organization is denied immediately.
15
+ """
16
+
17
+ from collections.abc import Awaitable, Callable
18
+ from dataclasses import dataclass
19
+ from typing import get_args
20
+ from uuid import UUID
21
+
22
+ from fastapi import Depends, HTTPException, Request, status
23
+ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
24
+ from sqlalchemy.ext.asyncio import AsyncSession
25
+
26
+ from sandloom.sdk.data import PlannedReads
27
+ from sandloom.sdk.effects import sensitive_effect
28
+ from sandloom.sdk.security import decode_token_cached
29
+ from sandloom.sdk.web import DbSession, current_user_id
30
+ from sandloom_tenancy.roles import role_at_least
31
+ from sandloom_tenancy.services.membership_service import MembershipService
32
+ from sandloom_tenancy.services.operations import member_role_in_active_org
33
+
34
+ #: The request unit's session dependency: exactly ``DbSession``'s
35
+ #: ``Depends`` (function scope), for guards whose session parameter follows
36
+ #: parameters with defaults.
37
+ _REQUEST_DB = get_args(DbSession)[1]
38
+
39
+ __all__ = [
40
+ "require_org_role",
41
+ "require_org_role_reads",
42
+ "current_user_id",
43
+ "TokenEmail",
44
+ "get_token_email",
45
+ ]
46
+
47
+ _bearer = HTTPBearer(auto_error=False)
48
+
49
+
50
+ def _admin_tagged(
51
+ guard: Callable[..., Awaitable[UUID]], minimum: str
52
+ ) -> Callable[..., Awaitable[UUID]]:
53
+ """An admin-or-owner gate carries the admin risk (ADR-0009 item 6)."""
54
+ if minimum == "member":
55
+ return guard
56
+ return sensitive_effect("admin")(guard)
57
+
58
+
59
+ def require_org_role(minimum: str) -> Callable[..., Awaitable[UUID]]:
60
+ """Dependency factory: caller must hold at least `minimum` role in the org.
61
+
62
+ Reads `org_id` from the path. Returns the caller's user id on success.
63
+ 404 is returned for non-members (and for inactive organizations) to avoid
64
+ leaking organization existence.
65
+ """
66
+ # Validate eagerly: a typo'd role must fail at import, not grant access.
67
+ role_at_least(minimum, minimum)
68
+
69
+ async def _guard(
70
+ org_id: UUID,
71
+ user_id: UUID = Depends(current_user_id),
72
+ db: AsyncSession = _REQUEST_DB,
73
+ ) -> UUID:
74
+ role = await MembershipService.get_role(org_id, user_id, db)
75
+ if role is None:
76
+ raise HTTPException(
77
+ status_code=status.HTTP_404_NOT_FOUND,
78
+ detail="Organization not found",
79
+ )
80
+ if not role_at_least(role, minimum):
81
+ raise HTTPException(
82
+ status_code=status.HTTP_403_FORBIDDEN,
83
+ detail="Insufficient organization role",
84
+ )
85
+ return user_id
86
+
87
+ return _admin_tagged(_guard, minimum)
88
+
89
+
90
+ def require_org_role_reads(minimum: str) -> Callable[..., Awaitable[UUID]]:
91
+ """:func:`require_org_role` for a READ-ONLY route (``PlannedReads``).
92
+
93
+ The same check (404 for non-members / inactive organizations, 403 below
94
+ ``minimum``) through the declared ``member_role_in_active_org`` on the
95
+ route's own ``PlannedReads`` handle (FastAPI shares it with the handler),
96
+ so guard + handler reads share one read-only transaction on the general
97
+ executor, or run on the optimized one. No Unit of Work is opened.
98
+ """
99
+ role_at_least(minimum, minimum)
100
+
101
+ async def _guard(
102
+ org_id: UUID,
103
+ reads: PlannedReads,
104
+ user_id: UUID = Depends(current_user_id),
105
+ ) -> UUID:
106
+ found = await reads.one(
107
+ member_role_in_active_org, organization_id=org_id, user_id=user_id
108
+ )
109
+ if found is None:
110
+ raise HTTPException(
111
+ status_code=status.HTTP_404_NOT_FOUND,
112
+ detail="Organization not found",
113
+ )
114
+ if not role_at_least(found.role, minimum):
115
+ raise HTTPException(
116
+ status_code=status.HTTP_403_FORBIDDEN,
117
+ detail="Insufficient organization role",
118
+ )
119
+ return user_id
120
+
121
+ return _admin_tagged(_guard, minimum)
122
+
123
+
124
+ @dataclass(frozen=True, slots=True)
125
+ class TokenEmail:
126
+ """The caller's e-mail as asserted by the (signature-verified) access token."""
127
+
128
+ email: str | None
129
+ #: ``None`` when the token does not carry an ``email_verified`` claim.
130
+ verified: bool | None
131
+
132
+
133
+ async def get_token_email(
134
+ request: Request,
135
+ _user_id: UUID = Depends(current_user_id),
136
+ credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
137
+ ) -> TokenEmail:
138
+ """Read ``email`` / ``email_verified`` claims from the caller's access token.
139
+
140
+ Depends on ``current_user_id`` so the token is already authenticated
141
+ (and typed ``access``); the decode is cached per request.
142
+ """
143
+ payload = (
144
+ decode_token_cached(request, credentials.credentials) if credentials else None
145
+ ) or {}
146
+ email = payload.get("email")
147
+ verified = payload.get("email_verified")
148
+ return TokenEmail(
149
+ email=email if isinstance(email, str) and email else None,
150
+ verified=verified if isinstance(verified, bool) else None,
151
+ )