shellui-django 0.2.0__tar.gz → 0.4.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.
- {shellui_django-0.2.0 → shellui_django-0.4.0}/CHANGELOG.md +27 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/PKG-INFO +6 -1
- {shellui_django-0.2.0 → shellui_django-0.4.0}/README.md +5 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/pyproject.toml +1 -1
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/__init__.py +1 -1
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/__init__.py +18 -0
- shellui_django-0.4.0/src/shellui_django/mcp/delegation.py +158 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/identity_jwks.py +12 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/internal.py +166 -43
- shellui_django-0.4.0/src/shellui_django/mcp/tests/test_delegation.py +227 -0
- shellui_django-0.4.0/src/shellui_django/mcp/tests/test_internal_assertions.py +228 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/.gitignore +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/LICENSE +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/SECURITY.md +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/decorators.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/gateway.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/masking.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/openapi_mcp.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/openapi_tools.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/rate_limit.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/resources.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/routing.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/server.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/__init__.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/mcp_routing_urlconf.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/rs256_helpers.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_gateway.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_internal_revocation.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_masking.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_openapi_tools.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_package.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_resources.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_routing.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_server_routing.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_write_gate_mcp.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/write_gate.py +0 -0
- {shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/testing/__init__.py +0 -0
|
@@ -23,6 +23,33 @@ Breaking changes bump the major version (minor while below 1.0.0), so services c
|
|
|
23
23
|
See for sample https://raw.githubusercontent.com/favoloso/conventional-changelog-emoji/master/CHANGELOG.md
|
|
24
24
|
-->
|
|
25
25
|
|
|
26
|
+
## [0.4.0] - 2026-11-04
|
|
27
|
+
|
|
28
|
+
### 🔒 Security
|
|
29
|
+
|
|
30
|
+
- Service-to-identity MCP internal assertions (`build_mcp_approval_assertion`, `build_mcp_call_log_assertion`, `build_mcp_revocation_assertion`) are signed RS256 with the caller `JWT_SIGNING_KEY` and caller issuer (`JWT_ISSUER` or SimpleJWT `ISSUER`), not SimpleJWT HMAC keys.
|
|
31
|
+
- `verify_mcp_internal_assertion` / `verify_rs256_mcp_assertion` verify RS256 against caller JWKS or PEM (`expected_issuer`, audience, scope, target, lifetime, optional `register_jti`). HS256 and `alg: none` are rejected; verification never uses a private key.
|
|
32
|
+
|
|
33
|
+
### 🚨 Changed
|
|
34
|
+
|
|
35
|
+
- `verify_mcp_internal_assertion` now requires `public_jwks_or_pem` and `expected_issuer` (breaking for Identity and other verifiers).
|
|
36
|
+
|
|
37
|
+
## [0.3.0] - 2026-11-02
|
|
38
|
+
|
|
39
|
+
### ✨ Feature
|
|
40
|
+
|
|
41
|
+
- Add `shellui_django.mcp.delegation`: RS256 helpers for gateway-to-Identity downstream MCP token mint requests (`sign_downstream_token_request`, `verify_downstream_token_request`) with shared audience and scope constants.
|
|
42
|
+
|
|
43
|
+
### 📚 Documentation
|
|
44
|
+
|
|
45
|
+
- Document downstream token delegation in `docs/mcp.md`.
|
|
46
|
+
|
|
47
|
+
## [0.2.1] - 2026-11-02
|
|
48
|
+
|
|
49
|
+
### 📚 Documentation
|
|
50
|
+
|
|
51
|
+
- Add CI, PyPI, Python and license badges to the README.
|
|
52
|
+
|
|
26
53
|
## [0.2.0] - 2026-11-02
|
|
27
54
|
|
|
28
55
|
### ✨ Feature
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: shellui-django
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.4.0
|
|
4
4
|
Summary: Shared Django libraries for Shellui services
|
|
5
5
|
Project-URL: Homepage, https://shellui.com
|
|
6
6
|
Project-URL: Source, https://github.com/shellui/django-commons
|
|
@@ -32,6 +32,11 @@ Description-Content-Type: text/markdown
|
|
|
32
32
|
|
|
33
33
|
# shellui-django
|
|
34
34
|
|
|
35
|
+
[](https://github.com/shellui/django-commons/actions/workflows/ci.yml)
|
|
36
|
+
[](https://pypi.org/project/shellui-django/)
|
|
37
|
+
[](https://pypi.org/project/shellui-django/)
|
|
38
|
+
[](LICENSE)
|
|
39
|
+
|
|
35
40
|
Shared Django libraries for [Shellui](https://shellui.com) backend services: identity, storage, hosting, email, and saas.
|
|
36
41
|
|
|
37
42
|
## Principles
|
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# shellui-django
|
|
2
2
|
|
|
3
|
+
[](https://github.com/shellui/django-commons/actions/workflows/ci.yml)
|
|
4
|
+
[](https://pypi.org/project/shellui-django/)
|
|
5
|
+
[](https://pypi.org/project/shellui-django/)
|
|
6
|
+
[](LICENSE)
|
|
7
|
+
|
|
3
8
|
Shared Django libraries for [Shellui](https://shellui.com) backend services: identity, storage, hosting, email, and saas.
|
|
4
9
|
|
|
5
10
|
## Principles
|
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
"""MCP server layer for Shellui Django services."""
|
|
2
2
|
|
|
3
3
|
from shellui_django.mcp.decorators import mcp_expose_tool
|
|
4
|
+
from shellui_django.mcp.delegation import (
|
|
5
|
+
DOWNSTREAM_TOKEN_AUDIENCE,
|
|
6
|
+
DOWNSTREAM_TOKEN_REQUEST_MAX_LIFETIME_SECONDS,
|
|
7
|
+
DOWNSTREAM_TOKEN_SCOPE,
|
|
8
|
+
DownstreamTokenRequestError,
|
|
9
|
+
sign_downstream_token_request,
|
|
10
|
+
verify_downstream_token_request,
|
|
11
|
+
)
|
|
4
12
|
from shellui_django.mcp.internal import (
|
|
5
13
|
APPROVAL_AUDIENCE,
|
|
6
14
|
APPROVAL_SCOPE,
|
|
15
|
+
INTERNAL_ASSERTION_MAX_LIFETIME_SECONDS,
|
|
7
16
|
REVOCATION_CACHE_SECONDS,
|
|
8
17
|
REVOCATION_LIST_SCOPE,
|
|
9
18
|
build_mcp_approval_assertion,
|
|
@@ -11,12 +20,20 @@ from shellui_django.mcp.internal import (
|
|
|
11
20
|
parse_trusted_revocation_poll_response,
|
|
12
21
|
verify_mcp_internal_assertion,
|
|
13
22
|
verify_mcp_revocation_list_response,
|
|
23
|
+
verify_rs256_mcp_assertion,
|
|
14
24
|
)
|
|
15
25
|
|
|
16
26
|
__all__ = [
|
|
17
27
|
'mcp_expose_tool',
|
|
28
|
+
'DOWNSTREAM_TOKEN_AUDIENCE',
|
|
29
|
+
'DOWNSTREAM_TOKEN_REQUEST_MAX_LIFETIME_SECONDS',
|
|
30
|
+
'DOWNSTREAM_TOKEN_SCOPE',
|
|
31
|
+
'DownstreamTokenRequestError',
|
|
32
|
+
'sign_downstream_token_request',
|
|
33
|
+
'verify_downstream_token_request',
|
|
18
34
|
'APPROVAL_AUDIENCE',
|
|
19
35
|
'APPROVAL_SCOPE',
|
|
36
|
+
'INTERNAL_ASSERTION_MAX_LIFETIME_SECONDS',
|
|
20
37
|
'REVOCATION_CACHE_SECONDS',
|
|
21
38
|
'REVOCATION_LIST_SCOPE',
|
|
22
39
|
'build_mcp_approval_assertion',
|
|
@@ -24,4 +41,5 @@ __all__ = [
|
|
|
24
41
|
'parse_trusted_revocation_poll_response',
|
|
25
42
|
'verify_mcp_internal_assertion',
|
|
26
43
|
'verify_mcp_revocation_list_response',
|
|
44
|
+
'verify_rs256_mcp_assertion',
|
|
27
45
|
]
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
"""RS256 JWT delegation: gateway requests Identity to mint downstream MCP access tokens."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
import uuid
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
import jwt
|
|
10
|
+
|
|
11
|
+
DOWNSTREAM_TOKEN_AUDIENCE = 'shellui-mcp-downstream-token'
|
|
12
|
+
DOWNSTREAM_TOKEN_SCOPE = 'mcp.downstream_token.mint'
|
|
13
|
+
DOWNSTREAM_TOKEN_REQUEST_MAX_LIFETIME_SECONDS = 60
|
|
14
|
+
DOWNSTREAM_TOKEN_REQUEST_LEEWAY_SECONDS = 5
|
|
15
|
+
|
|
16
|
+
_REQUIRED_CLAIMS = (
|
|
17
|
+
'iss',
|
|
18
|
+
'aud',
|
|
19
|
+
'scope',
|
|
20
|
+
'agent_id',
|
|
21
|
+
'company_id',
|
|
22
|
+
'resource',
|
|
23
|
+
'jti',
|
|
24
|
+
'iat',
|
|
25
|
+
'exp',
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class DownstreamTokenRequestError(Exception):
|
|
30
|
+
def __init__(self, message: str, *, status: int = 401):
|
|
31
|
+
super().__init__(message)
|
|
32
|
+
self.message = message
|
|
33
|
+
self.status = status
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def sign_downstream_token_request(
|
|
37
|
+
private_key_pem: str,
|
|
38
|
+
kid: str,
|
|
39
|
+
issuer: str,
|
|
40
|
+
agent_id: str,
|
|
41
|
+
company_id: int,
|
|
42
|
+
resource: str,
|
|
43
|
+
ttl: int,
|
|
44
|
+
) -> str:
|
|
45
|
+
"""Sign a short-lived RS256 request JWT for Identity's downstream token mint endpoint."""
|
|
46
|
+
if ttl <= 0 or ttl > DOWNSTREAM_TOKEN_REQUEST_MAX_LIFETIME_SECONDS:
|
|
47
|
+
raise DownstreamTokenRequestError(
|
|
48
|
+
f'ttl must be between 1 and {DOWNSTREAM_TOKEN_REQUEST_MAX_LIFETIME_SECONDS} seconds.'
|
|
49
|
+
)
|
|
50
|
+
pem = (private_key_pem or '').strip()
|
|
51
|
+
if not pem:
|
|
52
|
+
raise DownstreamTokenRequestError('private_key_pem is required.')
|
|
53
|
+
iss = (issuer or '').strip()
|
|
54
|
+
if not iss:
|
|
55
|
+
raise DownstreamTokenRequestError('issuer is required.')
|
|
56
|
+
agent = (agent_id or '').strip()
|
|
57
|
+
if not agent:
|
|
58
|
+
raise DownstreamTokenRequestError('agent_id is required.')
|
|
59
|
+
res = (resource or '').strip()
|
|
60
|
+
if not res:
|
|
61
|
+
raise DownstreamTokenRequestError('resource is required.')
|
|
62
|
+
now = int(time.time())
|
|
63
|
+
claims = {
|
|
64
|
+
'iss': iss,
|
|
65
|
+
'aud': DOWNSTREAM_TOKEN_AUDIENCE,
|
|
66
|
+
'scope': DOWNSTREAM_TOKEN_SCOPE,
|
|
67
|
+
'agent_id': agent,
|
|
68
|
+
'company_id': int(company_id),
|
|
69
|
+
'resource': res,
|
|
70
|
+
'jti': uuid.uuid4().hex,
|
|
71
|
+
'iat': now,
|
|
72
|
+
'exp': now + int(ttl),
|
|
73
|
+
}
|
|
74
|
+
headers: dict[str, str] | None = None
|
|
75
|
+
key_id = (kid or '').strip()
|
|
76
|
+
if key_id:
|
|
77
|
+
headers = {'kid': key_id}
|
|
78
|
+
token = jwt.encode(claims, pem, algorithm='RS256', headers=headers)
|
|
79
|
+
return token.decode('utf-8') if isinstance(token, bytes) else token
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _normalize_bearer_token(raw_token: str) -> str:
|
|
83
|
+
if not raw_token or not raw_token.strip():
|
|
84
|
+
raise DownstreamTokenRequestError('Missing downstream token request JWT.')
|
|
85
|
+
token = raw_token.strip()
|
|
86
|
+
if token.lower().startswith('bearer '):
|
|
87
|
+
token = token[7:].strip()
|
|
88
|
+
if not token:
|
|
89
|
+
raise DownstreamTokenRequestError('Missing downstream token request JWT.')
|
|
90
|
+
return token
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def _resolve_verification_key(token: str, public_jwks_or_pem: dict[str, Any] | str) -> Any:
|
|
94
|
+
from shellui_django.mcp.identity_jwks import IdentityJwksError, resolve_public_verification_key
|
|
95
|
+
|
|
96
|
+
try:
|
|
97
|
+
return resolve_public_verification_key(token, public_jwks_or_pem)
|
|
98
|
+
except IdentityJwksError as exc:
|
|
99
|
+
raise DownstreamTokenRequestError(str(exc)) from exc
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _assert_lifetime_within_limit(claims: dict[str, Any]) -> None:
|
|
103
|
+
try:
|
|
104
|
+
iat = int(claims['iat'])
|
|
105
|
+
exp = int(claims['exp'])
|
|
106
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
107
|
+
raise DownstreamTokenRequestError('Invalid iat or exp.') from exc
|
|
108
|
+
if exp <= iat:
|
|
109
|
+
raise DownstreamTokenRequestError('Token lifetime is invalid.')
|
|
110
|
+
if exp - iat > DOWNSTREAM_TOKEN_REQUEST_MAX_LIFETIME_SECONDS:
|
|
111
|
+
raise DownstreamTokenRequestError('Token lifetime exceeds the maximum allowed.')
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def verify_downstream_token_request(
|
|
115
|
+
token: str,
|
|
116
|
+
public_jwks_or_pem: dict[str, Any] | str,
|
|
117
|
+
expected_issuer: str,
|
|
118
|
+
) -> dict[str, Any]:
|
|
119
|
+
"""Verify a gateway-signed downstream token request; returns claims (including ``jti`` for one-time use)."""
|
|
120
|
+
normalized = _normalize_bearer_token(token)
|
|
121
|
+
issuer = (expected_issuer or '').strip().rstrip('/')
|
|
122
|
+
if not issuer:
|
|
123
|
+
raise DownstreamTokenRequestError('expected_issuer is required.')
|
|
124
|
+
try:
|
|
125
|
+
header = jwt.get_unverified_header(normalized)
|
|
126
|
+
except jwt.PyJWTError as exc:
|
|
127
|
+
raise DownstreamTokenRequestError('Invalid downstream token request JWT.') from exc
|
|
128
|
+
alg = str(header.get('alg') or '')
|
|
129
|
+
if alg != 'RS256':
|
|
130
|
+
raise DownstreamTokenRequestError('Downstream token request JWT must use RS256.')
|
|
131
|
+
key = _resolve_verification_key(normalized, public_jwks_or_pem)
|
|
132
|
+
try:
|
|
133
|
+
claims = jwt.decode(
|
|
134
|
+
normalized,
|
|
135
|
+
key=key,
|
|
136
|
+
algorithms=['RS256'],
|
|
137
|
+
audience=DOWNSTREAM_TOKEN_AUDIENCE,
|
|
138
|
+
issuer=issuer,
|
|
139
|
+
leeway=DOWNSTREAM_TOKEN_REQUEST_LEEWAY_SECONDS,
|
|
140
|
+
options={'require': list(_REQUIRED_CLAIMS)},
|
|
141
|
+
)
|
|
142
|
+
except jwt.PyJWTError as exc:
|
|
143
|
+
raise DownstreamTokenRequestError('Invalid downstream token request JWT.') from exc
|
|
144
|
+
scope = str(claims.get('scope') or '')
|
|
145
|
+
if scope != DOWNSTREAM_TOKEN_SCOPE:
|
|
146
|
+
raise DownstreamTokenRequestError('Downstream token request scope mismatch.')
|
|
147
|
+
aud = claims.get('aud')
|
|
148
|
+
if isinstance(aud, list):
|
|
149
|
+
if DOWNSTREAM_TOKEN_AUDIENCE not in aud:
|
|
150
|
+
raise DownstreamTokenRequestError('Downstream token request audience mismatch.')
|
|
151
|
+
elif str(aud or '') != DOWNSTREAM_TOKEN_AUDIENCE:
|
|
152
|
+
raise DownstreamTokenRequestError('Downstream token request audience mismatch.')
|
|
153
|
+
_assert_lifetime_within_limit(claims)
|
|
154
|
+
for name in _REQUIRED_CLAIMS:
|
|
155
|
+
value = claims.get(name)
|
|
156
|
+
if value is None or (isinstance(value, str) and not value.strip()):
|
|
157
|
+
raise DownstreamTokenRequestError(f'Missing required claim: {name}.')
|
|
158
|
+
return dict(claims)
|
|
@@ -68,6 +68,18 @@ def _public_key_from_jwk(jwk: dict[str, Any]):
|
|
|
68
68
|
return RSAAlgorithm.from_jwk(json.dumps(jwk))
|
|
69
69
|
|
|
70
70
|
|
|
71
|
+
def resolve_public_verification_key(token: str, public_jwks_or_pem: dict[str, Any] | str):
|
|
72
|
+
"""Return a verification key from inline JWKS, a fetched document, or a PEM string."""
|
|
73
|
+
if isinstance(public_jwks_or_pem, str):
|
|
74
|
+
pem = public_jwks_or_pem.strip()
|
|
75
|
+
if not pem:
|
|
76
|
+
raise IdentityJwksError('Verification key is required.')
|
|
77
|
+
return pem
|
|
78
|
+
if isinstance(public_jwks_or_pem, dict):
|
|
79
|
+
return resolve_verification_key(token, public_jwks_or_pem)
|
|
80
|
+
raise IdentityJwksError('public_jwks_or_pem must be a PEM string or JWKS document.')
|
|
81
|
+
|
|
82
|
+
|
|
71
83
|
def resolve_verification_key(token: str, jwks_document: dict[str, Any]):
|
|
72
84
|
header = jwt.get_unverified_header(token)
|
|
73
85
|
kid = header.get('kid')
|
|
@@ -4,16 +4,28 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import time
|
|
6
6
|
import uuid
|
|
7
|
+
from collections.abc import Callable
|
|
7
8
|
from typing import Any
|
|
8
9
|
|
|
9
10
|
import jwt
|
|
10
11
|
from django.conf import settings
|
|
11
12
|
from rest_framework_simplejwt.settings import api_settings
|
|
12
13
|
|
|
14
|
+
INTERNAL_ASSERTION_MAX_LIFETIME_SECONDS = 60
|
|
15
|
+
INTERNAL_ASSERTION_LEEWAY_SECONDS = 5
|
|
16
|
+
|
|
13
17
|
|
|
14
18
|
def _identity_issuer() -> str:
|
|
15
19
|
return (api_settings.ISSUER or getattr(settings, 'JWT_ISSUER', None) or '').strip()
|
|
16
20
|
|
|
21
|
+
|
|
22
|
+
def _service_issuer(explicit: str | None = None) -> str:
|
|
23
|
+
if explicit and explicit.strip():
|
|
24
|
+
return explicit.strip().rstrip('/')
|
|
25
|
+
configured = getattr(settings, 'JWT_ISSUER', None) or api_settings.ISSUER or ''
|
|
26
|
+
return str(configured).strip().rstrip('/')
|
|
27
|
+
|
|
28
|
+
|
|
17
29
|
APPROVAL_AUDIENCE = 'shellui-mcp-approval'
|
|
18
30
|
APPROVAL_SCOPE = 'mcp.approval.create'
|
|
19
31
|
CALL_LOG_AUDIENCE = 'shellui-mcp-call-log'
|
|
@@ -32,12 +44,45 @@ class InternalAssertionError(Exception):
|
|
|
32
44
|
self.status = status
|
|
33
45
|
|
|
34
46
|
|
|
35
|
-
def
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
47
|
+
def _signing_material(
|
|
48
|
+
*,
|
|
49
|
+
private_key_pem: str | None = None,
|
|
50
|
+
kid: str | None = None,
|
|
51
|
+
) -> tuple[str, str]:
|
|
52
|
+
if private_key_pem and private_key_pem.strip():
|
|
53
|
+
pem = private_key_pem.strip()
|
|
54
|
+
key_id = (kid or '').strip() or getattr(settings, 'JWT_ACTIVE_KEY_ID', '') or ''
|
|
55
|
+
return pem, key_id
|
|
56
|
+
signing = getattr(settings, 'JWT_SIGNING_KEY', None)
|
|
57
|
+
if signing is None:
|
|
58
|
+
raise InternalAssertionError(
|
|
59
|
+
'Service assertion signing is not configured.',
|
|
60
|
+
status=503,
|
|
61
|
+
)
|
|
62
|
+
pem = getattr(signing, 'private_pem', None) or ''
|
|
63
|
+
if not pem:
|
|
64
|
+
raise InternalAssertionError(
|
|
65
|
+
'Service assertion signing is not configured.',
|
|
66
|
+
status=503,
|
|
67
|
+
)
|
|
68
|
+
key_id = (
|
|
69
|
+
(kid or '').strip()
|
|
70
|
+
or getattr(signing, 'kid', None)
|
|
71
|
+
or getattr(settings, 'JWT_ACTIVE_KEY_ID', '')
|
|
72
|
+
or ''
|
|
73
|
+
)
|
|
74
|
+
return pem, key_id
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _encode_rs256_assertion(
|
|
78
|
+
claims: dict[str, Any],
|
|
79
|
+
*,
|
|
80
|
+
private_key_pem: str | None = None,
|
|
81
|
+
kid: str | None = None,
|
|
82
|
+
) -> str:
|
|
83
|
+
pem, key_id = _signing_material(private_key_pem=private_key_pem, kid=kid)
|
|
84
|
+
headers: dict[str, str] | None = {'kid': key_id} if key_id else None
|
|
85
|
+
token = jwt.encode(claims, pem, algorithm='RS256', headers=headers)
|
|
41
86
|
return token.decode('utf-8') if isinstance(token, bytes) else token
|
|
42
87
|
|
|
43
88
|
|
|
@@ -50,10 +95,13 @@ def build_mcp_approval_assertion(
|
|
|
50
95
|
arguments_hash: str,
|
|
51
96
|
audience_url: str,
|
|
52
97
|
lifetime_seconds: int = 60,
|
|
98
|
+
private_key_pem: str | None = None,
|
|
99
|
+
kid: str | None = None,
|
|
100
|
+
issuer: str | None = None,
|
|
53
101
|
) -> str:
|
|
54
102
|
now = int(time.time())
|
|
55
103
|
claims = {
|
|
56
|
-
'iss':
|
|
104
|
+
'iss': _service_issuer(issuer),
|
|
57
105
|
'aud': APPROVAL_AUDIENCE,
|
|
58
106
|
'sub': f'agent:{agent_id}',
|
|
59
107
|
'scope': APPROVAL_SCOPE,
|
|
@@ -67,20 +115,7 @@ def build_mcp_approval_assertion(
|
|
|
67
115
|
'exp': now + lifetime_seconds,
|
|
68
116
|
'jti': uuid.uuid4().hex,
|
|
69
117
|
}
|
|
70
|
-
return
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
def _encode_identity_issued_rs256(claims: dict[str, Any]) -> str | None:
|
|
74
|
-
signing = getattr(settings, 'JWT_SIGNING_KEY', None)
|
|
75
|
-
if signing is None:
|
|
76
|
-
return None
|
|
77
|
-
private_pem = getattr(signing, 'private_pem', None)
|
|
78
|
-
if not private_pem:
|
|
79
|
-
return None
|
|
80
|
-
kid = getattr(signing, 'kid', None) or getattr(settings, 'JWT_ACTIVE_KEY_ID', '') or ''
|
|
81
|
-
headers = {'kid': kid} if kid else None
|
|
82
|
-
token = jwt.encode(claims, private_pem, algorithm='RS256', headers=headers)
|
|
83
|
-
return token.decode('utf-8') if isinstance(token, bytes) else token
|
|
118
|
+
return _encode_rs256_assertion(claims, private_key_pem=private_key_pem, kid=kid)
|
|
84
119
|
|
|
85
120
|
|
|
86
121
|
def build_mcp_revocation_list_response_assertion(
|
|
@@ -105,19 +140,26 @@ def build_mcp_revocation_list_response_assertion(
|
|
|
105
140
|
'exp': now + lifetime_seconds,
|
|
106
141
|
'jti': uuid.uuid4().hex,
|
|
107
142
|
}
|
|
108
|
-
|
|
109
|
-
|
|
143
|
+
try:
|
|
144
|
+
return _encode_rs256_assertion(claims)
|
|
145
|
+
except InternalAssertionError as exc:
|
|
110
146
|
raise InternalAssertionError(
|
|
111
147
|
'Revocation list signing is not configured.',
|
|
112
148
|
status=503,
|
|
113
|
-
)
|
|
114
|
-
return rs256
|
|
149
|
+
) from exc
|
|
115
150
|
|
|
116
151
|
|
|
117
|
-
def build_mcp_revocation_assertion(
|
|
152
|
+
def build_mcp_revocation_assertion(
|
|
153
|
+
*,
|
|
154
|
+
audience_url: str,
|
|
155
|
+
lifetime_seconds: int = 60,
|
|
156
|
+
private_key_pem: str | None = None,
|
|
157
|
+
kid: str | None = None,
|
|
158
|
+
issuer: str | None = None,
|
|
159
|
+
) -> str:
|
|
118
160
|
now = int(time.time())
|
|
119
161
|
claims = {
|
|
120
|
-
'iss':
|
|
162
|
+
'iss': _service_issuer(issuer),
|
|
121
163
|
'aud': REVOCATION_AUDIENCE,
|
|
122
164
|
'sub': 'service',
|
|
123
165
|
'scope': REVOCATION_SCOPE,
|
|
@@ -126,13 +168,20 @@ def build_mcp_revocation_assertion(*, audience_url: str, lifetime_seconds: int =
|
|
|
126
168
|
'exp': now + lifetime_seconds,
|
|
127
169
|
'jti': uuid.uuid4().hex,
|
|
128
170
|
}
|
|
129
|
-
return
|
|
171
|
+
return _encode_rs256_assertion(claims, private_key_pem=private_key_pem, kid=kid)
|
|
130
172
|
|
|
131
173
|
|
|
132
|
-
def build_mcp_call_log_assertion(
|
|
174
|
+
def build_mcp_call_log_assertion(
|
|
175
|
+
*,
|
|
176
|
+
audience_url: str,
|
|
177
|
+
lifetime_seconds: int = 60,
|
|
178
|
+
private_key_pem: str | None = None,
|
|
179
|
+
kid: str | None = None,
|
|
180
|
+
issuer: str | None = None,
|
|
181
|
+
) -> str:
|
|
133
182
|
now = int(time.time())
|
|
134
183
|
claims = {
|
|
135
|
-
'iss':
|
|
184
|
+
'iss': _service_issuer(issuer),
|
|
136
185
|
'aud': CALL_LOG_AUDIENCE,
|
|
137
186
|
'sub': 'service',
|
|
138
187
|
'scope': CALL_LOG_SCOPE,
|
|
@@ -141,44 +190,118 @@ def build_mcp_call_log_assertion(*, audience_url: str, lifetime_seconds: int = 6
|
|
|
141
190
|
'exp': now + lifetime_seconds,
|
|
142
191
|
'jti': uuid.uuid4().hex,
|
|
143
192
|
}
|
|
144
|
-
return
|
|
193
|
+
return _encode_rs256_assertion(claims, private_key_pem=private_key_pem, kid=kid)
|
|
145
194
|
|
|
146
195
|
|
|
147
|
-
def
|
|
196
|
+
def _normalize_bearer_token(raw_token: str) -> str:
|
|
197
|
+
if not raw_token or not raw_token.strip():
|
|
198
|
+
raise InternalAssertionError('Missing assertion.')
|
|
199
|
+
token = raw_token.strip()
|
|
200
|
+
if token.lower().startswith('bearer '):
|
|
201
|
+
token = token[7:].strip()
|
|
202
|
+
if not token:
|
|
203
|
+
raise InternalAssertionError('Missing assertion.')
|
|
204
|
+
return token
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _assert_lifetime_within_limit(claims: dict[str, Any], *, max_lifetime_seconds: int) -> None:
|
|
208
|
+
try:
|
|
209
|
+
iat = int(claims['iat'])
|
|
210
|
+
exp = int(claims['exp'])
|
|
211
|
+
except (KeyError, TypeError, ValueError) as exc:
|
|
212
|
+
raise InternalAssertionError('Invalid iat or exp.') from exc
|
|
213
|
+
if exp <= iat:
|
|
214
|
+
raise InternalAssertionError('Assertion lifetime is invalid.')
|
|
215
|
+
if exp - iat > max_lifetime_seconds:
|
|
216
|
+
raise InternalAssertionError('Assertion lifetime exceeds the maximum allowed.')
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def verify_rs256_mcp_assertion(
|
|
148
220
|
raw_token: str,
|
|
221
|
+
public_jwks_or_pem: dict[str, Any] | str,
|
|
149
222
|
*,
|
|
223
|
+
expected_issuer: str,
|
|
150
224
|
expected_audience: str,
|
|
151
225
|
expected_scope: str,
|
|
152
226
|
expected_target: str | None = None,
|
|
227
|
+
register_jti: Callable[[str], bool] | None = None,
|
|
228
|
+
max_lifetime_seconds: int = INTERNAL_ASSERTION_MAX_LIFETIME_SECONDS,
|
|
153
229
|
) -> dict[str, Any]:
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
230
|
+
"""Verify a service-signed RS256 internal MCP assertion using caller JWKS or PEM."""
|
|
231
|
+
from shellui_django.mcp.identity_jwks import IdentityJwksError, resolve_public_verification_key
|
|
232
|
+
|
|
233
|
+
token = _normalize_bearer_token(raw_token)
|
|
234
|
+
issuer = (expected_issuer or '').strip().rstrip('/')
|
|
235
|
+
if not issuer:
|
|
236
|
+
raise InternalAssertionError('expected_issuer is required.')
|
|
237
|
+
try:
|
|
238
|
+
header = jwt.get_unverified_header(token)
|
|
239
|
+
except jwt.PyJWTError as exc:
|
|
240
|
+
raise InternalAssertionError('Invalid assertion.') from exc
|
|
241
|
+
alg = str(header.get('alg') or '')
|
|
242
|
+
if alg != 'RS256':
|
|
243
|
+
raise InternalAssertionError('Internal MCP assertion must use RS256.')
|
|
244
|
+
try:
|
|
245
|
+
key = resolve_public_verification_key(token, public_jwks_or_pem)
|
|
246
|
+
except IdentityJwksError as exc:
|
|
247
|
+
raise InternalAssertionError(str(exc)) from exc
|
|
159
248
|
try:
|
|
160
249
|
payload = jwt.decode(
|
|
161
250
|
token,
|
|
162
|
-
|
|
163
|
-
algorithms=[
|
|
251
|
+
key=key,
|
|
252
|
+
algorithms=['RS256'],
|
|
164
253
|
audience=expected_audience,
|
|
165
|
-
issuer=
|
|
166
|
-
|
|
254
|
+
issuer=issuer,
|
|
255
|
+
leeway=INTERNAL_ASSERTION_LEEWAY_SECONDS,
|
|
256
|
+
options={'require': ['exp', 'iat', 'sub', 'scope', 'jti']},
|
|
167
257
|
)
|
|
168
258
|
except jwt.PyJWTError as exc:
|
|
169
259
|
raise InternalAssertionError('Invalid assertion.') from exc
|
|
170
260
|
scope = str(payload.get('scope') or '')
|
|
171
261
|
if scope != expected_scope:
|
|
172
262
|
raise InternalAssertionError('Assertion scope mismatch.')
|
|
263
|
+
aud = payload.get('aud')
|
|
264
|
+
if isinstance(aud, list):
|
|
265
|
+
if expected_audience not in aud:
|
|
266
|
+
raise InternalAssertionError('Assertion audience mismatch.')
|
|
267
|
+
elif str(aud or '') != expected_audience:
|
|
268
|
+
raise InternalAssertionError('Assertion audience mismatch.')
|
|
173
269
|
if expected_target:
|
|
174
270
|
target = str(payload.get('target') or '').rstrip('/')
|
|
175
271
|
if target and target != expected_target.rstrip('/'):
|
|
176
272
|
raise InternalAssertionError('Assertion target mismatch.')
|
|
177
|
-
|
|
178
|
-
|
|
273
|
+
_assert_lifetime_within_limit(payload, max_lifetime_seconds=max_lifetime_seconds)
|
|
274
|
+
jti = str(payload.get('jti') or '').strip()
|
|
275
|
+
if not jti:
|
|
276
|
+
raise InternalAssertionError('Missing jti.')
|
|
277
|
+
if register_jti is not None and not register_jti(jti):
|
|
278
|
+
raise InternalAssertionError('Assertion replay detected.')
|
|
179
279
|
return payload
|
|
180
280
|
|
|
181
281
|
|
|
282
|
+
def verify_mcp_internal_assertion(
|
|
283
|
+
raw_token: str,
|
|
284
|
+
public_jwks_or_pem: dict[str, Any] | str,
|
|
285
|
+
*,
|
|
286
|
+
expected_issuer: str,
|
|
287
|
+
expected_audience: str,
|
|
288
|
+
expected_scope: str,
|
|
289
|
+
expected_target: str | None = None,
|
|
290
|
+
register_jti: Callable[[str], bool] | None = None,
|
|
291
|
+
max_lifetime_seconds: int = INTERNAL_ASSERTION_MAX_LIFETIME_SECONDS,
|
|
292
|
+
) -> dict[str, Any]:
|
|
293
|
+
return verify_rs256_mcp_assertion(
|
|
294
|
+
raw_token,
|
|
295
|
+
public_jwks_or_pem,
|
|
296
|
+
expected_issuer=expected_issuer,
|
|
297
|
+
expected_audience=expected_audience,
|
|
298
|
+
expected_scope=expected_scope,
|
|
299
|
+
expected_target=expected_target,
|
|
300
|
+
register_jti=register_jti,
|
|
301
|
+
max_lifetime_seconds=max_lifetime_seconds,
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
|
|
182
305
|
def _revocation_list_assertion_token(payload: dict[str, Any]) -> str:
|
|
183
306
|
token = payload.get('revocation_assertion') or payload.get('assertion')
|
|
184
307
|
if not token or not str(token).strip():
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import unittest
|
|
3
|
+
import uuid
|
|
4
|
+
|
|
5
|
+
import jwt
|
|
6
|
+
from cryptography.hazmat.primitives import serialization
|
|
7
|
+
|
|
8
|
+
from shellui_django.mcp.delegation import (
|
|
9
|
+
DOWNSTREAM_TOKEN_AUDIENCE,
|
|
10
|
+
DOWNSTREAM_TOKEN_REQUEST_MAX_LIFETIME_SECONDS,
|
|
11
|
+
DOWNSTREAM_TOKEN_SCOPE,
|
|
12
|
+
DownstreamTokenRequestError,
|
|
13
|
+
sign_downstream_token_request,
|
|
14
|
+
verify_downstream_token_request,
|
|
15
|
+
)
|
|
16
|
+
from shellui_django.mcp.tests.rs256_helpers import generate_test_rsa_jwks
|
|
17
|
+
|
|
18
|
+
TEST_ISSUER = 'https://gateway.example.com'
|
|
19
|
+
TEST_RESOURCE = 'https://storage.example.com/mcp'
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class DownstreamTokenDelegationTests(unittest.TestCase):
|
|
23
|
+
@classmethod
|
|
24
|
+
def setUpClass(cls):
|
|
25
|
+
cls.jwks, cls.private_pem, cls.kid = generate_test_rsa_jwks()
|
|
26
|
+
cls.public_pem = (
|
|
27
|
+
serialization.load_pem_private_key(cls.private_pem.encode(), password=None)
|
|
28
|
+
.public_key()
|
|
29
|
+
.public_bytes(
|
|
30
|
+
encoding=serialization.Encoding.PEM,
|
|
31
|
+
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
|
32
|
+
)
|
|
33
|
+
.decode()
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
def _sign(self, **kwargs):
|
|
37
|
+
defaults = {
|
|
38
|
+
'private_key_pem': self.private_pem,
|
|
39
|
+
'kid': self.kid,
|
|
40
|
+
'issuer': TEST_ISSUER,
|
|
41
|
+
'agent_id': 'agent-abc',
|
|
42
|
+
'company_id': 42,
|
|
43
|
+
'resource': TEST_RESOURCE,
|
|
44
|
+
'ttl': 30,
|
|
45
|
+
}
|
|
46
|
+
defaults.update(kwargs)
|
|
47
|
+
return sign_downstream_token_request(**defaults)
|
|
48
|
+
|
|
49
|
+
def _verify(self, token: str, *, jwks_or_pem=None, issuer=TEST_ISSUER):
|
|
50
|
+
material = jwks_or_pem if jwks_or_pem is not None else self.jwks
|
|
51
|
+
return verify_downstream_token_request(token, material, issuer)
|
|
52
|
+
|
|
53
|
+
def test_sign_verify_round_trip_jwks(self):
|
|
54
|
+
token = self._sign()
|
|
55
|
+
claims = self._verify(token)
|
|
56
|
+
self.assertEqual(claims['iss'], TEST_ISSUER)
|
|
57
|
+
self.assertEqual(claims['aud'], DOWNSTREAM_TOKEN_AUDIENCE)
|
|
58
|
+
self.assertEqual(claims['scope'], DOWNSTREAM_TOKEN_SCOPE)
|
|
59
|
+
self.assertEqual(claims['agent_id'], 'agent-abc')
|
|
60
|
+
self.assertEqual(claims['company_id'], 42)
|
|
61
|
+
self.assertEqual(claims['resource'], TEST_RESOURCE)
|
|
62
|
+
self.assertTrue(claims['jti'])
|
|
63
|
+
self.assertLessEqual(int(claims['exp']) - int(claims['iat']), DOWNSTREAM_TOKEN_REQUEST_MAX_LIFETIME_SECONDS)
|
|
64
|
+
|
|
65
|
+
def test_sign_verify_round_trip_public_pem(self):
|
|
66
|
+
token = self._sign(ttl=60)
|
|
67
|
+
claims = self._verify(token, jwks_or_pem=self.public_pem)
|
|
68
|
+
self.assertEqual(claims['resource'], TEST_RESOURCE)
|
|
69
|
+
|
|
70
|
+
def test_bearer_prefix_accepted(self):
|
|
71
|
+
token = self._sign()
|
|
72
|
+
claims = self._verify(f'Bearer {token}')
|
|
73
|
+
self.assertEqual(claims['agent_id'], 'agent-abc')
|
|
74
|
+
|
|
75
|
+
def test_sign_rejects_ttl_over_max(self):
|
|
76
|
+
with self.assertRaises(DownstreamTokenRequestError):
|
|
77
|
+
self._sign(ttl=61)
|
|
78
|
+
|
|
79
|
+
def test_sign_rejects_zero_ttl(self):
|
|
80
|
+
with self.assertRaises(DownstreamTokenRequestError):
|
|
81
|
+
self._sign(ttl=0)
|
|
82
|
+
|
|
83
|
+
def test_verify_rejects_lifetime_longer_than_max(self):
|
|
84
|
+
now = int(time.time())
|
|
85
|
+
claims = {
|
|
86
|
+
'iss': TEST_ISSUER,
|
|
87
|
+
'aud': DOWNSTREAM_TOKEN_AUDIENCE,
|
|
88
|
+
'scope': DOWNSTREAM_TOKEN_SCOPE,
|
|
89
|
+
'agent_id': 'agent-abc',
|
|
90
|
+
'company_id': 42,
|
|
91
|
+
'resource': TEST_RESOURCE,
|
|
92
|
+
'jti': uuid.uuid4().hex,
|
|
93
|
+
'iat': now,
|
|
94
|
+
'exp': now + DOWNSTREAM_TOKEN_REQUEST_MAX_LIFETIME_SECONDS + 10,
|
|
95
|
+
}
|
|
96
|
+
token = jwt.encode(claims, self.private_pem, algorithm='RS256', headers={'kid': self.kid})
|
|
97
|
+
token = token.decode('utf-8') if isinstance(token, bytes) else token
|
|
98
|
+
with self.assertRaises(DownstreamTokenRequestError) as ctx:
|
|
99
|
+
self._verify(token)
|
|
100
|
+
self.assertIn('lifetime', str(ctx.exception).lower())
|
|
101
|
+
|
|
102
|
+
def test_verify_rejects_expired(self):
|
|
103
|
+
now = int(time.time())
|
|
104
|
+
claims = {
|
|
105
|
+
'iss': TEST_ISSUER,
|
|
106
|
+
'aud': DOWNSTREAM_TOKEN_AUDIENCE,
|
|
107
|
+
'scope': DOWNSTREAM_TOKEN_SCOPE,
|
|
108
|
+
'agent_id': 'agent-abc',
|
|
109
|
+
'company_id': 42,
|
|
110
|
+
'resource': TEST_RESOURCE,
|
|
111
|
+
'jti': uuid.uuid4().hex,
|
|
112
|
+
'iat': now - 30,
|
|
113
|
+
'exp': now - 10,
|
|
114
|
+
}
|
|
115
|
+
token = jwt.encode(claims, self.private_pem, algorithm='RS256', headers={'kid': self.kid})
|
|
116
|
+
token = token.decode('utf-8') if isinstance(token, bytes) else token
|
|
117
|
+
with self.assertRaises(DownstreamTokenRequestError):
|
|
118
|
+
self._verify(token)
|
|
119
|
+
|
|
120
|
+
def test_verify_rejects_wrong_audience(self):
|
|
121
|
+
now = int(time.time())
|
|
122
|
+
claims = {
|
|
123
|
+
'iss': TEST_ISSUER,
|
|
124
|
+
'aud': 'wrong-audience',
|
|
125
|
+
'scope': DOWNSTREAM_TOKEN_SCOPE,
|
|
126
|
+
'agent_id': 'agent-abc',
|
|
127
|
+
'company_id': 42,
|
|
128
|
+
'resource': TEST_RESOURCE,
|
|
129
|
+
'jti': uuid.uuid4().hex,
|
|
130
|
+
'iat': now,
|
|
131
|
+
'exp': now + 30,
|
|
132
|
+
}
|
|
133
|
+
token = jwt.encode(claims, self.private_pem, algorithm='RS256', headers={'kid': self.kid})
|
|
134
|
+
token = token.decode('utf-8') if isinstance(token, bytes) else token
|
|
135
|
+
with self.assertRaises(DownstreamTokenRequestError):
|
|
136
|
+
self._verify(token)
|
|
137
|
+
|
|
138
|
+
def test_verify_rejects_wrong_issuer(self):
|
|
139
|
+
token = self._sign()
|
|
140
|
+
with self.assertRaises(DownstreamTokenRequestError):
|
|
141
|
+
self._verify(token, issuer='https://other.example.com')
|
|
142
|
+
|
|
143
|
+
def test_verify_rejects_wrong_scope(self):
|
|
144
|
+
now = int(time.time())
|
|
145
|
+
claims = {
|
|
146
|
+
'iss': TEST_ISSUER,
|
|
147
|
+
'aud': DOWNSTREAM_TOKEN_AUDIENCE,
|
|
148
|
+
'scope': 'mcp.other.scope',
|
|
149
|
+
'agent_id': 'agent-abc',
|
|
150
|
+
'company_id': 42,
|
|
151
|
+
'resource': TEST_RESOURCE,
|
|
152
|
+
'jti': uuid.uuid4().hex,
|
|
153
|
+
'iat': now,
|
|
154
|
+
'exp': now + 30,
|
|
155
|
+
}
|
|
156
|
+
token = jwt.encode(claims, self.private_pem, algorithm='RS256', headers={'kid': self.kid})
|
|
157
|
+
token = token.decode('utf-8') if isinstance(token, bytes) else token
|
|
158
|
+
with self.assertRaises(DownstreamTokenRequestError) as ctx:
|
|
159
|
+
self._verify(token)
|
|
160
|
+
self.assertIn('scope', str(ctx.exception).lower())
|
|
161
|
+
|
|
162
|
+
def test_verify_rejects_missing_claims(self):
|
|
163
|
+
token = self._sign()
|
|
164
|
+
payload = jwt.decode(token, options={'verify_signature': False})
|
|
165
|
+
for key in ('agent_id', 'company_id', 'resource', 'jti'):
|
|
166
|
+
tampered = dict(payload)
|
|
167
|
+
tampered.pop(key)
|
|
168
|
+
bad = jwt.encode(tampered, self.private_pem, algorithm='RS256', headers={'kid': self.kid})
|
|
169
|
+
bad = bad.decode('utf-8') if isinstance(bad, bytes) else bad
|
|
170
|
+
with self.assertRaises(DownstreamTokenRequestError):
|
|
171
|
+
self._verify(bad)
|
|
172
|
+
|
|
173
|
+
def test_verify_rejects_hs256_alg_confusion(self):
|
|
174
|
+
now = int(time.time())
|
|
175
|
+
hs256_token = jwt.encode(
|
|
176
|
+
{
|
|
177
|
+
'iss': TEST_ISSUER,
|
|
178
|
+
'aud': DOWNSTREAM_TOKEN_AUDIENCE,
|
|
179
|
+
'scope': DOWNSTREAM_TOKEN_SCOPE,
|
|
180
|
+
'agent_id': 'agent-abc',
|
|
181
|
+
'company_id': 42,
|
|
182
|
+
'resource': TEST_RESOURCE,
|
|
183
|
+
'jti': uuid.uuid4().hex,
|
|
184
|
+
'iat': now,
|
|
185
|
+
'exp': now + 30,
|
|
186
|
+
},
|
|
187
|
+
'symmetric-test-secret-for-hs256-rejection',
|
|
188
|
+
algorithm='HS256',
|
|
189
|
+
)
|
|
190
|
+
hs256_token = hs256_token.decode('utf-8') if isinstance(hs256_token, bytes) else hs256_token
|
|
191
|
+
with self.assertRaises(DownstreamTokenRequestError) as ctx:
|
|
192
|
+
self._verify(hs256_token)
|
|
193
|
+
self.assertIn('RS256', str(ctx.exception))
|
|
194
|
+
|
|
195
|
+
def test_verify_rejects_none_algorithm(self):
|
|
196
|
+
now = int(time.time())
|
|
197
|
+
header = {'alg': 'none', 'typ': 'JWT'}
|
|
198
|
+
payload = {
|
|
199
|
+
'iss': TEST_ISSUER,
|
|
200
|
+
'aud': DOWNSTREAM_TOKEN_AUDIENCE,
|
|
201
|
+
'scope': DOWNSTREAM_TOKEN_SCOPE,
|
|
202
|
+
'agent_id': 'agent-abc',
|
|
203
|
+
'company_id': 42,
|
|
204
|
+
'resource': TEST_RESOURCE,
|
|
205
|
+
'jti': uuid.uuid4().hex,
|
|
206
|
+
'iat': now,
|
|
207
|
+
'exp': now + 30,
|
|
208
|
+
}
|
|
209
|
+
none_token = jwt.encode(payload, '', algorithm='none', headers=header)
|
|
210
|
+
none_token = none_token.decode('utf-8') if isinstance(none_token, bytes) else none_token
|
|
211
|
+
with self.assertRaises(DownstreamTokenRequestError) as ctx:
|
|
212
|
+
self._verify(none_token)
|
|
213
|
+
self.assertIn('RS256', str(ctx.exception))
|
|
214
|
+
|
|
215
|
+
def test_verify_rejects_wrong_signing_key(self):
|
|
216
|
+
_other_jwks, other_private, other_kid = generate_test_rsa_jwks()
|
|
217
|
+
token = sign_downstream_token_request(
|
|
218
|
+
other_private,
|
|
219
|
+
other_kid,
|
|
220
|
+
TEST_ISSUER,
|
|
221
|
+
'agent-abc',
|
|
222
|
+
42,
|
|
223
|
+
TEST_RESOURCE,
|
|
224
|
+
30,
|
|
225
|
+
)
|
|
226
|
+
with self.assertRaises(DownstreamTokenRequestError):
|
|
227
|
+
self._verify(token)
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import time
|
|
2
|
+
import unittest
|
|
3
|
+
import uuid
|
|
4
|
+
|
|
5
|
+
import jwt
|
|
6
|
+
from cryptography.hazmat.primitives import serialization
|
|
7
|
+
|
|
8
|
+
from shellui_django.mcp.internal import (
|
|
9
|
+
CALL_LOG_AUDIENCE,
|
|
10
|
+
CALL_LOG_SCOPE,
|
|
11
|
+
INTERNAL_ASSERTION_MAX_LIFETIME_SECONDS,
|
|
12
|
+
REVOCATION_AUDIENCE,
|
|
13
|
+
REVOCATION_SCOPE,
|
|
14
|
+
InternalAssertionError,
|
|
15
|
+
build_mcp_call_log_assertion,
|
|
16
|
+
build_mcp_revocation_assertion,
|
|
17
|
+
verify_mcp_internal_assertion,
|
|
18
|
+
verify_rs256_mcp_assertion,
|
|
19
|
+
)
|
|
20
|
+
from shellui_django.mcp.tests.rs256_helpers import generate_test_rsa_jwks
|
|
21
|
+
|
|
22
|
+
TEST_ISSUER = 'https://ai.example.com'
|
|
23
|
+
TEST_TARGET = 'https://identity.example.com'
|
|
24
|
+
OTHER_ISSUER = 'https://other.example.com'
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class InternalAssertionRs256Tests(unittest.TestCase):
|
|
28
|
+
@classmethod
|
|
29
|
+
def setUpClass(cls):
|
|
30
|
+
cls.jwks, cls.private_pem, cls.kid = generate_test_rsa_jwks()
|
|
31
|
+
cls.other_jwks, cls.other_private_pem, cls.other_kid = generate_test_rsa_jwks()
|
|
32
|
+
cls.public_pem = (
|
|
33
|
+
serialization.load_pem_private_key(cls.private_pem.encode(), password=None)
|
|
34
|
+
.public_key()
|
|
35
|
+
.public_bytes(
|
|
36
|
+
encoding=serialization.Encoding.PEM,
|
|
37
|
+
format=serialization.PublicFormat.SubjectPublicKeyInfo,
|
|
38
|
+
)
|
|
39
|
+
.decode()
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
def _sign_revocation(self, **kwargs):
|
|
43
|
+
defaults = {
|
|
44
|
+
'audience_url': TEST_TARGET,
|
|
45
|
+
'private_key_pem': self.private_pem,
|
|
46
|
+
'kid': self.kid,
|
|
47
|
+
'issuer': TEST_ISSUER,
|
|
48
|
+
}
|
|
49
|
+
defaults.update(kwargs)
|
|
50
|
+
return build_mcp_revocation_assertion(**defaults)
|
|
51
|
+
|
|
52
|
+
def _verify(self, token: str, *, jwks_or_pem=None, issuer=TEST_ISSUER):
|
|
53
|
+
material = jwks_or_pem if jwks_or_pem is not None else self.jwks
|
|
54
|
+
return verify_mcp_internal_assertion(
|
|
55
|
+
token,
|
|
56
|
+
material,
|
|
57
|
+
expected_issuer=issuer,
|
|
58
|
+
expected_audience=REVOCATION_AUDIENCE,
|
|
59
|
+
expected_scope=REVOCATION_SCOPE,
|
|
60
|
+
expected_target=TEST_TARGET,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
def test_valid_round_trip(self):
|
|
64
|
+
token = self._sign_revocation()
|
|
65
|
+
claims = self._verify(token)
|
|
66
|
+
self.assertEqual(claims['iss'], TEST_ISSUER)
|
|
67
|
+
self.assertEqual(claims['sub'], 'service')
|
|
68
|
+
self.assertLessEqual(int(claims['exp']) - int(claims['iat']), INTERNAL_ASSERTION_MAX_LIFETIME_SECONDS)
|
|
69
|
+
|
|
70
|
+
def test_call_log_round_trip(self):
|
|
71
|
+
token = build_mcp_call_log_assertion(
|
|
72
|
+
audience_url=TEST_TARGET,
|
|
73
|
+
private_key_pem=self.private_pem,
|
|
74
|
+
kid=self.kid,
|
|
75
|
+
issuer=TEST_ISSUER,
|
|
76
|
+
)
|
|
77
|
+
claims = verify_rs256_mcp_assertion(
|
|
78
|
+
token,
|
|
79
|
+
self.jwks,
|
|
80
|
+
expected_issuer=TEST_ISSUER,
|
|
81
|
+
expected_audience=CALL_LOG_AUDIENCE,
|
|
82
|
+
expected_scope=CALL_LOG_SCOPE,
|
|
83
|
+
expected_target=TEST_TARGET,
|
|
84
|
+
)
|
|
85
|
+
self.assertEqual(claims['scope'], CALL_LOG_SCOPE)
|
|
86
|
+
|
|
87
|
+
def test_wrong_verification_key(self):
|
|
88
|
+
token = self._sign_revocation()
|
|
89
|
+
with self.assertRaises(InternalAssertionError):
|
|
90
|
+
self._verify(token, jwks_or_pem=self.other_jwks)
|
|
91
|
+
|
|
92
|
+
def test_wrong_issuer(self):
|
|
93
|
+
token = self._sign_revocation()
|
|
94
|
+
with self.assertRaises(InternalAssertionError):
|
|
95
|
+
self._verify(token, issuer=OTHER_ISSUER)
|
|
96
|
+
|
|
97
|
+
def test_hs256_rejected(self):
|
|
98
|
+
now = int(time.time())
|
|
99
|
+
hs256_token = jwt.encode(
|
|
100
|
+
{
|
|
101
|
+
'iss': TEST_ISSUER,
|
|
102
|
+
'aud': REVOCATION_AUDIENCE,
|
|
103
|
+
'sub': 'service',
|
|
104
|
+
'scope': REVOCATION_SCOPE,
|
|
105
|
+
'target': TEST_TARGET,
|
|
106
|
+
'iat': now,
|
|
107
|
+
'exp': now + 60,
|
|
108
|
+
'jti': uuid.uuid4().hex,
|
|
109
|
+
},
|
|
110
|
+
'shared-secret',
|
|
111
|
+
algorithm='HS256',
|
|
112
|
+
)
|
|
113
|
+
hs256_token = hs256_token.decode('utf-8') if isinstance(hs256_token, bytes) else hs256_token
|
|
114
|
+
with self.assertRaises(InternalAssertionError) as ctx:
|
|
115
|
+
self._verify(hs256_token)
|
|
116
|
+
self.assertIn('RS256', str(ctx.exception))
|
|
117
|
+
|
|
118
|
+
def test_alg_none_rejected(self):
|
|
119
|
+
now = int(time.time())
|
|
120
|
+
header = {'alg': 'none', 'typ': 'JWT'}
|
|
121
|
+
payload = {
|
|
122
|
+
'iss': TEST_ISSUER,
|
|
123
|
+
'aud': REVOCATION_AUDIENCE,
|
|
124
|
+
'sub': 'service',
|
|
125
|
+
'scope': REVOCATION_SCOPE,
|
|
126
|
+
'target': TEST_TARGET,
|
|
127
|
+
'iat': now,
|
|
128
|
+
'exp': now + 60,
|
|
129
|
+
'jti': uuid.uuid4().hex,
|
|
130
|
+
}
|
|
131
|
+
import base64
|
|
132
|
+
import json
|
|
133
|
+
|
|
134
|
+
def b64(data):
|
|
135
|
+
return base64.urlsafe_b64encode(json.dumps(data, separators=(',', ':')).encode()).rstrip(b'=').decode()
|
|
136
|
+
|
|
137
|
+
token = f'{b64(header)}.{b64(payload)}.'
|
|
138
|
+
with self.assertRaises(InternalAssertionError):
|
|
139
|
+
self._verify(token)
|
|
140
|
+
|
|
141
|
+
def test_expired_rejected(self):
|
|
142
|
+
now = int(time.time())
|
|
143
|
+
claims = {
|
|
144
|
+
'iss': TEST_ISSUER,
|
|
145
|
+
'aud': REVOCATION_AUDIENCE,
|
|
146
|
+
'sub': 'service',
|
|
147
|
+
'scope': REVOCATION_SCOPE,
|
|
148
|
+
'target': TEST_TARGET,
|
|
149
|
+
'iat': now - 120,
|
|
150
|
+
'exp': now - 60,
|
|
151
|
+
'jti': uuid.uuid4().hex,
|
|
152
|
+
}
|
|
153
|
+
token = jwt.encode(claims, self.private_pem, algorithm='RS256', headers={'kid': self.kid})
|
|
154
|
+
token = token.decode('utf-8') if isinstance(token, bytes) else token
|
|
155
|
+
with self.assertRaises(InternalAssertionError):
|
|
156
|
+
self._verify(token)
|
|
157
|
+
|
|
158
|
+
def test_wrong_audience(self):
|
|
159
|
+
token = self._sign_revocation()
|
|
160
|
+
with self.assertRaises(InternalAssertionError):
|
|
161
|
+
verify_mcp_internal_assertion(
|
|
162
|
+
token,
|
|
163
|
+
self.jwks,
|
|
164
|
+
expected_issuer=TEST_ISSUER,
|
|
165
|
+
expected_audience='wrong-audience',
|
|
166
|
+
expected_scope=REVOCATION_SCOPE,
|
|
167
|
+
expected_target=TEST_TARGET,
|
|
168
|
+
)
|
|
169
|
+
|
|
170
|
+
def test_wrong_scope(self):
|
|
171
|
+
token = self._sign_revocation()
|
|
172
|
+
with self.assertRaises(InternalAssertionError):
|
|
173
|
+
verify_mcp_internal_assertion(
|
|
174
|
+
token,
|
|
175
|
+
self.jwks,
|
|
176
|
+
expected_issuer=TEST_ISSUER,
|
|
177
|
+
expected_audience=REVOCATION_AUDIENCE,
|
|
178
|
+
expected_scope='wrong.scope',
|
|
179
|
+
expected_target=TEST_TARGET,
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
def test_wrong_target(self):
|
|
183
|
+
token = self._sign_revocation()
|
|
184
|
+
with self.assertRaises(InternalAssertionError):
|
|
185
|
+
verify_mcp_internal_assertion(
|
|
186
|
+
token,
|
|
187
|
+
self.jwks,
|
|
188
|
+
expected_issuer=TEST_ISSUER,
|
|
189
|
+
expected_audience=REVOCATION_AUDIENCE,
|
|
190
|
+
expected_scope=REVOCATION_SCOPE,
|
|
191
|
+
expected_target='https://evil.example.com',
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
def test_jti_replay_rejected(self):
|
|
195
|
+
token = self._sign_revocation()
|
|
196
|
+
seen: set[str] = set()
|
|
197
|
+
|
|
198
|
+
def register(jti: str) -> bool:
|
|
199
|
+
if jti in seen:
|
|
200
|
+
return False
|
|
201
|
+
seen.add(jti)
|
|
202
|
+
return True
|
|
203
|
+
|
|
204
|
+
verify_mcp_internal_assertion(
|
|
205
|
+
token,
|
|
206
|
+
self.jwks,
|
|
207
|
+
expected_issuer=TEST_ISSUER,
|
|
208
|
+
expected_audience=REVOCATION_AUDIENCE,
|
|
209
|
+
expected_scope=REVOCATION_SCOPE,
|
|
210
|
+
expected_target=TEST_TARGET,
|
|
211
|
+
register_jti=register,
|
|
212
|
+
)
|
|
213
|
+
with self.assertRaises(InternalAssertionError) as ctx:
|
|
214
|
+
verify_mcp_internal_assertion(
|
|
215
|
+
token,
|
|
216
|
+
self.jwks,
|
|
217
|
+
expected_issuer=TEST_ISSUER,
|
|
218
|
+
expected_audience=REVOCATION_AUDIENCE,
|
|
219
|
+
expected_scope=REVOCATION_SCOPE,
|
|
220
|
+
expected_target=TEST_TARGET,
|
|
221
|
+
register_jti=register,
|
|
222
|
+
)
|
|
223
|
+
self.assertIn('replay', str(ctx.exception).lower())
|
|
224
|
+
|
|
225
|
+
def test_public_pem_verification(self):
|
|
226
|
+
token = self._sign_revocation()
|
|
227
|
+
claims = self._verify(token, jwks_or_pem=self.public_pem)
|
|
228
|
+
self.assertEqual(claims['iss'], TEST_ISSUER)
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/mcp_routing_urlconf.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_openapi_tools.py
RENAMED
|
File without changes
|
|
File without changes
|
{shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_resources.py
RENAMED
|
File without changes
|
|
File without changes
|
{shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_server_routing.py
RENAMED
|
File without changes
|
{shellui_django-0.2.0 → shellui_django-0.4.0}/src/shellui_django/mcp/tests/test_write_gate_mcp.py
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|