rampart-python 0.1.0__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,72 @@
|
|
|
1
|
+
# Binaries
|
|
2
|
+
bin/
|
|
3
|
+
*.exe
|
|
4
|
+
*.exe~
|
|
5
|
+
*.dll
|
|
6
|
+
*.so
|
|
7
|
+
*.dylib
|
|
8
|
+
|
|
9
|
+
# Test
|
|
10
|
+
*.test
|
|
11
|
+
*.out
|
|
12
|
+
coverage.out
|
|
13
|
+
coverage.txt
|
|
14
|
+
coverage.html
|
|
15
|
+
|
|
16
|
+
# Go
|
|
17
|
+
vendor/
|
|
18
|
+
|
|
19
|
+
# IDE
|
|
20
|
+
.idea/
|
|
21
|
+
.vscode/
|
|
22
|
+
*.swp
|
|
23
|
+
*.swo
|
|
24
|
+
*~
|
|
25
|
+
|
|
26
|
+
# OS
|
|
27
|
+
.DS_Store
|
|
28
|
+
Thumbs.db
|
|
29
|
+
|
|
30
|
+
# Environment
|
|
31
|
+
.env
|
|
32
|
+
.env.local
|
|
33
|
+
.env.*.local
|
|
34
|
+
|
|
35
|
+
# Node (UI)
|
|
36
|
+
node_modules/
|
|
37
|
+
package-lock.json
|
|
38
|
+
.next/
|
|
39
|
+
dist/
|
|
40
|
+
build/
|
|
41
|
+
adapters/**/dist/
|
|
42
|
+
samples/**/node_modules/
|
|
43
|
+
samples/**/dist/
|
|
44
|
+
|
|
45
|
+
# Signing keys
|
|
46
|
+
*.pem
|
|
47
|
+
|
|
48
|
+
# Vite cache
|
|
49
|
+
.vite/
|
|
50
|
+
*/.vite/
|
|
51
|
+
|
|
52
|
+
# Playwright MCP
|
|
53
|
+
.playwright-mcp/
|
|
54
|
+
|
|
55
|
+
# Claude Code
|
|
56
|
+
CLAUDE.md
|
|
57
|
+
.claude/
|
|
58
|
+
.mcp.json
|
|
59
|
+
|
|
60
|
+
# Internal plans (local only)
|
|
61
|
+
plans/
|
|
62
|
+
|
|
63
|
+
# Screenshots and snapshots (dev testing artifacts)
|
|
64
|
+
*.png
|
|
65
|
+
!docs/screenshots/*.png
|
|
66
|
+
repo-snapshot.md
|
|
67
|
+
SECURITY_AUDIT.md
|
|
68
|
+
|
|
69
|
+
# Docker
|
|
70
|
+
docker-compose.override.yml
|
|
71
|
+
firebase-debug.log
|
|
72
|
+
/rampart
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Mani Movassagh
|
|
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,153 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rampart-python
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python middleware adapter for Rampart IAM — JWT verification for FastAPI and Flask
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Requires-Dist: cryptography>=41.0.0
|
|
9
|
+
Requires-Dist: pyjwt>=2.8.0
|
|
10
|
+
Requires-Dist: requests>=2.31.0
|
|
11
|
+
Provides-Extra: dev
|
|
12
|
+
Requires-Dist: pytest-asyncio>=0.21.0; extra == 'dev'
|
|
13
|
+
Requires-Dist: pytest>=7.0.0; extra == 'dev'
|
|
14
|
+
Requires-Dist: responses>=0.23.0; extra == 'dev'
|
|
15
|
+
Provides-Extra: fastapi
|
|
16
|
+
Requires-Dist: fastapi>=0.100.0; extra == 'fastapi'
|
|
17
|
+
Provides-Extra: flask
|
|
18
|
+
Requires-Dist: flask>=2.3.0; extra == 'flask'
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# Rampart Python Middleware
|
|
22
|
+
|
|
23
|
+
JWT verification middleware for [Rampart](https://github.com/manimovassagh/rampart) IAM server. Supports **FastAPI** and **Flask**.
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
# Core (PyJWT + cryptography)
|
|
29
|
+
pip install rampart-python
|
|
30
|
+
|
|
31
|
+
# With FastAPI support
|
|
32
|
+
pip install rampart-python[fastapi]
|
|
33
|
+
|
|
34
|
+
# With Flask support
|
|
35
|
+
pip install rampart-python[flask]
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## FastAPI
|
|
39
|
+
|
|
40
|
+
### Basic Authentication
|
|
41
|
+
|
|
42
|
+
```python
|
|
43
|
+
from fastapi import Depends, FastAPI
|
|
44
|
+
from rampart import RampartClaims
|
|
45
|
+
from rampart.fastapi import rampart_auth
|
|
46
|
+
|
|
47
|
+
app = FastAPI()
|
|
48
|
+
auth = rampart_auth("https://auth.example.com")
|
|
49
|
+
|
|
50
|
+
@app.get("/me")
|
|
51
|
+
async def me(claims: RampartClaims = Depends(auth)):
|
|
52
|
+
return {
|
|
53
|
+
"user_id": claims.sub,
|
|
54
|
+
"email": claims.email,
|
|
55
|
+
"roles": claims.roles,
|
|
56
|
+
}
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Role-Based Access Control
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from rampart.fastapi import rampart_auth, require_roles_from_claims
|
|
63
|
+
|
|
64
|
+
auth = rampart_auth("https://auth.example.com")
|
|
65
|
+
check_admin = require_roles_from_claims("admin")
|
|
66
|
+
|
|
67
|
+
@app.get("/admin/users")
|
|
68
|
+
async def list_users(claims: RampartClaims = Depends(auth)):
|
|
69
|
+
check_admin(claims) # Raises 403 if "admin" role is missing
|
|
70
|
+
return {"users": ["..."]}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Flask
|
|
74
|
+
|
|
75
|
+
### Basic Authentication
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
from flask import Flask, g
|
|
79
|
+
from rampart.flask import rampart_auth
|
|
80
|
+
|
|
81
|
+
app = Flask(__name__)
|
|
82
|
+
|
|
83
|
+
@app.route("/me")
|
|
84
|
+
@rampart_auth("https://auth.example.com")
|
|
85
|
+
def me():
|
|
86
|
+
return {
|
|
87
|
+
"user_id": g.auth.sub,
|
|
88
|
+
"email": g.auth.email,
|
|
89
|
+
"roles": g.auth.roles,
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### Role-Based Access Control
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
from rampart.flask import rampart_auth, require_roles
|
|
97
|
+
|
|
98
|
+
@app.route("/admin/users")
|
|
99
|
+
@rampart_auth("https://auth.example.com")
|
|
100
|
+
@require_roles("admin")
|
|
101
|
+
def list_users():
|
|
102
|
+
return {"users": ["..."]}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Direct Usage (No Framework)
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
from rampart import RampartAuth
|
|
109
|
+
|
|
110
|
+
auth = RampartAuth(issuer="https://auth.example.com")
|
|
111
|
+
claims = auth.verify_token(raw_jwt_string)
|
|
112
|
+
|
|
113
|
+
print(claims.sub) # "user-123"
|
|
114
|
+
print(claims.email) # "user@example.com"
|
|
115
|
+
print(claims.roles) # ["admin", "user"]
|
|
116
|
+
print(claims.org_id) # "org-456"
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## Claims
|
|
120
|
+
|
|
121
|
+
Verified tokens return a `RampartClaims` dataclass:
|
|
122
|
+
|
|
123
|
+
| Field | Type | Description |
|
|
124
|
+
|----------------------|----------------|--------------------------------|
|
|
125
|
+
| `sub` | `str` | Subject (user ID) |
|
|
126
|
+
| `iss` | `str` | Issuer URL |
|
|
127
|
+
| `iat` | `int` | Issued-at timestamp |
|
|
128
|
+
| `exp` | `int` | Expiration timestamp |
|
|
129
|
+
| `org_id` | `str | None` | Organization / tenant ID |
|
|
130
|
+
| `preferred_username` | `str | None` | Username |
|
|
131
|
+
| `email` | `str | None` | Email address |
|
|
132
|
+
| `email_verified` | `bool | None` | Whether email is verified |
|
|
133
|
+
| `given_name` | `str | None` | First name |
|
|
134
|
+
| `family_name` | `str | None` | Last name |
|
|
135
|
+
| `roles` | `list[str]` | Assigned roles |
|
|
136
|
+
|
|
137
|
+
## Configuration Options
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
RampartAuth(
|
|
141
|
+
issuer="https://auth.example.com", # Required: Rampart server URL
|
|
142
|
+
audience="my-api", # Optional: expected audience claim
|
|
143
|
+
jwks_cache_ttl=300, # JWKS cache lifetime in seconds (default: 300)
|
|
144
|
+
algorithms=["RS256"], # Allowed JWT algorithms (default: ["RS256"])
|
|
145
|
+
)
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## Running Tests
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
pip install -e ".[dev]"
|
|
152
|
+
pytest tests/
|
|
153
|
+
```
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
# Rampart Python Middleware
|
|
2
|
+
|
|
3
|
+
JWT verification middleware for [Rampart](https://github.com/manimovassagh/rampart) IAM server. Supports **FastAPI** and **Flask**.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
# Core (PyJWT + cryptography)
|
|
9
|
+
pip install rampart-python
|
|
10
|
+
|
|
11
|
+
# With FastAPI support
|
|
12
|
+
pip install rampart-python[fastapi]
|
|
13
|
+
|
|
14
|
+
# With Flask support
|
|
15
|
+
pip install rampart-python[flask]
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## FastAPI
|
|
19
|
+
|
|
20
|
+
### Basic Authentication
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
from fastapi import Depends, FastAPI
|
|
24
|
+
from rampart import RampartClaims
|
|
25
|
+
from rampart.fastapi import rampart_auth
|
|
26
|
+
|
|
27
|
+
app = FastAPI()
|
|
28
|
+
auth = rampart_auth("https://auth.example.com")
|
|
29
|
+
|
|
30
|
+
@app.get("/me")
|
|
31
|
+
async def me(claims: RampartClaims = Depends(auth)):
|
|
32
|
+
return {
|
|
33
|
+
"user_id": claims.sub,
|
|
34
|
+
"email": claims.email,
|
|
35
|
+
"roles": claims.roles,
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Role-Based Access Control
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from rampart.fastapi import rampart_auth, require_roles_from_claims
|
|
43
|
+
|
|
44
|
+
auth = rampart_auth("https://auth.example.com")
|
|
45
|
+
check_admin = require_roles_from_claims("admin")
|
|
46
|
+
|
|
47
|
+
@app.get("/admin/users")
|
|
48
|
+
async def list_users(claims: RampartClaims = Depends(auth)):
|
|
49
|
+
check_admin(claims) # Raises 403 if "admin" role is missing
|
|
50
|
+
return {"users": ["..."]}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## Flask
|
|
54
|
+
|
|
55
|
+
### Basic Authentication
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from flask import Flask, g
|
|
59
|
+
from rampart.flask import rampart_auth
|
|
60
|
+
|
|
61
|
+
app = Flask(__name__)
|
|
62
|
+
|
|
63
|
+
@app.route("/me")
|
|
64
|
+
@rampart_auth("https://auth.example.com")
|
|
65
|
+
def me():
|
|
66
|
+
return {
|
|
67
|
+
"user_id": g.auth.sub,
|
|
68
|
+
"email": g.auth.email,
|
|
69
|
+
"roles": g.auth.roles,
|
|
70
|
+
}
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Role-Based Access Control
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
from rampart.flask import rampart_auth, require_roles
|
|
77
|
+
|
|
78
|
+
@app.route("/admin/users")
|
|
79
|
+
@rampart_auth("https://auth.example.com")
|
|
80
|
+
@require_roles("admin")
|
|
81
|
+
def list_users():
|
|
82
|
+
return {"users": ["..."]}
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## Direct Usage (No Framework)
|
|
86
|
+
|
|
87
|
+
```python
|
|
88
|
+
from rampart import RampartAuth
|
|
89
|
+
|
|
90
|
+
auth = RampartAuth(issuer="https://auth.example.com")
|
|
91
|
+
claims = auth.verify_token(raw_jwt_string)
|
|
92
|
+
|
|
93
|
+
print(claims.sub) # "user-123"
|
|
94
|
+
print(claims.email) # "user@example.com"
|
|
95
|
+
print(claims.roles) # ["admin", "user"]
|
|
96
|
+
print(claims.org_id) # "org-456"
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## Claims
|
|
100
|
+
|
|
101
|
+
Verified tokens return a `RampartClaims` dataclass:
|
|
102
|
+
|
|
103
|
+
| Field | Type | Description |
|
|
104
|
+
|----------------------|----------------|--------------------------------|
|
|
105
|
+
| `sub` | `str` | Subject (user ID) |
|
|
106
|
+
| `iss` | `str` | Issuer URL |
|
|
107
|
+
| `iat` | `int` | Issued-at timestamp |
|
|
108
|
+
| `exp` | `int` | Expiration timestamp |
|
|
109
|
+
| `org_id` | `str | None` | Organization / tenant ID |
|
|
110
|
+
| `preferred_username` | `str | None` | Username |
|
|
111
|
+
| `email` | `str | None` | Email address |
|
|
112
|
+
| `email_verified` | `bool | None` | Whether email is verified |
|
|
113
|
+
| `given_name` | `str | None` | First name |
|
|
114
|
+
| `family_name` | `str | None` | Last name |
|
|
115
|
+
| `roles` | `list[str]` | Assigned roles |
|
|
116
|
+
|
|
117
|
+
## Configuration Options
|
|
118
|
+
|
|
119
|
+
```python
|
|
120
|
+
RampartAuth(
|
|
121
|
+
issuer="https://auth.example.com", # Required: Rampart server URL
|
|
122
|
+
audience="my-api", # Optional: expected audience claim
|
|
123
|
+
jwks_cache_ttl=300, # JWKS cache lifetime in seconds (default: 300)
|
|
124
|
+
algorithms=["RS256"], # Allowed JWT algorithms (default: ["RS256"])
|
|
125
|
+
)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## Running Tests
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
pip install -e ".[dev]"
|
|
132
|
+
pytest tests/
|
|
133
|
+
```
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.backends"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "rampart-python"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python middleware adapter for Rampart IAM — JWT verification for FastAPI and Flask"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
dependencies = [
|
|
13
|
+
"PyJWT>=2.8.0",
|
|
14
|
+
"cryptography>=41.0.0",
|
|
15
|
+
"requests>=2.31.0",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
[project.optional-dependencies]
|
|
19
|
+
fastapi = ["fastapi>=0.100.0"]
|
|
20
|
+
flask = ["flask>=2.3.0"]
|
|
21
|
+
dev = [
|
|
22
|
+
"pytest>=7.0.0",
|
|
23
|
+
"pytest-asyncio>=0.21.0",
|
|
24
|
+
"responses>=0.23.0",
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
[tool.hatch.build.targets.wheel]
|
|
28
|
+
packages = ["rampart"]
|
|
File without changes
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
"""Tests for Rampart Python middleware."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import time
|
|
7
|
+
from dataclasses import asdict
|
|
8
|
+
from typing import Any, Dict
|
|
9
|
+
|
|
10
|
+
import jwt as pyjwt
|
|
11
|
+
import pytest
|
|
12
|
+
from cryptography.hazmat.primitives import serialization
|
|
13
|
+
from cryptography.hazmat.primitives.asymmetric import rsa
|
|
14
|
+
|
|
15
|
+
from rampart.middleware import RampartAuth, RampartClaims
|
|
16
|
+
|
|
17
|
+
# ---------------------------------------------------------------------------
|
|
18
|
+
# Helpers: generate RSA keys and JWKS for testing
|
|
19
|
+
# ---------------------------------------------------------------------------
|
|
20
|
+
|
|
21
|
+
ISSUER = "https://auth.example.com"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _generate_rsa_keypair():
|
|
25
|
+
"""Generate an RSA private key and its public key."""
|
|
26
|
+
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
27
|
+
return private_key
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _private_key_pem(private_key) -> bytes:
|
|
31
|
+
return private_key.private_bytes(
|
|
32
|
+
encoding=serialization.Encoding.PEM,
|
|
33
|
+
format=serialization.PrivateFormat.PKCS8,
|
|
34
|
+
encryption_algorithm=serialization.NoEncryption(),
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _build_jwks_response(private_key) -> Dict[str, Any]:
|
|
39
|
+
"""Build a JWKS JSON response from an RSA private key."""
|
|
40
|
+
from jwt.algorithms import RSAAlgorithm
|
|
41
|
+
|
|
42
|
+
public_key = private_key.public_key()
|
|
43
|
+
jwk_dict = json.loads(RSAAlgorithm.to_jwk(public_key))
|
|
44
|
+
jwk_dict["kid"] = "test-key-1"
|
|
45
|
+
jwk_dict["use"] = "sig"
|
|
46
|
+
jwk_dict["alg"] = "RS256"
|
|
47
|
+
return {"keys": [jwk_dict]}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _sign_token(private_key, claims: Dict[str, Any]) -> str:
|
|
51
|
+
"""Sign a JWT with the given private key."""
|
|
52
|
+
return pyjwt.encode(
|
|
53
|
+
claims,
|
|
54
|
+
_private_key_pem(private_key),
|
|
55
|
+
algorithm="RS256",
|
|
56
|
+
headers={"kid": "test-key-1"},
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
# ---------------------------------------------------------------------------
|
|
61
|
+
# Fixtures
|
|
62
|
+
# ---------------------------------------------------------------------------
|
|
63
|
+
|
|
64
|
+
@pytest.fixture()
|
|
65
|
+
def rsa_key():
|
|
66
|
+
return _generate_rsa_keypair()
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@pytest.fixture()
|
|
70
|
+
def jwks_json(rsa_key):
|
|
71
|
+
return _build_jwks_response(rsa_key)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@pytest.fixture()
|
|
75
|
+
def valid_claims() -> Dict[str, Any]:
|
|
76
|
+
now = int(time.time())
|
|
77
|
+
return {
|
|
78
|
+
"sub": "user-123",
|
|
79
|
+
"iss": ISSUER,
|
|
80
|
+
"iat": now,
|
|
81
|
+
"exp": now + 3600,
|
|
82
|
+
"org_id": "org-456",
|
|
83
|
+
"preferred_username": "jdoe",
|
|
84
|
+
"email": "jdoe@example.com",
|
|
85
|
+
"email_verified": True,
|
|
86
|
+
"given_name": "Jane",
|
|
87
|
+
"family_name": "Doe",
|
|
88
|
+
"roles": ["admin", "user"],
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
# ---------------------------------------------------------------------------
|
|
93
|
+
# Unit tests for RampartClaims
|
|
94
|
+
# ---------------------------------------------------------------------------
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class TestRampartClaims:
|
|
98
|
+
def test_defaults(self):
|
|
99
|
+
claims = RampartClaims(sub="u1", iss=ISSUER, iat=0, exp=0)
|
|
100
|
+
assert claims.roles == []
|
|
101
|
+
assert claims.org_id is None
|
|
102
|
+
assert claims.email is None
|
|
103
|
+
|
|
104
|
+
def test_full_claims(self, valid_claims):
|
|
105
|
+
claims = RampartClaims(**valid_claims)
|
|
106
|
+
assert claims.sub == "user-123"
|
|
107
|
+
assert claims.roles == ["admin", "user"]
|
|
108
|
+
assert claims.email_verified is True
|
|
109
|
+
|
|
110
|
+
def test_asdict(self, valid_claims):
|
|
111
|
+
claims = RampartClaims(**valid_claims)
|
|
112
|
+
d = asdict(claims)
|
|
113
|
+
assert d["sub"] == "user-123"
|
|
114
|
+
assert isinstance(d["roles"], list)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
# ---------------------------------------------------------------------------
|
|
118
|
+
# Unit tests for RampartAuth.verify_token
|
|
119
|
+
# ---------------------------------------------------------------------------
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
class TestRampartAuthVerifyToken:
|
|
123
|
+
def test_verify_valid_token(self, rsa_key, jwks_json, valid_claims, responses_mock):
|
|
124
|
+
"""A correctly signed token with valid claims should verify successfully."""
|
|
125
|
+
responses_mock.get(
|
|
126
|
+
f"{ISSUER}/.well-known/jwks.json",
|
|
127
|
+
json=jwks_json,
|
|
128
|
+
)
|
|
129
|
+
auth = RampartAuth(issuer=ISSUER)
|
|
130
|
+
token = _sign_token(rsa_key, valid_claims)
|
|
131
|
+
result = auth.verify_token(token)
|
|
132
|
+
|
|
133
|
+
assert result.sub == "user-123"
|
|
134
|
+
assert result.iss == ISSUER
|
|
135
|
+
assert result.roles == ["admin", "user"]
|
|
136
|
+
assert result.email == "jdoe@example.com"
|
|
137
|
+
|
|
138
|
+
def test_expired_token_raises(self, rsa_key, jwks_json, valid_claims, responses_mock):
|
|
139
|
+
"""An expired token should raise ExpiredSignatureError."""
|
|
140
|
+
responses_mock.get(f"{ISSUER}/.well-known/jwks.json", json=jwks_json)
|
|
141
|
+
auth = RampartAuth(issuer=ISSUER)
|
|
142
|
+
|
|
143
|
+
valid_claims["exp"] = int(time.time()) - 3600
|
|
144
|
+
token = _sign_token(rsa_key, valid_claims)
|
|
145
|
+
|
|
146
|
+
with pytest.raises(pyjwt.ExpiredSignatureError):
|
|
147
|
+
auth.verify_token(token)
|
|
148
|
+
|
|
149
|
+
def test_wrong_issuer_raises(self, rsa_key, jwks_json, valid_claims, responses_mock):
|
|
150
|
+
"""A token with a different issuer should be rejected."""
|
|
151
|
+
responses_mock.get(f"{ISSUER}/.well-known/jwks.json", json=jwks_json)
|
|
152
|
+
auth = RampartAuth(issuer=ISSUER)
|
|
153
|
+
|
|
154
|
+
valid_claims["iss"] = "https://evil.example.com"
|
|
155
|
+
token = _sign_token(rsa_key, valid_claims)
|
|
156
|
+
|
|
157
|
+
with pytest.raises(pyjwt.InvalidIssuerError):
|
|
158
|
+
auth.verify_token(token)
|
|
159
|
+
|
|
160
|
+
def test_roles_as_string_normalized(self, rsa_key, jwks_json, valid_claims, responses_mock):
|
|
161
|
+
"""If roles is a single string, it should be wrapped in a list."""
|
|
162
|
+
responses_mock.get(f"{ISSUER}/.well-known/jwks.json", json=jwks_json)
|
|
163
|
+
auth = RampartAuth(issuer=ISSUER)
|
|
164
|
+
|
|
165
|
+
valid_claims["roles"] = "admin"
|
|
166
|
+
token = _sign_token(rsa_key, valid_claims)
|
|
167
|
+
result = auth.verify_token(token)
|
|
168
|
+
|
|
169
|
+
assert result.roles == ["admin"]
|
|
170
|
+
|
|
171
|
+
def test_missing_optional_claims(self, rsa_key, jwks_json, responses_mock):
|
|
172
|
+
"""Tokens without optional claims should still verify."""
|
|
173
|
+
responses_mock.get(f"{ISSUER}/.well-known/jwks.json", json=jwks_json)
|
|
174
|
+
auth = RampartAuth(issuer=ISSUER)
|
|
175
|
+
|
|
176
|
+
now = int(time.time())
|
|
177
|
+
minimal_claims = {
|
|
178
|
+
"sub": "user-minimal",
|
|
179
|
+
"iss": ISSUER,
|
|
180
|
+
"iat": now,
|
|
181
|
+
"exp": now + 3600,
|
|
182
|
+
}
|
|
183
|
+
token = _sign_token(rsa_key, minimal_claims)
|
|
184
|
+
result = auth.verify_token(token)
|
|
185
|
+
|
|
186
|
+
assert result.sub == "user-minimal"
|
|
187
|
+
assert result.roles == []
|
|
188
|
+
assert result.email is None
|
|
189
|
+
assert result.org_id is None
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# ---------------------------------------------------------------------------
|
|
193
|
+
# Pytest fixture for `responses` library
|
|
194
|
+
# ---------------------------------------------------------------------------
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
@pytest.fixture()
|
|
198
|
+
def responses_mock():
|
|
199
|
+
"""Activate the responses library to mock HTTP requests."""
|
|
200
|
+
import responses
|
|
201
|
+
|
|
202
|
+
with responses.RequestsMock() as rsps:
|
|
203
|
+
yield rsps
|