shellui-django 0.2.0__tar.gz → 0.3.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.
Files changed (36) hide show
  1. {shellui_django-0.2.0 → shellui_django-0.3.0}/CHANGELOG.md +16 -0
  2. {shellui_django-0.2.0 → shellui_django-0.3.0}/PKG-INFO +6 -1
  3. {shellui_django-0.2.0 → shellui_django-0.3.0}/README.md +5 -0
  4. {shellui_django-0.2.0 → shellui_django-0.3.0}/pyproject.toml +1 -1
  5. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/__init__.py +1 -1
  6. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/__init__.py +14 -0
  7. shellui_django-0.3.0/src/shellui_django/mcp/delegation.py +165 -0
  8. shellui_django-0.3.0/src/shellui_django/mcp/tests/test_delegation.py +227 -0
  9. {shellui_django-0.2.0 → shellui_django-0.3.0}/.gitignore +0 -0
  10. {shellui_django-0.2.0 → shellui_django-0.3.0}/LICENSE +0 -0
  11. {shellui_django-0.2.0 → shellui_django-0.3.0}/SECURITY.md +0 -0
  12. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/decorators.py +0 -0
  13. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/gateway.py +0 -0
  14. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/identity_jwks.py +0 -0
  15. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/internal.py +0 -0
  16. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/masking.py +0 -0
  17. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/openapi_mcp.py +0 -0
  18. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/openapi_tools.py +0 -0
  19. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/rate_limit.py +0 -0
  20. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/resources.py +0 -0
  21. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/routing.py +0 -0
  22. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/server.py +0 -0
  23. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/tests/__init__.py +0 -0
  24. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/tests/mcp_routing_urlconf.py +0 -0
  25. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/tests/rs256_helpers.py +0 -0
  26. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/tests/test_gateway.py +0 -0
  27. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/tests/test_internal_revocation.py +0 -0
  28. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/tests/test_masking.py +0 -0
  29. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/tests/test_openapi_tools.py +0 -0
  30. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/tests/test_package.py +0 -0
  31. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/tests/test_resources.py +0 -0
  32. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/tests/test_routing.py +0 -0
  33. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/tests/test_server_routing.py +0 -0
  34. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/tests/test_write_gate_mcp.py +0 -0
  35. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/mcp/write_gate.py +0 -0
  36. {shellui_django-0.2.0 → shellui_django-0.3.0}/src/shellui_django/testing/__init__.py +0 -0
@@ -23,6 +23,22 @@ 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.3.0] - 2026-11-02
27
+
28
+ ### ✨ Feature
29
+
30
+ - 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.
31
+
32
+ ### 📚 Documentation
33
+
34
+ - Document downstream token delegation in `docs/mcp.md`.
35
+
36
+ ## [0.2.1] - 2026-11-02
37
+
38
+ ### 📚 Documentation
39
+
40
+ - Add CI, PyPI, Python and license badges to the README.
41
+
26
42
  ## [0.2.0] - 2026-11-02
27
43
 
28
44
  ### ✨ Feature
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: shellui-django
3
- Version: 0.2.0
3
+ Version: 0.3.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
+ [![CI](https://github.com/shellui/django-commons/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/shellui/django-commons/actions/workflows/ci.yml)
36
+ [![PyPI](https://img.shields.io/pypi/v/shellui-django)](https://pypi.org/project/shellui-django/)
37
+ [![Python](https://img.shields.io/pypi/pyversions/shellui-django)](https://pypi.org/project/shellui-django/)
38
+ [![License: MIT](https://img.shields.io/github/license/shellui/django-commons)](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
+ [![CI](https://github.com/shellui/django-commons/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/shellui/django-commons/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/shellui-django)](https://pypi.org/project/shellui-django/)
5
+ [![Python](https://img.shields.io/pypi/pyversions/shellui-django)](https://pypi.org/project/shellui-django/)
6
+ [![License: MIT](https://img.shields.io/github/license/shellui/django-commons)](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,6 +1,6 @@
1
1
  [project]
2
2
  name = "shellui-django"
3
- version = "0.2.0"
3
+ version = "0.3.0"
4
4
  description = "Shared Django libraries for Shellui services"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -1,3 +1,3 @@
1
1
  """Shared Django libraries for Shellui services."""
2
2
 
3
- __version__ = '0.2.0'
3
+ __version__ = '0.3.0'
@@ -1,6 +1,14 @@
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,6 +23,12 @@ from shellui_django.mcp.internal import (
15
23
 
16
24
  __all__ = [
17
25
  'mcp_expose_tool',
26
+ 'DOWNSTREAM_TOKEN_AUDIENCE',
27
+ 'DOWNSTREAM_TOKEN_REQUEST_MAX_LIFETIME_SECONDS',
28
+ 'DOWNSTREAM_TOKEN_SCOPE',
29
+ 'DownstreamTokenRequestError',
30
+ 'sign_downstream_token_request',
31
+ 'verify_downstream_token_request',
18
32
  'APPROVAL_AUDIENCE',
19
33
  'APPROVAL_SCOPE',
20
34
  'REVOCATION_CACHE_SECONDS',
@@ -0,0 +1,165 @@
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
+ if isinstance(public_jwks_or_pem, str):
95
+ pem = public_jwks_or_pem.strip()
96
+ if not pem:
97
+ raise DownstreamTokenRequestError('Verification key is required.')
98
+ return pem
99
+ if isinstance(public_jwks_or_pem, dict):
100
+ from shellui_django.mcp.identity_jwks import IdentityJwksError, resolve_verification_key
101
+
102
+ try:
103
+ return resolve_verification_key(token, public_jwks_or_pem)
104
+ except IdentityJwksError as exc:
105
+ raise DownstreamTokenRequestError(str(exc)) from exc
106
+ raise DownstreamTokenRequestError('public_jwks_or_pem must be a PEM string or JWKS document.')
107
+
108
+
109
+ def _assert_lifetime_within_limit(claims: dict[str, Any]) -> None:
110
+ try:
111
+ iat = int(claims['iat'])
112
+ exp = int(claims['exp'])
113
+ except (KeyError, TypeError, ValueError) as exc:
114
+ raise DownstreamTokenRequestError('Invalid iat or exp.') from exc
115
+ if exp <= iat:
116
+ raise DownstreamTokenRequestError('Token lifetime is invalid.')
117
+ if exp - iat > DOWNSTREAM_TOKEN_REQUEST_MAX_LIFETIME_SECONDS:
118
+ raise DownstreamTokenRequestError('Token lifetime exceeds the maximum allowed.')
119
+
120
+
121
+ def verify_downstream_token_request(
122
+ token: str,
123
+ public_jwks_or_pem: dict[str, Any] | str,
124
+ expected_issuer: str,
125
+ ) -> dict[str, Any]:
126
+ """Verify a gateway-signed downstream token request; returns claims (including ``jti`` for one-time use)."""
127
+ normalized = _normalize_bearer_token(token)
128
+ issuer = (expected_issuer or '').strip().rstrip('/')
129
+ if not issuer:
130
+ raise DownstreamTokenRequestError('expected_issuer is required.')
131
+ try:
132
+ header = jwt.get_unverified_header(normalized)
133
+ except jwt.PyJWTError as exc:
134
+ raise DownstreamTokenRequestError('Invalid downstream token request JWT.') from exc
135
+ alg = str(header.get('alg') or '')
136
+ if alg != 'RS256':
137
+ raise DownstreamTokenRequestError('Downstream token request JWT must use RS256.')
138
+ key = _resolve_verification_key(normalized, public_jwks_or_pem)
139
+ try:
140
+ claims = jwt.decode(
141
+ normalized,
142
+ key=key,
143
+ algorithms=['RS256'],
144
+ audience=DOWNSTREAM_TOKEN_AUDIENCE,
145
+ issuer=issuer,
146
+ leeway=DOWNSTREAM_TOKEN_REQUEST_LEEWAY_SECONDS,
147
+ options={'require': list(_REQUIRED_CLAIMS)},
148
+ )
149
+ except jwt.PyJWTError as exc:
150
+ raise DownstreamTokenRequestError('Invalid downstream token request JWT.') from exc
151
+ scope = str(claims.get('scope') or '')
152
+ if scope != DOWNSTREAM_TOKEN_SCOPE:
153
+ raise DownstreamTokenRequestError('Downstream token request scope mismatch.')
154
+ aud = claims.get('aud')
155
+ if isinstance(aud, list):
156
+ if DOWNSTREAM_TOKEN_AUDIENCE not in aud:
157
+ raise DownstreamTokenRequestError('Downstream token request audience mismatch.')
158
+ elif str(aud or '') != DOWNSTREAM_TOKEN_AUDIENCE:
159
+ raise DownstreamTokenRequestError('Downstream token request audience mismatch.')
160
+ _assert_lifetime_within_limit(claims)
161
+ for name in _REQUIRED_CLAIMS:
162
+ value = claims.get(name)
163
+ if value is None or (isinstance(value, str) and not value.strip()):
164
+ raise DownstreamTokenRequestError(f'Missing required claim: {name}.')
165
+ return dict(claims)
@@ -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)
File without changes