ab-token-validator 0.1.1__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.
@@ -0,0 +1,195 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # UV
98
+ # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ uv.lock
102
+
103
+ # poetry
104
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
105
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
106
+ # commonly ignored for libraries.
107
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
108
+ #poetry.lock
109
+ #poetry.toml
110
+
111
+ # pdm
112
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
113
+ #pdm.lock
114
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
115
+ # in version control.
116
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
117
+ .pdm.toml
118
+ .pdm-python
119
+ .pdm-build/
120
+
121
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
122
+ __pypackages__/
123
+
124
+ # Celery stuff
125
+ celerybeat-schedule
126
+ celerybeat.pid
127
+
128
+ # SageMath parsed files
129
+ *.sage.py
130
+
131
+ # Environments
132
+ .env
133
+ .venv
134
+ env/
135
+ venv/
136
+ ENV/
137
+ env.bak/
138
+ venv.bak/
139
+
140
+ # Spyder project settings
141
+ .spyderproject
142
+ .spyproject
143
+
144
+ # Rope project settings
145
+ .ropeproject
146
+
147
+ # mkdocs documentation
148
+ /site
149
+
150
+ # mypy
151
+ .mypy_cache/
152
+ .dmypy.json
153
+ dmypy.json
154
+
155
+ # Pyre type checker
156
+ .pyre/
157
+
158
+ # pytype static type analyzer
159
+ .pytype/
160
+
161
+ # Cython debug symbols
162
+ cython_debug/
163
+
164
+ # PyCharm
165
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
166
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
167
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
168
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
169
+ #.idea/
170
+
171
+ # Abstra
172
+ # Abstra is an AI-powered process automation framework.
173
+ # Ignore directories containing user credentials, local state, and settings.
174
+ # Learn more at https://abstra.io/docs
175
+ .abstra/
176
+
177
+ # Visual Studio Code
178
+ # Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
179
+ # that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
180
+ # and can be added to the global gitignore or merged into this file. However, if you prefer,
181
+ # you could uncomment the following to ignore the entire vscode folder
182
+ # .vscode/
183
+
184
+ # Ruff stuff:
185
+ .ruff_cache/
186
+
187
+ # PyPI configuration file
188
+ .pypirc
189
+
190
+ # Cursor
191
+ # Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to
192
+ # exclude from AI features like autocomplete and code analysis. Recommended for sensitive data
193
+ # refer to https://docs.cursor.com/context/ignore-files
194
+ .cursorignore
195
+ .cursorindexingignore
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Matthew Coulter
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.4
2
+ Name: ab-token-validator
3
+ Version: 0.1.1
4
+ Author-email: Matthew Coulter <53892067+mattcoulter7@users.noreply.github.com>
5
+ License-File: LICENSE
6
+ Requires-Python: <4,>=3.12
7
+ Requires-Dist: ab-dependency
8
+ Requires-Dist: aiocache<0.13,>=0.12.3
9
+ Requires-Dist: fastapi<0.116,>=0.115.14
10
+ Requires-Dist: httpx<0.29,>=0.28.1
11
+ Requires-Dist: pydantic<3,>=2.11.7
12
+ Requires-Dist: python-jose[cryptography]<4,>=3.5.0
13
+ Requires-Dist: uuid7<0.2,>=0.1.0
14
+ Requires-Dist: yarl<2,>=1.20.1
15
+ Description-Content-Type: text/markdown
16
+
17
+ # Open Banking, Opened | FastAPI Token Validator
18
+
19
+ FastAPI Token Validator Package for Open Banking, Opened API packages.
@@ -0,0 +1,3 @@
1
+ # Open Banking, Opened | FastAPI Token Validator
2
+
3
+ FastAPI Token Validator Package for Open Banking, Opened API packages.
@@ -0,0 +1,78 @@
1
+ [build-system]
2
+ build-backend = "hatchling.build"
3
+ requires = ["hatchling"]
4
+
5
+ [dependency-groups]
6
+ dev = [
7
+ "debugpy>=1.8.14,<2",
8
+ "isort>=6.0.1,<7",
9
+ "ab-test-fixtures",
10
+ "pre-commit>=4.2.0,<5",
11
+ "pytest-asyncio>=1.0.0,<2",
12
+ "pytest-cov>=6.2.1,<7",
13
+ "pytest>=8.4.1,<9",
14
+ "ruff>=0.12.3,<0.13",
15
+ "tox>=4.27.0,<5"
16
+ ]
17
+
18
+ [project]
19
+ authors = [{email = "53892067+mattcoulter7@users.noreply.github.com", name = "Matthew Coulter"}]
20
+ dependencies = [
21
+ "aiocache>=0.12.3,<0.13",
22
+ "fastapi>=0.115.14,<0.116",
23
+ "httpx>=0.28.1,<0.29",
24
+ "ab-dependency",
25
+ "pydantic>=2.11.7,<3",
26
+ "python-jose[cryptography]>=3.5.0,<4",
27
+ "uuid7>=0.1.0,<0.2",
28
+ "yarl>=1.20.1,<2"
29
+ ]
30
+ description = ""
31
+ name = "ab-token-validator"
32
+ readme = "README.md"
33
+ requires-python = ">=3.12, <4"
34
+ version = "0.1.1"
35
+
36
+ [tool.uv.sources]
37
+ ab-dependency = { git = "https://@github.com/auth-broker/package-dependency", tag= "0.1.2" }
38
+ ab-test-fixtures = { git = "https://@github.com/auth-broker/package-test-fixtures", tag= "0.1.1" }
39
+
40
+ [tool.hatch.build.targets.sdist]
41
+ include = ["src/ab_core"]
42
+
43
+ [tool.hatch.build.targets.wheel]
44
+ include = ["src/ab_core"]
45
+
46
+ [tool.hatch.build.targets.wheel.sources]
47
+ "src/ab_core" = "ab_core"
48
+
49
+ [tool.pytest.ini_options]
50
+ asyncio_default_fixture_loop_scope = "session"
51
+ asyncio_mode = "auto"
52
+ markers = [
53
+ "integration: Assigns the test to the integration test suite.",
54
+ "regression: Assigns the test to the regression test suite"
55
+ ]
56
+
57
+ [tool.ruff]
58
+ line-length = 120
59
+ src = ["src"]
60
+ target-version = "py312"
61
+
62
+ [tool.ruff.lint]
63
+ exclude = [".git", ".venv", "__pycache__", "proto"]
64
+ fixable = ["ALL"]
65
+ ignore = [
66
+ "D104" # missing docstring in public package
67
+ ]
68
+ select = [
69
+ "ARG001", # unused arguments
70
+ "B", # flake8-bugbear
71
+ "C4", # flake8-comprehensions
72
+ "D", # pydocstyle (docstring checks)
73
+ "E", # pycodestyle errors
74
+ "F", # pyflakes
75
+ "I", # isort
76
+ "UP", # pyupgrade
77
+ "W" # pycodestyle warnings
78
+ ]
@@ -0,0 +1,6 @@
1
+ from enum import StrEnum
2
+
3
+
4
+ class TokenValidatorType(StrEnum):
5
+ OIDC = "OIDC"
6
+ TEMPLATE = "TEMPLATE"
@@ -0,0 +1,22 @@
1
+ from typing import List, Optional
2
+
3
+ from pydantic import BaseModel
4
+
5
+
6
+ class ValidatedOIDCClaims(BaseModel):
7
+ iss: str
8
+ sub: str
9
+ aud: str | List[str]
10
+ exp: int
11
+ iat: int
12
+ auth_time: int
13
+ acr: str
14
+
15
+ # New fields
16
+ email: Optional[str] = None
17
+ email_verified: Optional[bool] = None
18
+ name: Optional[str] = None
19
+ given_name: Optional[str] = None
20
+ preferred_username: Optional[str] = None
21
+ nickname: Optional[str] = None
22
+ groups: Optional[List[str]] = None
@@ -0,0 +1,14 @@
1
+ from typing import Annotated, Union
2
+
3
+ from pydantic import Discriminator
4
+
5
+ from .oidc import OIDCTokenValidator
6
+ from .template import TemplateTokenValidator
7
+
8
+ TokenValidator = Annotated[
9
+ Union[
10
+ OIDCTokenValidator,
11
+ TemplateTokenValidator,
12
+ ],
13
+ Discriminator("type"),
14
+ ]
@@ -0,0 +1,25 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Generic, TypeVar
3
+
4
+ from pydantic import BaseModel
5
+
6
+ ValidatedType = TypeVar("ValidatedType")
7
+
8
+
9
+ class TokenValidatorBase(BaseModel, Generic[ValidatedType], ABC):
10
+ """
11
+ Abstract base for any token validator.
12
+
13
+ Generic on the validated return type.
14
+ Also a Pydantic model, so you get:
15
+ - field validation on init
16
+ - .model_dump(), .model_json(), etc
17
+ """
18
+
19
+ @abstractmethod
20
+ async def validate(self, token: str) -> ValidatedType:
21
+ """
22
+ Validate a raw token string and return a structured result.
23
+ Should raise on failure.
24
+ """
25
+ ...
@@ -0,0 +1,52 @@
1
+ from typing import List, Literal, Sequence, Union
2
+
3
+ import httpx
4
+ from aiocache import SimpleMemoryCache, cached
5
+ from jose import JWTError, jwt
6
+ from pydantic import AnyHttpUrl, Field, HttpUrl
7
+
8
+ from ..schema.token_validator_type import TokenValidatorType
9
+ from ..schema.validated_token import ValidatedOIDCClaims
10
+ from .base import TokenValidatorBase
11
+
12
+
13
+ class OIDCTokenValidator(TokenValidatorBase[ValidatedOIDCClaims]):
14
+ """
15
+ Validates a JWT from an OIDC provider
16
+ and returns a ValidatedOIDCClaims model.
17
+ """
18
+
19
+ type: Literal[TokenValidatorType.OIDC] = TokenValidatorType.OIDC
20
+
21
+ issuer: HttpUrl
22
+ jwks_uri: AnyHttpUrl
23
+ audience: Union[str, Sequence[str]]
24
+ algorithms: List[str] = Field(default_factory=lambda: ["RS256"])
25
+
26
+ # @field_validator("audience", mode="before")
27
+ # def normalize_audience(cls, v: Union[str, Sequence[str]]) -> List[str]:
28
+ # return list(v) if isinstance(v, (list, tuple, set)) else [str(v)]
29
+
30
+ @cached(ttl=300, cache=SimpleMemoryCache)
31
+ async def _get_jwks(self) -> dict:
32
+ async with httpx.AsyncClient() as client:
33
+ resp = await client.get(self.jwks_uri.encoded_string(), timeout=5)
34
+ resp.raise_for_status()
35
+ return resp.json()
36
+
37
+ async def validate(self, token: str) -> ValidatedOIDCClaims:
38
+ jwks = await self._get_jwks()
39
+ header = jwt.get_unverified_header(token)
40
+ key = next((k for k in jwks["keys"] if k.get("kid") == header.get("kid")), None)
41
+ if key is None:
42
+ raise JWTError("No matching 'kid' found in JWKS")
43
+
44
+ claims_dict = jwt.decode(
45
+ token,
46
+ key=key,
47
+ algorithms=self.algorithms,
48
+ audience=self.audience,
49
+ issuer=str(self.issuer),
50
+ )
51
+
52
+ return ValidatedOIDCClaims.model_validate(claims_dict)
@@ -0,0 +1,17 @@
1
+ from typing import Literal
2
+
3
+ from ..schema.token_validator_type import TokenValidatorType
4
+ from ..schema.validated_token import ValidatedOIDCClaims
5
+ from .base import TokenValidatorBase
6
+
7
+
8
+ class TemplateTokenValidator(TokenValidatorBase[ValidatedOIDCClaims]):
9
+ """
10
+ Validates a JWT from an OIDC provider
11
+ and returns a ValidatedOIDCClaims model.
12
+ """
13
+
14
+ type: Literal[TokenValidatorType.TEMPLATE] = TokenValidatorType.TEMPLATE
15
+
16
+ async def validate(self, token: str) -> ValidatedOIDCClaims:
17
+ raise NotImplementedError()