open-shield-python 0.2.0__tar.gz → 0.2.2__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. open_shield_python-0.2.2/CODE_OF_CONDUCT.md +132 -0
  2. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/CONTRIBUTING.md +1 -1
  3. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/LICENSE +1 -1
  4. open_shield_python-0.2.2/PKG-INFO +324 -0
  5. open_shield_python-0.2.2/README.md +298 -0
  6. open_shield_python-0.2.2/SECURITY.md +20 -0
  7. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/pyproject.toml +27 -1
  8. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/api/fastapi/middleware.py +3 -0
  9. open_shield_python-0.2.2/src/open_shield/domain/ports/__init__.py +5 -0
  10. open_shield_python-0.2.2/src/open_shield/domain/ports/tenant_resolver.py +37 -0
  11. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/domain/services/token_service.py +47 -10
  12. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/tests/unit/domain/test_claim_mapping.py +94 -1
  13. open_shield_python-0.2.0/None +0 -0
  14. open_shield_python-0.2.0/PKG-INFO +0 -119
  15. open_shield_python-0.2.0/README.md +0 -105
  16. open_shield_python-0.2.0/src/open_shield/domain/ports/__init__.py +0 -4
  17. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/.agent/skills/python-packaging/SKILL.md +0 -0
  18. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/.agent/skills/python-packaging/resources/implementation-playbook.md +0 -0
  19. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/.agent/skills/python-pro/SKILL.md +0 -0
  20. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/.agent/skills/python-testing-patterns/SKILL.md +0 -0
  21. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/.agent/skills/python-testing-patterns/resources/implementation-playbook.md +0 -0
  22. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/.agent/skills/solid_architecture/SKILL.md +0 -0
  23. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/.agent/skills/solid_architecture/examples/before_after_refactor.py +0 -0
  24. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/.agent/skills/solid_architecture/examples/clean_architecture_layout.md +0 -0
  25. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/.agent/skills/solid_architecture/examples/dip_ports_adapters.py +0 -0
  26. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/.agent/skills/solid_architecture/resources/code_review_checklist.md +0 -0
  27. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/.github/workflows/ci.yml +0 -0
  28. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/.gitignore +0 -0
  29. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/CHANGELOG.md +0 -0
  30. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/architecture/system-overview.md +0 -0
  31. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/design/overview.md +0 -0
  32. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/implementation/guidelines.md +0 -0
  33. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/README.md +0 -0
  34. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/backlog.md +0 -0
  35. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/decisions/0000-template.md +0 -0
  36. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/decisions/001-clean-architecture.md +0 -0
  37. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/decisions/002-modern-tooling.md +0 -0
  38. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/decisions/003-pydantic-usage.md +0 -0
  39. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/phases/phase-0-init.md +0 -0
  40. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/phases/phase-1-core.md +0 -0
  41. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/phases/phase-2-authz.md +0 -0
  42. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/phases/phase-3-integration.md +0 -0
  43. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/phases/phase-4-publish.md +0 -0
  44. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/roadmap.md +0 -0
  45. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/specs.md +0 -0
  46. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/tasks.md +0 -0
  47. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/docs/planning/tech-debt.md +0 -0
  48. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/main.py +0 -0
  49. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/adapters/__init__.py +0 -0
  50. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/adapters/config.py +0 -0
  51. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/adapters/key_provider.py +0 -0
  52. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/adapters/token_validator.py +0 -0
  53. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/api/__init__.py +0 -0
  54. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/api/fastapi/__init__.py +0 -0
  55. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/api/fastapi/dependencies.py +0 -0
  56. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/domain/__init__.py +0 -0
  57. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/domain/entities.py +0 -0
  58. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/domain/exceptions.py +0 -0
  59. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/domain/ports/key_provider.py +0 -0
  60. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/domain/ports/token_validator.py +0 -0
  61. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/domain/services/__init__.py +0 -0
  62. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/domain/services/authorization_service.py +0 -0
  63. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/src/open_shield/domain/services/claim_mapping.py +0 -0
  64. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/tests/integration/adapters/test_key_provider.py +0 -0
  65. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/tests/integration/adapters/test_token_validator.py +0 -0
  66. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/tests/integration/api/test_fastapi.py +0 -0
  67. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/tests/unit/adapters/test_config.py +0 -0
  68. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/tests/unit/domain/test_authorization_service.py +0 -0
  69. {open_shield_python-0.2.0 → open_shield_python-0.2.2}/tests/unit/domain/test_token_service.py +0 -0
@@ -0,0 +1,132 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our
6
+ community a harassment-free experience for everyone, regardless of age, body
7
+ size, visible or invisible disability, ethnicity, sex characteristics, gender
8
+ identity and expression, level of experience, education, socio-economic status,
9
+ nationality, personal appearance, race, religion, or sexual identity
10
+ and orientation.
11
+
12
+ We pledge to act and interact in ways that contribute to an open, welcoming,
13
+ diverse, inclusive, and healthy community.
14
+
15
+ ## Our Standards
16
+
17
+ Examples of behavior that contributes to a positive environment for our
18
+ community include:
19
+
20
+ * Demonstrating empathy and kindness toward other people
21
+ * Being respectful of differing opinions, viewpoints, and experiences
22
+ * Giving and gracefully accepting constructive feedback
23
+ * Accepting responsibility and apologizing to those affected by our mistakes,
24
+ and learning from the experience
25
+ * Focusing on what is best not just for us as individuals, but for the
26
+ overall community
27
+
28
+ Examples of unacceptable behavior include:
29
+
30
+ * The use of sexualized language or imagery, and sexual attention or
31
+ advances of any kind
32
+ * Trolling, insulting or derogatory comments, and personal or political attacks
33
+ * Public or private harassment
34
+ * Publishing others' private information, such as a physical or email
35
+ address, without their explicit permission
36
+ * Other conduct which could reasonably be considered inappropriate in a
37
+ professional setting
38
+
39
+ ## Enforcement Responsibilities
40
+
41
+ Community leaders are responsible for clarifying and enforcing our standards of
42
+ acceptable behavior and will take appropriate and fair corrective action in
43
+ response to any behavior that they deem inappropriate, threatening, offensive,
44
+ or harmful.
45
+
46
+ Community leaders have the right and responsibility to remove, edit, or reject
47
+ comments, commits, code, wiki edits, issues, and other contributions that are
48
+ not aligned to this Code of Conduct, and will communicate reasons for moderation
49
+ decisions when appropriate.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies within all community spaces, and also applies when
54
+ an individual is officially representing the community in public spaces.
55
+ Examples of representing our community include using an official e-mail address,
56
+ posting via an official social media account, or acting as an appointed
57
+ representative at an online or offline event.
58
+
59
+ ## Enforcement
60
+
61
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
62
+ reported to the community leaders responsible for enforcement at
63
+ avinashsingh539+osp-security@gmail.com.
64
+ All complaints will be reviewed and investigated promptly and fairly.
65
+
66
+ All community leaders are obligated to respect the privacy and security of the
67
+ reporter of any incident.
68
+
69
+ ## Enforcement Guidelines
70
+
71
+ Community leaders will follow these Community Impact Guidelines in determining
72
+ the consequences for any action they deem in violation of this Code of Conduct:
73
+
74
+ ### 1. Correction
75
+
76
+ **Community Impact**: Use of inappropriate language or other behavior deemed
77
+ unprofessional or unwelcome in the community.
78
+
79
+ **Consequence**: A private, written warning from community leaders, providing
80
+ clarity around the nature of the violation and an explanation of why the
81
+ behavior was inappropriate. A public apology may be requested.
82
+
83
+ ### 2. Warning
84
+
85
+ **Community Impact**: A violation through a single incident or series
86
+ of actions.
87
+
88
+ **Consequence**: A warning with consequences for continued behavior. No
89
+ interaction with the people involved, including unsolicited interaction with
90
+ those enforcing the Code of Conduct, for a specified period of time. This
91
+ includes avoiding interactions in community spaces as well as external channels
92
+ like social media. Violating these terms may lead to a temporary or
93
+ permanent ban.
94
+
95
+ ### 3. Temporary Ban
96
+
97
+ **Community Impact**: A serious violation of community standards, including
98
+ sustained inappropriate behavior.
99
+
100
+ **Consequence**: A temporary ban from any sort of interaction or public
101
+ communication with the community for a specified period of time. No public or
102
+ private interaction with the people involved, including unsolicited interaction
103
+ with those enforcing the Code of Conduct, is allowed during this period.
104
+ Violating these terms may lead to a permanent ban.
105
+
106
+ ### 4. Permanent Ban
107
+
108
+ **Community Impact**: Demonstrating a pattern of violation of community
109
+ standards, including sustained inappropriate behavior, harassment of an
110
+ individual, or aggression toward or disparagement of classes of individuals.
111
+
112
+ **Consequence**: A permanent ban from any sort of public interaction within
113
+ the community.
114
+
115
+ ## Attribution
116
+
117
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118
+ version 2.1, available at
119
+ [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
120
+
121
+ Community Impact Guidelines were inspired by
122
+ [Mozilla's code of conduct enforcement ladder][Mozilla CoC].
123
+
124
+ For answers to common questions about this code of conduct, see the FAQ at
125
+ [https://www.contributor-covenant.org/faq][FAQ]. Translations are available
126
+ at [https://www.contributor-covenant.org/translations][translations].
127
+
128
+ [homepage]: https://www.contributor-covenant.org
129
+ [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
130
+ [Mozilla CoC]: https://github.com/mozilla/diversity
131
+ [FAQ]: https://www.contributor-covenant.org/faq
132
+ [translations]: https://www.contributor-covenant.org/translations
@@ -11,7 +11,7 @@ Thank you for your interest in contributing to Open Shield! We welcome contribut
11
11
 
12
12
  2. **Clone the repository**:
13
13
  ```bash
14
- git clone https://github.com/prayog-ai-labs/open-shield-python.git
14
+ git clone https://github.com/avinash-singh-io/open-shield-python.git
15
15
  cd open-shield-python
16
16
  ```
17
17
 
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2026 Prayog AI Labs
3
+ Copyright (c) 2026 Avinash Singh
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
@@ -0,0 +1,324 @@
1
+ Metadata-Version: 2.4
2
+ Name: open-shield-python
3
+ Version: 0.2.2
4
+ Summary: Vendor-agnostic authentication and authorization enforcement SDK
5
+ Project-URL: Homepage, https://github.com/avinash-singh-io/open-shield-python
6
+ Project-URL: Repository, https://github.com/avinash-singh-io/open-shield-python
7
+ Project-URL: Bug Tracker, https://github.com/avinash-singh-io/open-shield-python/issues
8
+ Author-email: Avinash Singh <avinashsingh539+osp-security@gmail.com>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: authentication,authorization,fastapi,jwt,oidc,rbac,security
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.12
19
+ Requires-Dist: cryptography>=42.0.0
20
+ Requires-Dist: fastapi>=0.129.0
21
+ Requires-Dist: httpx>=0.27.0
22
+ Requires-Dist: pydantic-settings>=2.0.0
23
+ Requires-Dist: pydantic>=2.0.0
24
+ Requires-Dist: pyjwt>=2.8.0
25
+ Description-Content-Type: text/markdown
26
+
27
+ # Open Shield Python SDK
28
+
29
+ [![CI](https://github.com/avinash-singh-io/open-shield-python/actions/workflows/ci.yml/badge.svg)](https://github.com/avinash-singh-io/open-shield-python/actions/workflows/ci.yml)
30
+
31
+ Vendor-agnostic authentication and authorization enforcement SDK for Python.
32
+
33
+ Open Shield lets you enforce authentication (AuthN) and authorization (AuthZ) in your Python applications without coupling to a specific identity provider. Works with **Logto**, **Keycloak**, **Auth0**, **Entra ID**, **Cognito**, or any OIDC-compliant provider.
34
+
35
+ ## Features
36
+
37
+ - **Vendor Neutral** — Works with any OIDC-compliant identity provider
38
+ - **Configurable Claim Mapping** — Map any JWT claim to user/tenant/role fields
39
+ - **3-Step Tenant Cascade** — Correct isolation for individual users, SaaS orgs, and M2M clients
40
+ - **Actor Type Inference** — Automatically detect users, agents, and service accounts
41
+ - **Framework Agnostic** — Core logic is pure Python; first-class FastAPI support
42
+ - **Clean Architecture** — Domain ↔ Adapters ↔ API layers with strict dependency inversion
43
+ - **Type Safe** — Fully typed, checked with `mypy`
44
+ - **Automatic JWKS Rotation** — Fetches and caches keys from OIDC discovery
45
+
46
+ ## Installation
47
+
48
+ ```bash
49
+ pip install open-shield-python
50
+ ```
51
+
52
+ ## Quick Start (FastAPI)
53
+
54
+ ### 1. Configure Environment
55
+
56
+ ```bash
57
+ OPEN_SHIELD_ISSUER_URL=https://your-auth-domain.com/oidc
58
+ OPEN_SHIELD_AUDIENCE=my-api-identifier
59
+ ```
60
+
61
+ ### 2. Add Middleware
62
+
63
+ ```python
64
+ from fastapi import FastAPI, Depends
65
+ from open_shield.api.fastapi import (
66
+ OpenShieldMiddleware,
67
+ get_user_context,
68
+ get_optional_user_context,
69
+ RequireScope,
70
+ RequireRole,
71
+ )
72
+ from open_shield.adapters import OpenShieldConfig
73
+ from open_shield.domain.entities import UserContext
74
+
75
+ app = FastAPI()
76
+ config = OpenShieldConfig() # Reads from env vars
77
+
78
+ app.add_middleware(OpenShieldMiddleware, config=config)
79
+
80
+ @app.get("/health")
81
+ def health():
82
+ return {"status": "ok"}
83
+
84
+ @app.get("/users/me")
85
+ def read_current_user(ctx: UserContext = Depends(get_user_context)):
86
+ return {
87
+ "id": ctx.user.id,
88
+ "email": ctx.user.email,
89
+ "actor_type": ctx.user.actor_type,
90
+ "tenant": ctx.tenant.tenant_id if ctx.tenant else None,
91
+ "scopes": ctx.user.scopes,
92
+ "roles": ctx.user.roles,
93
+ }
94
+
95
+ @app.get("/admin/dashboard")
96
+ def admin_dashboard(ctx: UserContext = Depends(RequireScope("read:admin"))):
97
+ return {"data": "secret"}
98
+
99
+ @app.get("/manager/reports")
100
+ def reports(ctx: UserContext = Depends(RequireRole(["manager", "admin"]))):
101
+ return {"reports": []}
102
+ ```
103
+
104
+ ---
105
+
106
+ ## Configurable Claim Mapping
107
+
108
+ Different identity providers use different JWT claim names. Open Shield lets you configure which claims map to which identity fields — **zero code changes** when switching providers.
109
+
110
+ ### Environment Variables
111
+
112
+ | Variable | Description | Default |
113
+ |----------|-------------|---------|
114
+ | `OPEN_SHIELD_ISSUER_URL` | OIDC Issuer URL **(required)** | — |
115
+ | `OPEN_SHIELD_AUDIENCE` | Expected `aud` claim | `None` |
116
+ | `OPEN_SHIELD_ALGORITHMS` | Allowed signing algorithms | `["RS256"]` |
117
+ | `OPEN_SHIELD_USER_ID_CLAIM` | Claim for user ID | `sub` |
118
+ | `OPEN_SHIELD_EMAIL_CLAIM` | Claim for email | `email` |
119
+ | `OPEN_SHIELD_TENANT_ID_CLAIM` | Claim for tenant/org ID | `tid` |
120
+ | `OPEN_SHIELD_SCOPE_CLAIM` | Claim for scopes | `scope` |
121
+ | `OPEN_SHIELD_ROLES_CLAIM` | Claim for roles | `roles` |
122
+ | `OPEN_SHIELD_TENANT_FALLBACK` | Fallback when tenant claim missing | `none` |
123
+
124
+ ### Provider Examples
125
+
126
+ <details>
127
+ <summary><strong>Logto</strong></summary>
128
+
129
+ ```bash
130
+ OPEN_SHIELD_ISSUER_URL=https://my-logto.com/oidc
131
+ OPEN_SHIELD_AUDIENCE=https://my-api.com
132
+ OPEN_SHIELD_TENANT_ID_CLAIM=organization_id
133
+ OPEN_SHIELD_TENANT_FALLBACK=sub # Individual users get isolation
134
+ ```
135
+ </details>
136
+
137
+ <details>
138
+ <summary><strong>Keycloak</strong></summary>
139
+
140
+ ```bash
141
+ OPEN_SHIELD_ISSUER_URL=https://keycloak.com/realms/myrealm
142
+ OPEN_SHIELD_AUDIENCE=my-client-id
143
+ OPEN_SHIELD_TENANT_ID_CLAIM=tenant # Custom claim from mapper
144
+ OPEN_SHIELD_ROLES_CLAIM=roles # Keycloak realm_access also supported
145
+ ```
146
+ </details>
147
+
148
+ <details>
149
+ <summary><strong>Auth0</strong></summary>
150
+
151
+ ```bash
152
+ OPEN_SHIELD_ISSUER_URL=https://my-tenant.auth0.com/
153
+ OPEN_SHIELD_AUDIENCE=https://my-api
154
+ OPEN_SHIELD_TENANT_ID_CLAIM=org_id
155
+ OPEN_SHIELD_SCOPE_CLAIM=permissions # Auth0 uses 'permissions' for RBAC
156
+ ```
157
+ </details>
158
+
159
+ <details>
160
+ <summary><strong>Azure Entra ID</strong></summary>
161
+
162
+ ```bash
163
+ OPEN_SHIELD_ISSUER_URL=https://login.microsoftonline.com/{tenant-id}/v2.0
164
+ OPEN_SHIELD_AUDIENCE=api://my-api
165
+ OPEN_SHIELD_TENANT_ID_CLAIM=tid
166
+ OPEN_SHIELD_ROLES_CLAIM=roles
167
+ ```
168
+ </details>
169
+
170
+ ### Programmatic Configuration
171
+
172
+ ```python
173
+ from open_shield.adapters import OpenShieldConfig
174
+
175
+ config = OpenShieldConfig(
176
+ ISSUER_URL="https://my-auth.com/oidc",
177
+ AUDIENCE="https://my-api",
178
+ TENANT_ID_CLAIM="organization_id",
179
+ TENANT_FALLBACK="sub",
180
+ )
181
+ ```
182
+
183
+ ---
184
+
185
+ ## Tenant Resolution Cascade
186
+
187
+ Tenant isolation is critical for data security. Open Shield uses a **3-step cascade** to resolve the tenant for every request — supporting individual users, SaaS organizations, and M2M service accounts.
188
+
189
+ ### How It Works
190
+
191
+ ```
192
+ Step 1: M2M client (sub == client_id) → TenantResolverPort.resolve_tenant()
193
+ Step 2: Organization claim → OPEN_SHIELD_TENANT_ID_CLAIM
194
+ Step 3: Sub fallback → sub (when TENANT_FALLBACK=sub)
195
+ ```
196
+
197
+ | Use Case | Tenant Source | Config |
198
+ |----------|---------------|--------|
199
+ | Individual user | `sub` | `TENANT_FALLBACK=sub` |
200
+ | SaaS with orgs | `organization_id` | `TENANT_ID_CLAIM=organization_id` |
201
+ | M2M service | Registry lookup | Implement `TenantResolverPort` |
202
+ | No tenant needed | None | `TENANT_FALLBACK=none` (default) |
203
+
204
+ ### When to Use Each Strategy
205
+
206
+ **Individual users (OSS, personal tools):**
207
+ ```bash
208
+ OPEN_SHIELD_TENANT_FALLBACK=sub
209
+ ```
210
+ Each user = separate dataset. Simple. Works immediately.
211
+
212
+ **SaaS with organizations (teams, billing per org):**
213
+ ```bash
214
+ OPEN_SHIELD_TENANT_ID_CLAIM=organization_id
215
+ OPEN_SHIELD_TENANT_FALLBACK=none # Don't fall back to sub
216
+ ```
217
+ Multiple users share org data. Required for team features.
218
+
219
+ **M2M / AI agents (client_credentials flow):**
220
+ ```python
221
+ from open_shield.domain.ports import TenantResolverPort
222
+
223
+ class MyTenantResolver(TenantResolverPort):
224
+ """Look up tenant for machine clients from your registry."""
225
+
226
+ def resolve_tenant(self, client_id: str) -> str | None:
227
+ # Query your DB, config, or IdP management API
228
+ return db.get_tenant_for_client(client_id)
229
+
230
+ # Pass resolver to middleware
231
+ config = OpenShieldConfig(...)
232
+ app.add_middleware(
233
+ OpenShieldMiddleware,
234
+ config=config,
235
+ tenant_resolver=MyTenantResolver(),
236
+ )
237
+ ```
238
+
239
+ ### Resolution Metadata
240
+
241
+ Every resolved tenant includes traceability:
242
+
243
+ ```python
244
+ ctx.tenant.metadata["resolution"] # "m2m_lookup" | "claim" | "sub_fallback"
245
+ ```
246
+
247
+ ---
248
+
249
+ ## Actor Type Inference
250
+
251
+ Open Shield automatically classifies the caller:
252
+
253
+ | Actor Type | Detection | Example |
254
+ |------------|-----------|---------|
255
+ | `user` | Default for human tokens | Normal login flow |
256
+ | `service` | `sub == client_id` | M2M client_credentials |
257
+ | `agent` | `sub == client_id` + `"agent"` role | AI agent with agent role |
258
+
259
+ ```python
260
+ ctx.user.actor_type # "user" | "service" | "agent"
261
+ ```
262
+
263
+ ---
264
+
265
+ ## Architecture
266
+
267
+ ```
268
+ ┌─────────────────────────────────────────────────┐
269
+ │ API Layer (FastAPI middleware, dependencies) │
270
+ ├─────────────────────────────────────────────────┤
271
+ │ Domain Layer (pure Python, zero dependencies) │
272
+ │ ├── Entities: User, Token, TenantContext │
273
+ │ ├── Services: TokenService, AuthzService │
274
+ │ ├── Ports: TokenValidatorPort, TenantResolver │
275
+ │ └── ClaimMapping: configurable extraction │
276
+ ├─────────────────────────────────────────────────┤
277
+ │ Adapters Layer (PyJWT, httpx, OIDC discovery) │
278
+ └─────────────────────────────────────────────────┘
279
+ ```
280
+
281
+ **Ports (interfaces):**
282
+ - `TokenValidatorPort` — JWT validation
283
+ - `KeyProviderPort` — JWKS key fetching
284
+ - `TenantResolverPort` — M2M client → tenant lookup
285
+
286
+ All ports are in the domain layer. Adapters implement them in the adapters layer. You can swap implementations without touching application code.
287
+
288
+ ---
289
+
290
+ ## Optional Authentication
291
+
292
+ For routes that work with or without auth (e.g., public APIs with enhanced features for logged-in users):
293
+
294
+ ```python
295
+ from open_shield.api.fastapi import get_optional_user_context
296
+
297
+ @app.get("/search")
298
+ def search(ctx: UserContext | None = Depends(get_optional_user_context)):
299
+ if ctx:
300
+ return personalized_results(ctx.user.id)
301
+ return public_results()
302
+ ```
303
+
304
+ ---
305
+
306
+ ## Development
307
+
308
+ ```bash
309
+ # Install dependencies
310
+ uv sync
311
+
312
+ # Run tests
313
+ uv run pytest
314
+
315
+ # Lint and format
316
+ uv run ruff check .
317
+
318
+ # Type check
319
+ uv run mypy src/
320
+ ```
321
+
322
+ ## License
323
+
324
+ MIT