open-shield-python 0.2.1__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 (68) hide show
  1. open_shield_python-0.2.2/CODE_OF_CONDUCT.md +132 -0
  2. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/CONTRIBUTING.md +1 -1
  3. {open_shield_python-0.2.1 → 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.1 → open_shield_python-0.2.2}/pyproject.toml +27 -1
  8. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/api/fastapi/middleware.py +3 -0
  9. open_shield_python-0.2.1/None +0 -0
  10. open_shield_python-0.2.1/PKG-INFO +0 -119
  11. open_shield_python-0.2.1/README.md +0 -105
  12. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/.agent/skills/python-packaging/SKILL.md +0 -0
  13. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/.agent/skills/python-packaging/resources/implementation-playbook.md +0 -0
  14. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/.agent/skills/python-pro/SKILL.md +0 -0
  15. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/.agent/skills/python-testing-patterns/SKILL.md +0 -0
  16. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/.agent/skills/python-testing-patterns/resources/implementation-playbook.md +0 -0
  17. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/.agent/skills/solid_architecture/SKILL.md +0 -0
  18. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/.agent/skills/solid_architecture/examples/before_after_refactor.py +0 -0
  19. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/.agent/skills/solid_architecture/examples/clean_architecture_layout.md +0 -0
  20. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/.agent/skills/solid_architecture/examples/dip_ports_adapters.py +0 -0
  21. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/.agent/skills/solid_architecture/resources/code_review_checklist.md +0 -0
  22. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/.github/workflows/ci.yml +0 -0
  23. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/.gitignore +0 -0
  24. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/CHANGELOG.md +0 -0
  25. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/architecture/system-overview.md +0 -0
  26. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/design/overview.md +0 -0
  27. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/implementation/guidelines.md +0 -0
  28. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/README.md +0 -0
  29. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/backlog.md +0 -0
  30. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/decisions/0000-template.md +0 -0
  31. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/decisions/001-clean-architecture.md +0 -0
  32. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/decisions/002-modern-tooling.md +0 -0
  33. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/decisions/003-pydantic-usage.md +0 -0
  34. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/phases/phase-0-init.md +0 -0
  35. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/phases/phase-1-core.md +0 -0
  36. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/phases/phase-2-authz.md +0 -0
  37. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/phases/phase-3-integration.md +0 -0
  38. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/phases/phase-4-publish.md +0 -0
  39. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/roadmap.md +0 -0
  40. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/specs.md +0 -0
  41. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/tasks.md +0 -0
  42. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/docs/planning/tech-debt.md +0 -0
  43. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/main.py +0 -0
  44. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/adapters/__init__.py +0 -0
  45. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/adapters/config.py +0 -0
  46. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/adapters/key_provider.py +0 -0
  47. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/adapters/token_validator.py +0 -0
  48. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/api/__init__.py +0 -0
  49. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/api/fastapi/__init__.py +0 -0
  50. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/api/fastapi/dependencies.py +0 -0
  51. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/domain/__init__.py +0 -0
  52. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/domain/entities.py +0 -0
  53. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/domain/exceptions.py +0 -0
  54. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/domain/ports/__init__.py +0 -0
  55. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/domain/ports/key_provider.py +0 -0
  56. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/domain/ports/tenant_resolver.py +0 -0
  57. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/domain/ports/token_validator.py +0 -0
  58. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/domain/services/__init__.py +0 -0
  59. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/domain/services/authorization_service.py +0 -0
  60. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/domain/services/claim_mapping.py +0 -0
  61. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/src/open_shield/domain/services/token_service.py +0 -0
  62. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/tests/integration/adapters/test_key_provider.py +0 -0
  63. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/tests/integration/adapters/test_token_validator.py +0 -0
  64. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/tests/integration/api/test_fastapi.py +0 -0
  65. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/tests/unit/adapters/test_config.py +0 -0
  66. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/tests/unit/domain/test_authorization_service.py +0 -0
  67. {open_shield_python-0.2.1 → open_shield_python-0.2.2}/tests/unit/domain/test_claim_mapping.py +0 -0
  68. {open_shield_python-0.2.1 → 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
@@ -0,0 +1,298 @@
1
+ # Open Shield Python SDK
2
+
3
+ [![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)
4
+
5
+ Vendor-agnostic authentication and authorization enforcement SDK for Python.
6
+
7
+ 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.
8
+
9
+ ## Features
10
+
11
+ - **Vendor Neutral** — Works with any OIDC-compliant identity provider
12
+ - **Configurable Claim Mapping** — Map any JWT claim to user/tenant/role fields
13
+ - **3-Step Tenant Cascade** — Correct isolation for individual users, SaaS orgs, and M2M clients
14
+ - **Actor Type Inference** — Automatically detect users, agents, and service accounts
15
+ - **Framework Agnostic** — Core logic is pure Python; first-class FastAPI support
16
+ - **Clean Architecture** — Domain ↔ Adapters ↔ API layers with strict dependency inversion
17
+ - **Type Safe** — Fully typed, checked with `mypy`
18
+ - **Automatic JWKS Rotation** — Fetches and caches keys from OIDC discovery
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ pip install open-shield-python
24
+ ```
25
+
26
+ ## Quick Start (FastAPI)
27
+
28
+ ### 1. Configure Environment
29
+
30
+ ```bash
31
+ OPEN_SHIELD_ISSUER_URL=https://your-auth-domain.com/oidc
32
+ OPEN_SHIELD_AUDIENCE=my-api-identifier
33
+ ```
34
+
35
+ ### 2. Add Middleware
36
+
37
+ ```python
38
+ from fastapi import FastAPI, Depends
39
+ from open_shield.api.fastapi import (
40
+ OpenShieldMiddleware,
41
+ get_user_context,
42
+ get_optional_user_context,
43
+ RequireScope,
44
+ RequireRole,
45
+ )
46
+ from open_shield.adapters import OpenShieldConfig
47
+ from open_shield.domain.entities import UserContext
48
+
49
+ app = FastAPI()
50
+ config = OpenShieldConfig() # Reads from env vars
51
+
52
+ app.add_middleware(OpenShieldMiddleware, config=config)
53
+
54
+ @app.get("/health")
55
+ def health():
56
+ return {"status": "ok"}
57
+
58
+ @app.get("/users/me")
59
+ def read_current_user(ctx: UserContext = Depends(get_user_context)):
60
+ return {
61
+ "id": ctx.user.id,
62
+ "email": ctx.user.email,
63
+ "actor_type": ctx.user.actor_type,
64
+ "tenant": ctx.tenant.tenant_id if ctx.tenant else None,
65
+ "scopes": ctx.user.scopes,
66
+ "roles": ctx.user.roles,
67
+ }
68
+
69
+ @app.get("/admin/dashboard")
70
+ def admin_dashboard(ctx: UserContext = Depends(RequireScope("read:admin"))):
71
+ return {"data": "secret"}
72
+
73
+ @app.get("/manager/reports")
74
+ def reports(ctx: UserContext = Depends(RequireRole(["manager", "admin"]))):
75
+ return {"reports": []}
76
+ ```
77
+
78
+ ---
79
+
80
+ ## Configurable Claim Mapping
81
+
82
+ 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.
83
+
84
+ ### Environment Variables
85
+
86
+ | Variable | Description | Default |
87
+ |----------|-------------|---------|
88
+ | `OPEN_SHIELD_ISSUER_URL` | OIDC Issuer URL **(required)** | — |
89
+ | `OPEN_SHIELD_AUDIENCE` | Expected `aud` claim | `None` |
90
+ | `OPEN_SHIELD_ALGORITHMS` | Allowed signing algorithms | `["RS256"]` |
91
+ | `OPEN_SHIELD_USER_ID_CLAIM` | Claim for user ID | `sub` |
92
+ | `OPEN_SHIELD_EMAIL_CLAIM` | Claim for email | `email` |
93
+ | `OPEN_SHIELD_TENANT_ID_CLAIM` | Claim for tenant/org ID | `tid` |
94
+ | `OPEN_SHIELD_SCOPE_CLAIM` | Claim for scopes | `scope` |
95
+ | `OPEN_SHIELD_ROLES_CLAIM` | Claim for roles | `roles` |
96
+ | `OPEN_SHIELD_TENANT_FALLBACK` | Fallback when tenant claim missing | `none` |
97
+
98
+ ### Provider Examples
99
+
100
+ <details>
101
+ <summary><strong>Logto</strong></summary>
102
+
103
+ ```bash
104
+ OPEN_SHIELD_ISSUER_URL=https://my-logto.com/oidc
105
+ OPEN_SHIELD_AUDIENCE=https://my-api.com
106
+ OPEN_SHIELD_TENANT_ID_CLAIM=organization_id
107
+ OPEN_SHIELD_TENANT_FALLBACK=sub # Individual users get isolation
108
+ ```
109
+ </details>
110
+
111
+ <details>
112
+ <summary><strong>Keycloak</strong></summary>
113
+
114
+ ```bash
115
+ OPEN_SHIELD_ISSUER_URL=https://keycloak.com/realms/myrealm
116
+ OPEN_SHIELD_AUDIENCE=my-client-id
117
+ OPEN_SHIELD_TENANT_ID_CLAIM=tenant # Custom claim from mapper
118
+ OPEN_SHIELD_ROLES_CLAIM=roles # Keycloak realm_access also supported
119
+ ```
120
+ </details>
121
+
122
+ <details>
123
+ <summary><strong>Auth0</strong></summary>
124
+
125
+ ```bash
126
+ OPEN_SHIELD_ISSUER_URL=https://my-tenant.auth0.com/
127
+ OPEN_SHIELD_AUDIENCE=https://my-api
128
+ OPEN_SHIELD_TENANT_ID_CLAIM=org_id
129
+ OPEN_SHIELD_SCOPE_CLAIM=permissions # Auth0 uses 'permissions' for RBAC
130
+ ```
131
+ </details>
132
+
133
+ <details>
134
+ <summary><strong>Azure Entra ID</strong></summary>
135
+
136
+ ```bash
137
+ OPEN_SHIELD_ISSUER_URL=https://login.microsoftonline.com/{tenant-id}/v2.0
138
+ OPEN_SHIELD_AUDIENCE=api://my-api
139
+ OPEN_SHIELD_TENANT_ID_CLAIM=tid
140
+ OPEN_SHIELD_ROLES_CLAIM=roles
141
+ ```
142
+ </details>
143
+
144
+ ### Programmatic Configuration
145
+
146
+ ```python
147
+ from open_shield.adapters import OpenShieldConfig
148
+
149
+ config = OpenShieldConfig(
150
+ ISSUER_URL="https://my-auth.com/oidc",
151
+ AUDIENCE="https://my-api",
152
+ TENANT_ID_CLAIM="organization_id",
153
+ TENANT_FALLBACK="sub",
154
+ )
155
+ ```
156
+
157
+ ---
158
+
159
+ ## Tenant Resolution Cascade
160
+
161
+ 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.
162
+
163
+ ### How It Works
164
+
165
+ ```
166
+ Step 1: M2M client (sub == client_id) → TenantResolverPort.resolve_tenant()
167
+ Step 2: Organization claim → OPEN_SHIELD_TENANT_ID_CLAIM
168
+ Step 3: Sub fallback → sub (when TENANT_FALLBACK=sub)
169
+ ```
170
+
171
+ | Use Case | Tenant Source | Config |
172
+ |----------|---------------|--------|
173
+ | Individual user | `sub` | `TENANT_FALLBACK=sub` |
174
+ | SaaS with orgs | `organization_id` | `TENANT_ID_CLAIM=organization_id` |
175
+ | M2M service | Registry lookup | Implement `TenantResolverPort` |
176
+ | No tenant needed | None | `TENANT_FALLBACK=none` (default) |
177
+
178
+ ### When to Use Each Strategy
179
+
180
+ **Individual users (OSS, personal tools):**
181
+ ```bash
182
+ OPEN_SHIELD_TENANT_FALLBACK=sub
183
+ ```
184
+ Each user = separate dataset. Simple. Works immediately.
185
+
186
+ **SaaS with organizations (teams, billing per org):**
187
+ ```bash
188
+ OPEN_SHIELD_TENANT_ID_CLAIM=organization_id
189
+ OPEN_SHIELD_TENANT_FALLBACK=none # Don't fall back to sub
190
+ ```
191
+ Multiple users share org data. Required for team features.
192
+
193
+ **M2M / AI agents (client_credentials flow):**
194
+ ```python
195
+ from open_shield.domain.ports import TenantResolverPort
196
+
197
+ class MyTenantResolver(TenantResolverPort):
198
+ """Look up tenant for machine clients from your registry."""
199
+
200
+ def resolve_tenant(self, client_id: str) -> str | None:
201
+ # Query your DB, config, or IdP management API
202
+ return db.get_tenant_for_client(client_id)
203
+
204
+ # Pass resolver to middleware
205
+ config = OpenShieldConfig(...)
206
+ app.add_middleware(
207
+ OpenShieldMiddleware,
208
+ config=config,
209
+ tenant_resolver=MyTenantResolver(),
210
+ )
211
+ ```
212
+
213
+ ### Resolution Metadata
214
+
215
+ Every resolved tenant includes traceability:
216
+
217
+ ```python
218
+ ctx.tenant.metadata["resolution"] # "m2m_lookup" | "claim" | "sub_fallback"
219
+ ```
220
+
221
+ ---
222
+
223
+ ## Actor Type Inference
224
+
225
+ Open Shield automatically classifies the caller:
226
+
227
+ | Actor Type | Detection | Example |
228
+ |------------|-----------|---------|
229
+ | `user` | Default for human tokens | Normal login flow |
230
+ | `service` | `sub == client_id` | M2M client_credentials |
231
+ | `agent` | `sub == client_id` + `"agent"` role | AI agent with agent role |
232
+
233
+ ```python
234
+ ctx.user.actor_type # "user" | "service" | "agent"
235
+ ```
236
+
237
+ ---
238
+
239
+ ## Architecture
240
+
241
+ ```
242
+ ┌─────────────────────────────────────────────────┐
243
+ │ API Layer (FastAPI middleware, dependencies) │
244
+ ├─────────────────────────────────────────────────┤
245
+ │ Domain Layer (pure Python, zero dependencies) │
246
+ │ ├── Entities: User, Token, TenantContext │
247
+ │ ├── Services: TokenService, AuthzService │
248
+ │ ├── Ports: TokenValidatorPort, TenantResolver │
249
+ │ └── ClaimMapping: configurable extraction │
250
+ ├─────────────────────────────────────────────────┤
251
+ │ Adapters Layer (PyJWT, httpx, OIDC discovery) │
252
+ └─────────────────────────────────────────────────┘
253
+ ```
254
+
255
+ **Ports (interfaces):**
256
+ - `TokenValidatorPort` — JWT validation
257
+ - `KeyProviderPort` — JWKS key fetching
258
+ - `TenantResolverPort` — M2M client → tenant lookup
259
+
260
+ All ports are in the domain layer. Adapters implement them in the adapters layer. You can swap implementations without touching application code.
261
+
262
+ ---
263
+
264
+ ## Optional Authentication
265
+
266
+ For routes that work with or without auth (e.g., public APIs with enhanced features for logged-in users):
267
+
268
+ ```python
269
+ from open_shield.api.fastapi import get_optional_user_context
270
+
271
+ @app.get("/search")
272
+ def search(ctx: UserContext | None = Depends(get_optional_user_context)):
273
+ if ctx:
274
+ return personalized_results(ctx.user.id)
275
+ return public_results()
276
+ ```
277
+
278
+ ---
279
+
280
+ ## Development
281
+
282
+ ```bash
283
+ # Install dependencies
284
+ uv sync
285
+
286
+ # Run tests
287
+ uv run pytest
288
+
289
+ # Lint and format
290
+ uv run ruff check .
291
+
292
+ # Type check
293
+ uv run mypy src/
294
+ ```
295
+
296
+ ## License
297
+
298
+ MIT
@@ -0,0 +1,20 @@
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ Currently, the `main` branch and the latest published PyPI release are supported for security updates.
6
+
7
+ ## Reporting a Vulnerability
8
+
9
+ We take the security of Open Shield very seriously. If you discover a vulnerability, please do NOT use the issue tracker to report it publicly.
10
+
11
+ Instead, please send an email to: **avinashsingh539+osp-security@gmail.com**
12
+
13
+ Please provide as much information as possible, including:
14
+
15
+ - A description of the vulnerability.
16
+ - Steps to reproduce it.
17
+ - Possible impact or attack vector.
18
+ - Your contact information for follow-up.
19
+
20
+ We will acknowledge receipt of your report within 48 hours and provide an estimated timeline for a fix. Once the vulnerability is patched, we will coordinate public disclosure.
@@ -1,9 +1,30 @@
1
1
  [project]
2
2
  name = "open-shield-python"
3
- version = "0.2.1"
3
+ version = "0.2.2"
4
4
  description = "Vendor-agnostic authentication and authorization enforcement SDK"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
7
+ license = { text = "MIT" }
8
+ authors = [
9
+ { name = "Avinash Singh", email = "avinashsingh539+osp-security@gmail.com" }
10
+ ]
11
+ keywords = [
12
+ "authentication",
13
+ "authorization",
14
+ "fastapi",
15
+ "jwt",
16
+ "oidc",
17
+ "rbac",
18
+ "security"
19
+ ]
20
+ classifiers = [
21
+ "Development Status :: 4 - Beta",
22
+ "Intended Audience :: Developers",
23
+ "License :: OSI Approved :: MIT License",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Typing :: Typed",
27
+ ]
7
28
  dependencies = [
8
29
  "pydantic>=2.0.0",
9
30
  "pydantic-settings>=2.0.0",
@@ -52,3 +73,8 @@ dev = [
52
73
  "ruff>=0.15.0",
53
74
  "uvicorn>=0.40.0",
54
75
  ]
76
+
77
+ [project.urls]
78
+ Homepage = "https://github.com/avinash-singh-io/open-shield-python"
79
+ Repository = "https://github.com/avinash-singh-io/open-shield-python"
80
+ "Bug Tracker" = "https://github.com/avinash-singh-io/open-shield-python/issues"
@@ -4,6 +4,7 @@ from starlette.types import ASGIApp
4
4
 
5
5
  from open_shield.adapters import OIDCDiscoKeyProvider, OpenShieldConfig, PyJWTValidator
6
6
  from open_shield.domain.exceptions import OpenShieldError, TokenValidationError
7
+ from open_shield.domain.ports import TenantResolverPort
7
8
  from open_shield.domain.services import TokenService
8
9
  from open_shield.domain.services.claim_mapping import ClaimMapping
9
10
 
@@ -27,6 +28,7 @@ class OpenShieldMiddleware(BaseHTTPMiddleware):
27
28
  app: ASGIApp,
28
29
  config: OpenShieldConfig,
29
30
  exclude_paths: set[str] | None = None,
31
+ tenant_resolver: TenantResolverPort | None = None,
30
32
  ):
31
33
  super().__init__(app)
32
34
  self.config = config
@@ -58,6 +60,7 @@ class OpenShieldMiddleware(BaseHTTPMiddleware):
58
60
  self.token_service = TokenService(
59
61
  validator=validator,
60
62
  claim_mapping=claim_mapping,
63
+ tenant_resolver=tenant_resolver,
61
64
  )
62
65
 
63
66
  async def dispatch(
File without changes
@@ -1,119 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: open-shield-python
3
- Version: 0.2.1
4
- Summary: Vendor-agnostic authentication and authorization enforcement SDK
5
- License-File: LICENSE
6
- Requires-Python: >=3.12
7
- Requires-Dist: cryptography>=42.0.0
8
- Requires-Dist: fastapi>=0.129.0
9
- Requires-Dist: httpx>=0.27.0
10
- Requires-Dist: pydantic-settings>=2.0.0
11
- Requires-Dist: pydantic>=2.0.0
12
- Requires-Dist: pyjwt>=2.8.0
13
- Description-Content-Type: text/markdown
14
-
15
- # Open Shield Python SDK
16
-
17
- [![CI](https://github.com/prayog-ai-labs/open-shield-python/actions/workflows/ci.yml/badge.svg)](https://github.com/prayog-ai-labs/open-shield-python/actions/workflows/ci.yml)
18
-
19
- Vendor-agnostic authentication and authorization enforcement SDK for Python.
20
-
21
- Open Shield allows you to enforce authentication (AuthN) and authorization (AuthZ) in your Python applications without tightly coupling your code to a specific identity provider (like Auth0, Keycloak, or Cognito).
22
-
23
- ## Features
24
-
25
- - **Vendor Neutral**: Works with any OIDC-compliant provider.
26
- - **Framework Agnostic**: Core logic is pure Python; first-class support for **FastAPI**.
27
- - **Clean Architecture**: Domain logic is isolated from infrastructure concerns.
28
- - **Type Safe**: Fully typed and checked with `mypy`.
29
- - **Automatic JWKS Rotation**: Fetches and caches keys from your provider's OIDC discovery endpoint.
30
-
31
- ## Installation
32
-
33
- ```bash
34
- pip install open-shield-python
35
- ```
36
-
37
- ## Quick Start (FastAPI)
38
-
39
- 1. **Configure Environment**
40
-
41
- Set the following environment variables:
42
-
43
- ```bash
44
- OPEN_SHIELD_ISSUER_URL=https://your-auth-domain.com/realms/myrealm
45
- OPEN_SHIELD_AUDIENCE=my-api-identifier
46
- ```
47
-
48
- 2. **Add Middleware**
49
-
50
- ```python
51
- from fastapi import FastAPI, Depends
52
- from open_shield.api.fastapi import OpenShieldMiddleware, get_user_context, RequireScope, RequireRole
53
- from open_shield.adapters import OpenShieldConfig
54
- from open_shield.domain.entities import UserContext
55
-
56
- app = FastAPI()
57
-
58
- # Load config from environment
59
- config = OpenShieldConfig()
60
-
61
- # Add global authentication middleware
62
- app.add_middleware(OpenShieldMiddleware, config=config)
63
-
64
- # Public route (excluded by default: /docs, /openapi.json, /redoc, /health)
65
- @app.get("/health")
66
- def health():
67
- return {"status": "ok"}
68
-
69
- # Protected route (Authentication required)
70
- @app.get("/users/me")
71
- def read_current_user(context: UserContext = Depends(get_user_context)):
72
- return {
73
- "id": context.user.id,
74
- "email": context.user.email,
75
- "roles": context.user.roles
76
- }
77
-
78
- # Scoped route (Authorization required)
79
- @app.get("/admin/dashboard")
80
- def admin_dashboard(context: UserContext = Depends(RequireScope("read:admin"))):
81
- return {"data": "secret admin data"}
82
-
83
- # Role-based route
84
- @app.get("/manager/reports")
85
- def reports(context: UserContext = Depends(RequireRole(["manager", "admin"]))):
86
- return {"reports": []}
87
- ```
88
-
89
- ## Architecture
90
-
91
- This SDK follows **Clean Architecture** principles:
92
-
93
- - **Domain Layer**: Pure Python logic, entities, and interfaces (Ports). Zero external dependencies.
94
- - **Adapters Layer**: Concrete implementations of Ports (e.g., `PyJWT` for validation, `httpx` for JWKS).
95
- - **API Layer**: Framework specific glue code (e.g., FastAPI Middleware).
96
-
97
- ## configuration
98
-
99
- | Environment Variable | Description | Default |
100
- |----------------------|-------------|---------|
101
- | `OPEN_SHIELD_ISSUER_URL` | OIDC Issuer URL (required) | - |
102
- | `OPEN_SHIELD_AUDIENCE` | Expected audience (`aud` claim) | None |
103
- | `OPEN_SHIELD_ALGORITHMS` | Allowed signing algorithms | `["RS256"]` |
104
- | `OPEN_SHIELD_REQUIRE_SCOPES` | Enforce scope presence | `True` |
105
-
106
- ## Development
107
-
108
- This project uses `uv` for dependency management.
109
-
110
- ```bash
111
- # Install dependencies
112
- uv sync
113
-
114
- # Run tests
115
- uv run pytest
116
-
117
- # Lint and Format
118
- uv run ruff check .
119
- ```
@@ -1,105 +0,0 @@
1
- # Open Shield Python SDK
2
-
3
- [![CI](https://github.com/prayog-ai-labs/open-shield-python/actions/workflows/ci.yml/badge.svg)](https://github.com/prayog-ai-labs/open-shield-python/actions/workflows/ci.yml)
4
-
5
- Vendor-agnostic authentication and authorization enforcement SDK for Python.
6
-
7
- Open Shield allows you to enforce authentication (AuthN) and authorization (AuthZ) in your Python applications without tightly coupling your code to a specific identity provider (like Auth0, Keycloak, or Cognito).
8
-
9
- ## Features
10
-
11
- - **Vendor Neutral**: Works with any OIDC-compliant provider.
12
- - **Framework Agnostic**: Core logic is pure Python; first-class support for **FastAPI**.
13
- - **Clean Architecture**: Domain logic is isolated from infrastructure concerns.
14
- - **Type Safe**: Fully typed and checked with `mypy`.
15
- - **Automatic JWKS Rotation**: Fetches and caches keys from your provider's OIDC discovery endpoint.
16
-
17
- ## Installation
18
-
19
- ```bash
20
- pip install open-shield-python
21
- ```
22
-
23
- ## Quick Start (FastAPI)
24
-
25
- 1. **Configure Environment**
26
-
27
- Set the following environment variables:
28
-
29
- ```bash
30
- OPEN_SHIELD_ISSUER_URL=https://your-auth-domain.com/realms/myrealm
31
- OPEN_SHIELD_AUDIENCE=my-api-identifier
32
- ```
33
-
34
- 2. **Add Middleware**
35
-
36
- ```python
37
- from fastapi import FastAPI, Depends
38
- from open_shield.api.fastapi import OpenShieldMiddleware, get_user_context, RequireScope, RequireRole
39
- from open_shield.adapters import OpenShieldConfig
40
- from open_shield.domain.entities import UserContext
41
-
42
- app = FastAPI()
43
-
44
- # Load config from environment
45
- config = OpenShieldConfig()
46
-
47
- # Add global authentication middleware
48
- app.add_middleware(OpenShieldMiddleware, config=config)
49
-
50
- # Public route (excluded by default: /docs, /openapi.json, /redoc, /health)
51
- @app.get("/health")
52
- def health():
53
- return {"status": "ok"}
54
-
55
- # Protected route (Authentication required)
56
- @app.get("/users/me")
57
- def read_current_user(context: UserContext = Depends(get_user_context)):
58
- return {
59
- "id": context.user.id,
60
- "email": context.user.email,
61
- "roles": context.user.roles
62
- }
63
-
64
- # Scoped route (Authorization required)
65
- @app.get("/admin/dashboard")
66
- def admin_dashboard(context: UserContext = Depends(RequireScope("read:admin"))):
67
- return {"data": "secret admin data"}
68
-
69
- # Role-based route
70
- @app.get("/manager/reports")
71
- def reports(context: UserContext = Depends(RequireRole(["manager", "admin"]))):
72
- return {"reports": []}
73
- ```
74
-
75
- ## Architecture
76
-
77
- This SDK follows **Clean Architecture** principles:
78
-
79
- - **Domain Layer**: Pure Python logic, entities, and interfaces (Ports). Zero external dependencies.
80
- - **Adapters Layer**: Concrete implementations of Ports (e.g., `PyJWT` for validation, `httpx` for JWKS).
81
- - **API Layer**: Framework specific glue code (e.g., FastAPI Middleware).
82
-
83
- ## configuration
84
-
85
- | Environment Variable | Description | Default |
86
- |----------------------|-------------|---------|
87
- | `OPEN_SHIELD_ISSUER_URL` | OIDC Issuer URL (required) | - |
88
- | `OPEN_SHIELD_AUDIENCE` | Expected audience (`aud` claim) | None |
89
- | `OPEN_SHIELD_ALGORITHMS` | Allowed signing algorithms | `["RS256"]` |
90
- | `OPEN_SHIELD_REQUIRE_SCOPES` | Enforce scope presence | `True` |
91
-
92
- ## Development
93
-
94
- This project uses `uv` for dependency management.
95
-
96
- ```bash
97
- # Install dependencies
98
- uv sync
99
-
100
- # Run tests
101
- uv run pytest
102
-
103
- # Lint and Format
104
- uv run ruff check .
105
- ```