Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ea82ac44e9
|
||
|
|
e73c4b2c18
|
No files matched your search
@@ -164,6 +164,9 @@ authentication methods (`private_key_jwt`, mTLS) is not supported.
|
||||
- Generic OIDC discovery
|
||||
- Authorization Code Flow with PKCE (S256)
|
||||
- ID token signature validation with JWKS
|
||||
- Issuer validation against discovery metadata, including support for
|
||||
Microsoft Entra ID `{tenantid}` issuer templates
|
||||
- Refreshed ID token validation on token refresh
|
||||
- `state` and `nonce` protection
|
||||
- Session fixation defense via `regenerate_id()` after login
|
||||
- Optional userinfo endpoint fetch
|
||||
@@ -174,8 +177,37 @@ authentication methods (`private_key_jwt`, mTLS) is not supported.
|
||||
- `single-identity` (default) or `multi-identity` session strategy
|
||||
- Composable with any other `KayaMixin` (RSGI, MCP, etc.)
|
||||
|
||||
## Microsoft Entra ID
|
||||
|
||||
Entra ID v2 ID tokens carry an `iss` claim of the form
|
||||
`https://login.microsoftonline.com/<tenant-id>/v2.0`, while the discovery
|
||||
metadata for the multi-tenant endpoints advertises the templated issuer
|
||||
`https://login.microsoftonline.com/{tenantid}/v2.0`. `kaya-oidc` validates the
|
||||
`iss` claim against the discovered metadata and substitutes the token's `tid`
|
||||
claim into `{tenantid}`, so both tenant-specific and multi-tenant issuers work:
|
||||
|
||||
```python
|
||||
OIDCConfig(
|
||||
issuer='https://login.microsoftonline.com/<tenant-id-or-domain>/v2.0',
|
||||
client_id=os.environ['OIDC_CLIENT_ID'],
|
||||
client_secret=os.environ['OIDC_CLIENT_SECRET'],
|
||||
redirect_uri='https://example.com/auth/callback',
|
||||
)
|
||||
```
|
||||
|
||||
Use a tenant-specific issuer (the tenant GUID or a verified domain name) to
|
||||
restrict logins to that tenant. The `common` and `organizations` aliases are
|
||||
multi-tenant: any tenant in that cloud can obtain an ID token that passes
|
||||
validation. If you build a multi-tenant application, check the `tid` claim
|
||||
against the tenants you trust.
|
||||
|
||||
## Security notes
|
||||
|
||||
- The `iss` claim is validated against the `issuer` value of the provider's
|
||||
discovery document, not against `OIDCConfig.issuer` (they can differ, for
|
||||
example for Entra ID multi-tenant endpoints).
|
||||
- Refreshed ID tokens are validated before being stored; the `nonce` is also
|
||||
checked when the refreshed token carries one.
|
||||
- The `none` signing algorithm is rejected by default.
|
||||
- Only algorithms listed in `OIDCConfig.allowed_id_token_algorithms` are accepted.
|
||||
- Always use HTTPS for `redirect_uri` in production.
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import re
|
||||
from typing import Any, Mapping, Optional, Sequence, cast
|
||||
from urllib.parse import urlencode
|
||||
|
||||
@@ -8,6 +9,8 @@ from jwt import PyJWK
|
||||
from ._config import PARPolicy, OIDCConfig
|
||||
from ._utils import generate_nonce, generate_pkce, generate_state
|
||||
|
||||
_TENANT_ID_PLACEHOLDER = re.compile(r'\{tenantid\}', re.IGNORECASE)
|
||||
|
||||
|
||||
class OIDCClient:
|
||||
"""Low-level OIDC client implementing discovery, PKCE, and token validation."""
|
||||
@@ -164,6 +167,29 @@ class OIDCClient:
|
||||
return cast(Mapping[str, Any], resp.json())
|
||||
|
||||
async def validate_id_token(self, id_token: str, nonce: str) -> Mapping[str, Any]:
|
||||
payload = await self._decode_id_token(id_token)
|
||||
if payload.get('nonce') != nonce:
|
||||
raise ValueError('ID token nonce mismatch')
|
||||
return payload
|
||||
|
||||
async def validate_refreshed_id_token(
|
||||
self,
|
||||
id_token: str,
|
||||
expected_nonce: Optional[str] = None,
|
||||
) -> Mapping[str, Any]:
|
||||
"""Validate an ID token returned by the refresh token grant.
|
||||
|
||||
Unlike the authorization code flow, the provider may omit the ``nonce``
|
||||
claim; when it is present and the original nonce is known, the two must
|
||||
match (OIDC Core 12.2).
|
||||
"""
|
||||
payload = await self._decode_id_token(id_token)
|
||||
token_nonce = payload.get('nonce')
|
||||
if token_nonce is not None and expected_nonce is not None and token_nonce != expected_nonce:
|
||||
raise ValueError('ID token nonce mismatch')
|
||||
return payload
|
||||
|
||||
async def _decode_id_token(self, id_token: str) -> Mapping[str, Any]:
|
||||
header = jwt.get_unverified_header(id_token)
|
||||
alg = header.get('alg')
|
||||
if not isinstance(alg, str):
|
||||
@@ -172,29 +198,59 @@ class OIDCClient:
|
||||
if alg == 'none':
|
||||
if not self._config.allow_unsigned_id_tokens:
|
||||
raise ValueError('Unsigned ID tokens are not allowed')
|
||||
metadata_issuer = await self._get_metadata_issuer()
|
||||
payload = jwt.decode(
|
||||
id_token,
|
||||
options={'verify_signature': False},
|
||||
audience=self._config.client_id,
|
||||
options={
|
||||
'verify_signature': False,
|
||||
'verify_aud': True,
|
||||
'verify_exp': True,
|
||||
'verify_iat': True,
|
||||
'verify_nbf': True,
|
||||
},
|
||||
)
|
||||
else:
|
||||
if alg not in self._config.allowed_id_token_algorithms:
|
||||
raise ValueError(f'ID token algorithm {alg} is not allowed')
|
||||
metadata_issuer = await self._get_metadata_issuer()
|
||||
jwks = await self._ensure_jwks()
|
||||
signing_key = self._get_signing_key(jwks, header.get('kid'), alg)
|
||||
payload = jwt.decode(
|
||||
id_token,
|
||||
signing_key.key,
|
||||
algorithms=[alg],
|
||||
issuer=self._config.issuer,
|
||||
audience=self._config.client_id,
|
||||
)
|
||||
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError('ID token payload is not a JSON object')
|
||||
if payload.get('nonce') != nonce:
|
||||
raise ValueError('ID token nonce mismatch')
|
||||
self._validate_issuer(payload, metadata_issuer)
|
||||
return payload
|
||||
|
||||
async def _get_metadata_issuer(self) -> str:
|
||||
metadata = await self._ensure_metadata()
|
||||
issuer = metadata.get('issuer')
|
||||
if not isinstance(issuer, str):
|
||||
raise RuntimeError('OIDC provider does not advertise an issuer')
|
||||
return issuer
|
||||
|
||||
@staticmethod
|
||||
def _validate_issuer(payload: Mapping[str, Any], metadata_issuer: str) -> None:
|
||||
iss = payload.get('iss')
|
||||
if not isinstance(iss, str):
|
||||
raise jwt.MissingRequiredClaimError('iss')
|
||||
|
||||
expected = metadata_issuer
|
||||
if _TENANT_ID_PLACEHOLDER.search(expected):
|
||||
tenant_id = payload.get('tid')
|
||||
if not isinstance(tenant_id, str):
|
||||
raise jwt.InvalidIssuerError('Invalid issuer')
|
||||
expected = _TENANT_ID_PLACEHOLDER.sub(tenant_id, expected, count=1)
|
||||
|
||||
if iss != expected:
|
||||
raise jwt.InvalidIssuerError('Invalid issuer')
|
||||
|
||||
def _get_signing_key(self, jwks: Mapping[str, Any], kid: Optional[str], alg: str) -> PyJWK:
|
||||
keys = jwks.get('keys')
|
||||
if not isinstance(keys, Sequence):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from typing import Any, Awaitable, Callable, Literal, Mapping, Optional, Sequence, cast
|
||||
|
||||
import jwt
|
||||
from kaya.core import HttpContext, KayaApp, KayaMixin
|
||||
from kaya.session import Session, SessionMixin
|
||||
from urllib.parse import parse_qs
|
||||
@@ -175,8 +176,9 @@ class OIDCMixin(KayaMixin):
|
||||
user.update(userinfo)
|
||||
|
||||
session.pop(self._key('state'), None)
|
||||
session.pop(self._key('nonce'), None)
|
||||
session.pop(self._key('code_verifier'), None)
|
||||
# Keep this provider's nonce so refreshed ID tokens can be
|
||||
# checked for nonce continuity (OIDC Core 12.2).
|
||||
|
||||
session[self._key('user')] = user
|
||||
session[self._key('id_token')] = id_token
|
||||
@@ -190,7 +192,7 @@ class OIDCMixin(KayaMixin):
|
||||
|
||||
session.regenerate_id()
|
||||
await ctx.send_empty(302, {'Location': self._config.post_login_redirect})
|
||||
except ValueError as exc:
|
||||
except (ValueError, jwt.PyJWTError) as exc:
|
||||
await ctx.send_str(400, f'Authentication failed: {exc}')
|
||||
|
||||
@app.GET(self._config.logout_path)
|
||||
@@ -279,10 +281,22 @@ class OIDCMixin(KayaMixin):
|
||||
try:
|
||||
token_response = await self._client.refresh_token(refresh_token)
|
||||
access_token = token_response.get('access_token')
|
||||
id_token = token_response.get('id_token')
|
||||
if isinstance(id_token, str):
|
||||
stored_nonce = session.get(self._key('nonce'))
|
||||
claims = await self._client.validate_refreshed_id_token(
|
||||
id_token,
|
||||
stored_nonce if isinstance(stored_nonce, str) else None,
|
||||
)
|
||||
user = session.get(self._key('user'))
|
||||
original_sub = user.get('sub') if isinstance(user, Mapping) else None
|
||||
if isinstance(original_sub, str) and claims.get('sub') != original_sub:
|
||||
raise ValueError('ID token subject mismatch')
|
||||
|
||||
if isinstance(access_token, str):
|
||||
session[self._key('access_token')] = access_token
|
||||
if 'id_token' in token_response:
|
||||
session[self._key('id_token')] = token_response['id_token']
|
||||
if isinstance(id_token, str):
|
||||
session[self._key('id_token')] = id_token
|
||||
if 'refresh_token' in token_response:
|
||||
session[self._key('refresh_token')] = token_response['refresh_token']
|
||||
return access_token if isinstance(access_token, str) else None
|
||||
|
||||
@@ -2,7 +2,7 @@ import base64
|
||||
import unittest
|
||||
from dataclasses import replace
|
||||
from time import time
|
||||
from typing import Mapping, Optional
|
||||
from typing import Any, Mapping, Optional
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
||||
import httpx
|
||||
@@ -24,6 +24,7 @@ class MockOIDCProvider:
|
||||
issuer: Optional[str] = None,
|
||||
sub: str = 'user123',
|
||||
email: str = 'user@example.com',
|
||||
metadata_issuer: Optional[str] = None,
|
||||
supports_par: bool = False,
|
||||
require_par: bool = False,
|
||||
par_error: bool = False,
|
||||
@@ -32,14 +33,19 @@ class MockOIDCProvider:
|
||||
self.public_key = self.private_key.public_key()
|
||||
self.kid = 'mock-key'
|
||||
self.issuer = issuer or f'https://{name}-oidc.local'
|
||||
self.metadata_issuer = metadata_issuer if metadata_issuer is not None else self.issuer
|
||||
self.sub = sub
|
||||
self.email = email
|
||||
self.nonce = f'{name}-nonce-value'
|
||||
self.token_issuer: Optional[str] = None
|
||||
self.token_tid: Optional[str] = None
|
||||
self.token_sub: Optional[str] = None
|
||||
self.token_expired = False
|
||||
self.par_error = par_error
|
||||
self.par_requests: list[dict[str, list[str]]] = []
|
||||
self.par_auth_headers: list[Optional[str]] = []
|
||||
self.discovery = {
|
||||
'issuer': self.issuer,
|
||||
'issuer': self.metadata_issuer,
|
||||
'authorization_endpoint': f'{self.issuer}/auth',
|
||||
'token_endpoint': f'{self.issuer}/token',
|
||||
'userinfo_endpoint': f'{self.issuer}/userinfo',
|
||||
@@ -64,17 +70,29 @@ class MockOIDCProvider:
|
||||
'alg': 'RS256',
|
||||
}
|
||||
|
||||
def issue_id_token(self, nonce: str, audience: str, expired: bool = False, wrong_nonce: bool = False) -> str:
|
||||
def issue_id_token(
|
||||
self,
|
||||
nonce: Optional[str],
|
||||
audience: str,
|
||||
expired: bool = False,
|
||||
wrong_nonce: bool = False,
|
||||
issuer: Optional[str] = None,
|
||||
tid: Optional[str] = None,
|
||||
sub: Optional[str] = None,
|
||||
) -> str:
|
||||
now = time()
|
||||
exp = now - 3600 if expired else now + 3600
|
||||
payload = {
|
||||
'sub': self.sub,
|
||||
'iss': self.issuer,
|
||||
payload: dict[str, Any] = {
|
||||
'sub': sub if sub is not None else self.sub,
|
||||
'iss': issuer if issuer is not None else self.issuer,
|
||||
'aud': audience,
|
||||
'iat': now,
|
||||
'exp': exp,
|
||||
'nonce': 'wrong-nonce' if wrong_nonce else nonce,
|
||||
}
|
||||
if nonce is not None:
|
||||
payload['nonce'] = 'wrong-nonce' if wrong_nonce else nonce
|
||||
if tid is not None:
|
||||
payload['tid'] = tid
|
||||
return jwt.encode(
|
||||
payload,
|
||||
self.private_key,
|
||||
@@ -82,13 +100,39 @@ class MockOIDCProvider:
|
||||
headers={'kid': self.kid},
|
||||
)
|
||||
|
||||
def issue_unsigned_id_token(
|
||||
self,
|
||||
nonce: str,
|
||||
audience: str,
|
||||
issuer: Optional[str] = None,
|
||||
) -> str:
|
||||
payload: dict[str, Any] = {
|
||||
'sub': self.sub,
|
||||
'iss': issuer if issuer is not None else self.issuer,
|
||||
'aud': audience,
|
||||
'iat': time(),
|
||||
'exp': time() + 3600,
|
||||
'nonce': nonce,
|
||||
}
|
||||
return jwt.encode(payload, None, algorithm='none')
|
||||
|
||||
def _issue_configured_token(self, audience: str) -> str:
|
||||
return self.issue_id_token(
|
||||
self.nonce,
|
||||
audience,
|
||||
expired=self.token_expired,
|
||||
issuer=self.token_issuer,
|
||||
tid=self.token_tid,
|
||||
sub=self.token_sub if self.token_sub is not None else self.sub,
|
||||
)
|
||||
|
||||
def handle_request(self, request: httpx.Request) -> httpx.Response:
|
||||
url = str(request.url)
|
||||
path = urlparse(url).path
|
||||
# Serve discovery and JWKS for any host so that issuer-mismatch tests can still fetch keys.
|
||||
if path == '/.well-known/openid-configuration':
|
||||
if path.endswith('/.well-known/openid-configuration'):
|
||||
return httpx.Response(200, json=self.discovery)
|
||||
if path == '/jwks':
|
||||
if path.endswith('/jwks'):
|
||||
return httpx.Response(200, json={'keys': [self._public_key_to_jwk()]})
|
||||
if path == '/par':
|
||||
if request.method != 'POST':
|
||||
@@ -111,13 +155,13 @@ class MockOIDCProvider:
|
||||
return httpx.Response(200, json={
|
||||
'access_token': 'new-access-token',
|
||||
'refresh_token': 'new-refresh-token',
|
||||
'id_token': self.issue_id_token('refreshed-nonce', data.get('client_id', 'client')),
|
||||
'id_token': self._issue_configured_token(data.get('client_id', 'client')),
|
||||
'token_type': 'Bearer',
|
||||
})
|
||||
return httpx.Response(200, json={
|
||||
'access_token': 'mock-access-token',
|
||||
'refresh_token': 'mock-refresh-token',
|
||||
'id_token': self.issue_id_token(self.nonce, data.get('client_id', 'client')),
|
||||
'id_token': self._issue_configured_token(data.get('client_id', 'client')),
|
||||
'token_type': 'Bearer',
|
||||
})
|
||||
if path == '/userinfo':
|
||||
@@ -185,17 +229,110 @@ class OIDCClientTest(unittest.TestCase):
|
||||
|
||||
@async_test
|
||||
async def test_validate_id_token_wrong_issuer(self) -> None:
|
||||
token = self.provider.issue_id_token('nonce-value', 'client')
|
||||
provider = MockOIDCProvider(metadata_issuer='https://other-issuer.local')
|
||||
token = provider.issue_id_token('nonce-value', 'client')
|
||||
config = OIDCConfig(
|
||||
issuer='https://wrong-issuer.local',
|
||||
issuer=provider.issuer,
|
||||
client_id='client',
|
||||
redirect_uri='http://localhost:8000/auth/callback',
|
||||
http_client=self.http_client,
|
||||
http_client=httpx.AsyncClient(transport=MockTransport(provider)),
|
||||
)
|
||||
client = OIDCClient(config)
|
||||
with self.assertRaises(jwt.InvalidIssuerError):
|
||||
await client.validate_id_token(token, 'nonce-value')
|
||||
|
||||
@async_test
|
||||
async def test_validate_id_token_uses_discovered_issuer(self) -> None:
|
||||
# The configured issuer is only used as the discovery URL; the ID token
|
||||
# is validated against the issuer advertised by the discovery document.
|
||||
provider = MockOIDCProvider(metadata_issuer='https://canonical-issuer.local')
|
||||
token = provider.issue_id_token('nonce-value', 'client', issuer='https://canonical-issuer.local')
|
||||
config = OIDCConfig(
|
||||
issuer=provider.issuer,
|
||||
client_id='client',
|
||||
redirect_uri='http://localhost:8000/auth/callback',
|
||||
http_client=httpx.AsyncClient(transport=MockTransport(provider)),
|
||||
)
|
||||
client = OIDCClient(config)
|
||||
claims = await client.validate_id_token(token, 'nonce-value')
|
||||
self.assertEqual('user123', claims['sub'])
|
||||
|
||||
@async_test
|
||||
async def test_validate_id_token_entra_style_issuer_template(self) -> None:
|
||||
# Microsoft Entra ID multi-tenant metadata advertises
|
||||
# https://login.microsoftonline.com/{tenantid}/v2.0 and tokens carry
|
||||
# the concrete tenant id in both iss and tid.
|
||||
tenant = '11111111-2222-3333-4444-555555555555'
|
||||
provider = MockOIDCProvider(metadata_issuer='https://mock-oidc.local/{tenantid}/v2.0')
|
||||
token = provider.issue_id_token(
|
||||
'nonce-value',
|
||||
'client',
|
||||
issuer=f'https://mock-oidc.local/{tenant}/v2.0',
|
||||
tid=tenant,
|
||||
)
|
||||
config = OIDCConfig(
|
||||
issuer=f'{provider.issuer}/common/v2.0',
|
||||
client_id='client',
|
||||
redirect_uri='http://localhost:8000/auth/callback',
|
||||
http_client=httpx.AsyncClient(transport=MockTransport(provider)),
|
||||
)
|
||||
client = OIDCClient(config)
|
||||
claims = await client.validate_id_token(token, 'nonce-value')
|
||||
self.assertEqual(tenant, claims['tid'])
|
||||
|
||||
@async_test
|
||||
async def test_validate_id_token_template_with_wrong_tid(self) -> None:
|
||||
tenant = '11111111-2222-3333-4444-555555555555'
|
||||
other_tenant = '99999999-8888-7777-6666-555555555555'
|
||||
provider = MockOIDCProvider(metadata_issuer='https://mock-oidc.local/{tenantid}/v2.0')
|
||||
token = provider.issue_id_token(
|
||||
'nonce-value',
|
||||
'client',
|
||||
issuer=f'https://mock-oidc.local/{tenant}/v2.0',
|
||||
tid=other_tenant,
|
||||
)
|
||||
config = OIDCConfig(
|
||||
issuer=f'{provider.issuer}/common/v2.0',
|
||||
client_id='client',
|
||||
redirect_uri='http://localhost:8000/auth/callback',
|
||||
http_client=httpx.AsyncClient(transport=MockTransport(provider)),
|
||||
)
|
||||
client = OIDCClient(config)
|
||||
with self.assertRaises(jwt.InvalidIssuerError):
|
||||
await client.validate_id_token(token, 'nonce-value')
|
||||
|
||||
@async_test
|
||||
async def test_validate_id_token_template_without_tid(self) -> None:
|
||||
tenant = '11111111-2222-3333-4444-555555555555'
|
||||
provider = MockOIDCProvider(metadata_issuer='https://mock-oidc.local/{tenantid}/v2.0')
|
||||
token = provider.issue_id_token(
|
||||
'nonce-value',
|
||||
'client',
|
||||
issuer=f'https://mock-oidc.local/{tenant}/v2.0',
|
||||
)
|
||||
config = OIDCConfig(
|
||||
issuer=f'{provider.issuer}/common/v2.0',
|
||||
client_id='client',
|
||||
redirect_uri='http://localhost:8000/auth/callback',
|
||||
http_client=httpx.AsyncClient(transport=MockTransport(provider)),
|
||||
)
|
||||
client = OIDCClient(config)
|
||||
with self.assertRaises(jwt.InvalidIssuerError):
|
||||
await client.validate_id_token(token, 'nonce-value')
|
||||
|
||||
@async_test
|
||||
async def test_validate_refreshed_id_token_allows_missing_nonce(self) -> None:
|
||||
token = self.provider.issue_id_token(None, 'client')
|
||||
claims = await self.client.validate_refreshed_id_token(token, 'nonce-value')
|
||||
self.assertEqual('user123', claims['sub'])
|
||||
|
||||
@async_test
|
||||
async def test_validate_refreshed_id_token_wrong_nonce(self) -> None:
|
||||
token = self.provider.issue_id_token('other-nonce', 'client')
|
||||
with self.assertRaises(ValueError) as ctx:
|
||||
await self.client.validate_refreshed_id_token(token, 'nonce-value')
|
||||
self.assertIn('nonce', str(ctx.exception))
|
||||
|
||||
@async_test
|
||||
async def test_validate_id_token_disallowed_algorithm(self) -> None:
|
||||
token = self.provider.issue_id_token('nonce-value', 'client')
|
||||
@@ -211,6 +348,55 @@ class OIDCClientTest(unittest.TestCase):
|
||||
await client.validate_id_token(token, 'nonce-value')
|
||||
self.assertIn('RS256', str(ctx.exception))
|
||||
|
||||
@async_test
|
||||
async def test_validate_id_token_unsigned_allowed(self) -> None:
|
||||
token = self.provider.issue_unsigned_id_token('nonce-value', 'client')
|
||||
config = OIDCConfig(
|
||||
issuer=self.provider.issuer,
|
||||
client_id='client',
|
||||
redirect_uri='http://localhost:8000/auth/callback',
|
||||
http_client=self.http_client,
|
||||
allow_unsigned_id_tokens=True,
|
||||
)
|
||||
client = OIDCClient(config)
|
||||
claims = await client.validate_id_token(token, 'nonce-value')
|
||||
self.assertEqual('user123', claims['sub'])
|
||||
|
||||
@async_test
|
||||
async def test_validate_id_token_unsigned_rejected_by_default(self) -> None:
|
||||
token = self.provider.issue_unsigned_id_token('nonce-value', 'client')
|
||||
with self.assertRaises(ValueError) as ctx:
|
||||
await self.client.validate_id_token(token, 'nonce-value')
|
||||
self.assertIn('Unsigned', str(ctx.exception))
|
||||
|
||||
@async_test
|
||||
async def test_validate_id_token_unsigned_wrong_audience(self) -> None:
|
||||
token = self.provider.issue_unsigned_id_token('nonce-value', 'other-client')
|
||||
config = OIDCConfig(
|
||||
issuer=self.provider.issuer,
|
||||
client_id='client',
|
||||
redirect_uri='http://localhost:8000/auth/callback',
|
||||
http_client=self.http_client,
|
||||
allow_unsigned_id_tokens=True,
|
||||
)
|
||||
client = OIDCClient(config)
|
||||
with self.assertRaises(jwt.InvalidAudienceError):
|
||||
await client.validate_id_token(token, 'nonce-value')
|
||||
|
||||
@async_test
|
||||
async def test_validate_id_token_unsigned_wrong_issuer(self) -> None:
|
||||
token = self.provider.issue_unsigned_id_token('nonce-value', 'client', issuer='https://evil-issuer.local')
|
||||
config = OIDCConfig(
|
||||
issuer=self.provider.issuer,
|
||||
client_id='client',
|
||||
redirect_uri='http://localhost:8000/auth/callback',
|
||||
http_client=self.http_client,
|
||||
allow_unsigned_id_tokens=True,
|
||||
)
|
||||
client = OIDCClient(config)
|
||||
with self.assertRaises(jwt.InvalidIssuerError):
|
||||
await client.validate_id_token(token, 'nonce-value')
|
||||
|
||||
@async_test
|
||||
async def test_fetch_userinfo(self) -> None:
|
||||
userinfo = await self.client.fetch_userinfo('access-token')
|
||||
@@ -498,6 +684,24 @@ class OIDCMixinTest(unittest.TestCase):
|
||||
new_token = await oidc.refresh_access_token(ctx.session)
|
||||
await ctx.send_str(200, new_token or 'no-token')
|
||||
|
||||
@app.GET('/id-token')
|
||||
@oidc.require_auth
|
||||
async def id_token(ctx: HttpContext) -> None:
|
||||
stored = ctx.session.get(oidc._key('id_token'))
|
||||
await ctx.send_str(200, stored if isinstance(stored, str) else 'none')
|
||||
|
||||
async def _login(self, client: httpx.AsyncClient, provider: MockOIDCProvider) -> None:
|
||||
r = await client.get('/auth/login', follow_redirects=False)
|
||||
self.assertEqual(302, r.status_code)
|
||||
query = parse_qs(urlparse(r.headers['Location']).query)
|
||||
provider.nonce = query['nonce'][0]
|
||||
r = await client.get(
|
||||
'/auth/callback',
|
||||
params={'code': 'mock-code', 'state': query['state'][0]},
|
||||
follow_redirects=False,
|
||||
)
|
||||
self.assertEqual(302, r.status_code)
|
||||
|
||||
@async_test
|
||||
async def test_login_redirect(self) -> None:
|
||||
app, oidc, provider, store = self._build_app()
|
||||
@@ -543,6 +747,42 @@ class OIDCMixinTest(unittest.TestCase):
|
||||
r = await client.get('/auth/callback', params={'code': 'mock-code', 'state': 'wrong'}, follow_redirects=False)
|
||||
self.assertEqual(400, r.status_code)
|
||||
|
||||
@async_test
|
||||
async def test_callback_invalid_issuer_returns_400(self) -> None:
|
||||
app, oidc, provider, store = self._build_app()
|
||||
self._setup_routes(app, oidc)
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://127.0.0.1:80') as client:
|
||||
r = await client.get('/auth/login', follow_redirects=False)
|
||||
query = parse_qs(urlparse(r.headers['Location']).query)
|
||||
provider.nonce = query['nonce'][0]
|
||||
provider.token_issuer = 'https://evil-issuer.local'
|
||||
|
||||
r = await client.get(
|
||||
'/auth/callback',
|
||||
params={'code': 'mock-code', 'state': query['state'][0]},
|
||||
follow_redirects=False,
|
||||
)
|
||||
self.assertEqual(400, r.status_code)
|
||||
|
||||
@async_test
|
||||
async def test_callback_expired_id_token_returns_400(self) -> None:
|
||||
app, oidc, provider, store = self._build_app()
|
||||
self._setup_routes(app, oidc)
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://127.0.0.1:80') as client:
|
||||
r = await client.get('/auth/login', follow_redirects=False)
|
||||
query = parse_qs(urlparse(r.headers['Location']).query)
|
||||
provider.nonce = query['nonce'][0]
|
||||
provider.token_expired = True
|
||||
|
||||
r = await client.get(
|
||||
'/auth/callback',
|
||||
params={'code': 'mock-code', 'state': query['state'][0]},
|
||||
follow_redirects=False,
|
||||
)
|
||||
self.assertEqual(400, r.status_code)
|
||||
|
||||
@async_test
|
||||
async def test_logout(self) -> None:
|
||||
app, oidc, provider, store = self._build_app()
|
||||
@@ -580,17 +820,68 @@ class OIDCMixinTest(unittest.TestCase):
|
||||
self._setup_routes(app, oidc)
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://127.0.0.1:80') as client:
|
||||
r = await client.get('/auth/login', follow_redirects=False)
|
||||
parsed = urlparse(r.headers['Location'])
|
||||
query = parse_qs(parsed.query)
|
||||
state = query['state'][0]
|
||||
provider.nonce = query['nonce'][0]
|
||||
await client.get('/auth/callback', params={'code': 'mock-code', 'state': state}, follow_redirects=False)
|
||||
await self._login(client, provider)
|
||||
|
||||
r = await client.get('/refresh')
|
||||
self.assertEqual(200, r.status_code)
|
||||
self.assertEqual('new-access-token', r.text)
|
||||
|
||||
@async_test
|
||||
async def test_refresh_access_token_rejects_invalid_issuer(self) -> None:
|
||||
app, oidc, provider, store = self._build_app()
|
||||
self._setup_routes(app, oidc)
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://127.0.0.1:80') as client:
|
||||
await self._login(client, provider)
|
||||
original_id_token = (await client.get('/id-token')).text
|
||||
|
||||
provider.token_issuer = 'https://evil-issuer.local'
|
||||
r = await client.get('/refresh')
|
||||
self.assertEqual(200, r.status_code)
|
||||
self.assertEqual('no-token', r.text)
|
||||
|
||||
# The refreshed ID token was not validated, so nothing was stored.
|
||||
self.assertEqual(original_id_token, (await client.get('/id-token')).text)
|
||||
|
||||
@async_test
|
||||
async def test_refresh_access_token_rejects_wrong_nonce(self) -> None:
|
||||
app, oidc, provider, store = self._build_app()
|
||||
self._setup_routes(app, oidc)
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://127.0.0.1:80') as client:
|
||||
await self._login(client, provider)
|
||||
|
||||
provider.nonce = 'tampered-nonce'
|
||||
r = await client.get('/refresh')
|
||||
self.assertEqual(200, r.status_code)
|
||||
self.assertEqual('no-token', r.text)
|
||||
|
||||
@async_test
|
||||
async def test_refresh_access_token_rejects_wrong_subject(self) -> None:
|
||||
app, oidc, provider, store = self._build_app()
|
||||
self._setup_routes(app, oidc)
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://127.0.0.1:80') as client:
|
||||
await self._login(client, provider)
|
||||
|
||||
provider.token_sub = 'other-user'
|
||||
r = await client.get('/refresh')
|
||||
self.assertEqual(200, r.status_code)
|
||||
self.assertEqual('no-token', r.text)
|
||||
|
||||
@async_test
|
||||
async def test_refresh_access_token_expired_id_token(self) -> None:
|
||||
app, oidc, provider, store = self._build_app()
|
||||
self._setup_routes(app, oidc)
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://127.0.0.1:80') as client:
|
||||
await self._login(client, provider)
|
||||
|
||||
provider.token_expired = True
|
||||
r = await client.get('/refresh')
|
||||
self.assertEqual(200, r.status_code)
|
||||
self.assertEqual('no-token', r.text)
|
||||
|
||||
@async_test
|
||||
async def test_dependency_applied_automatically(self) -> None:
|
||||
# Only pass oidc to KayaApp; SessionMixin should be applied via dependencies.
|
||||
|
||||
@@ -69,6 +69,48 @@ object, so any valid OpenAPI 3.1 construct can be used:
|
||||
`parameters` entries whose `name` and `in` match an auto-generated path
|
||||
parameter override it; all others are appended.
|
||||
|
||||
## Reusable schemas (`components`)
|
||||
|
||||
Schemas can be defined once and referenced from operation fragments: pass a
|
||||
`components` mapping to the mixin and use `schema_ref` in `@operation`.
|
||||
|
||||
```python
|
||||
from kaya.openapi import OpenAPIMixin, operation, schema_ref
|
||||
|
||||
USER = {
|
||||
'type': 'object',
|
||||
'required': ['id'],
|
||||
'properties': {'id': {'type': 'integer'}, 'name': {'type': 'string'}},
|
||||
}
|
||||
USER_PAGE = {
|
||||
'type': 'object',
|
||||
'properties': {'results': {'type': 'array', 'items': schema_ref('User')}},
|
||||
}
|
||||
|
||||
app = KayaApp(mixins=[OpenAPIMixin(
|
||||
title='My API',
|
||||
version='1.0.0',
|
||||
components={'schemas': {'User': USER, 'UserPage': USER_PAGE}},
|
||||
)])
|
||||
|
||||
|
||||
@app.GET('/users')
|
||||
@operation(summary='List users',
|
||||
responses={200: {
|
||||
'description': 'A page of users',
|
||||
'content': {'application/json': {'schema': schema_ref('UserPage')}},
|
||||
}})
|
||||
async def list_users(ctx: HttpContext) -> None:
|
||||
...
|
||||
```
|
||||
|
||||
`components` is merged verbatim (as a copy) into the generated document under
|
||||
`components`, so Swagger UI lists the named schemas. Every
|
||||
`#/components/<section>/<name>` reference — in operations or between
|
||||
components — is validated when the document is generated: a missing section or
|
||||
entry raises `ValueError`. Reflected references (`./other.json#/...`, absolute
|
||||
URLs) are left alone.
|
||||
|
||||
## Configuration
|
||||
|
||||
```python
|
||||
@@ -81,6 +123,7 @@ OpenAPIMixin(
|
||||
servers=[{'url': 'https://api.example.com'}],
|
||||
openapi_version='3.1.0',
|
||||
include_self=False, # include spec/docs endpoints in the document
|
||||
components=None, # reusable OpenAPI components (e.g. schemas)
|
||||
)
|
||||
```
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
from ._metadata import operation
|
||||
from ._mixin import OpenAPIMixin
|
||||
from ._spec import generate_spec
|
||||
from ._spec import generate_spec, schema_ref
|
||||
|
||||
|
||||
__all__ = [
|
||||
'OpenAPIMixin',
|
||||
'generate_spec',
|
||||
'operation',
|
||||
'schema_ref',
|
||||
]
|
||||
@@ -25,7 +25,9 @@ def operation(summary: Optional[str] = None,
|
||||
:class:`~kaya.openapi.OpenAPIMixin` when generating the specification.
|
||||
|
||||
All schema fragments are plain dicts inserted verbatim into the generated
|
||||
OpenAPI document, so any valid OpenAPI 3.1 construct can be used.
|
||||
OpenAPI document, so any valid OpenAPI 3.1 construct can be used. ``$ref``
|
||||
fragments may point at the reusable schemas registered through the
|
||||
``components`` argument of :class:`~kaya.openapi.OpenAPIMixin`.
|
||||
|
||||
Example::
|
||||
|
||||
|
||||
@@ -55,6 +55,11 @@ class OpenAPIMixin(KayaMixin):
|
||||
bodies and response schemas to individual handlers; the handler docstring
|
||||
is used as the operation description when no explicit one is given.
|
||||
|
||||
Reusable schemas are supplied through ``components`` and referenced from
|
||||
operation fragments with :func:`~kaya.openapi.schema_ref`; every
|
||||
``#/components/...`` reference is validated when the document is
|
||||
generated.
|
||||
|
||||
Example::
|
||||
|
||||
openapi = OpenAPIMixin(title='My API', version='1.0.0')
|
||||
@@ -74,7 +79,8 @@ class OpenAPIMixin(KayaMixin):
|
||||
docs_path: str = '/docs',
|
||||
servers: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||
openapi_version: str = '3.1.0',
|
||||
include_self: bool = False) -> None:
|
||||
include_self: bool = False,
|
||||
components: Optional[Mapping[str, Any]] = None) -> None:
|
||||
self._title = title
|
||||
self._version = version
|
||||
self._description = description
|
||||
@@ -83,6 +89,7 @@ class OpenAPIMixin(KayaMixin):
|
||||
self._servers = servers
|
||||
self._openapi_version = openapi_version
|
||||
self._include_self = include_self
|
||||
self._components = components
|
||||
|
||||
def apply(self, app: KayaApp) -> None:
|
||||
@app.GET(self._spec_path)
|
||||
@@ -107,4 +114,5 @@ class OpenAPIMixin(KayaMixin):
|
||||
description=self._description,
|
||||
servers=self._servers,
|
||||
exclude_paths=exclude_paths,
|
||||
openapi_version=self._openapi_version)
|
||||
openapi_version=self._openapi_version,
|
||||
components=self._components)
|
||||
@@ -1,7 +1,7 @@
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
from inspect import getdoc
|
||||
from typing import AbstractSet, Any, Mapping, Optional, Sequence
|
||||
from typing import AbstractSet, Any, Dict, Iterator, Mapping, Optional, Sequence
|
||||
|
||||
from kaya.core import HttpMethod, KayaApp
|
||||
from kaya.core._path_handler import PathHandler
|
||||
@@ -22,6 +22,17 @@ STANDARD_METHODS: Sequence[HttpMethod] = (
|
||||
)
|
||||
|
||||
|
||||
def schema_ref(name: str) -> Dict[str, str]:
|
||||
"""Return a reference to the component schema ``name``.
|
||||
|
||||
The reference resolves to ``#/components/schemas/<name>`` in the
|
||||
generated document; the schema itself is supplied through the
|
||||
``components`` argument of :func:`generate_spec` (or
|
||||
:class:`~kaya.openapi.OpenAPIMixin`).
|
||||
"""
|
||||
return {'$ref': f'#/components/schemas/{name}'}
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Route:
|
||||
raw_path: str
|
||||
@@ -122,13 +133,67 @@ def _build_operation(params: Sequence[Mapping[str, Any]],
|
||||
return operation
|
||||
|
||||
|
||||
def _unescape_pointer_token(token: str) -> str:
|
||||
"""Decode one JSON Pointer reference token (``~1`` → ``/``, ``~0`` → ``~``)."""
|
||||
return token.replace('~1', '/').replace('~0', '~')
|
||||
|
||||
|
||||
def _iter_refs(node: Any) -> Iterator[str]:
|
||||
"""Yield every ``$ref`` string found anywhere under ``node``."""
|
||||
if isinstance(node, Mapping):
|
||||
ref = node.get('$ref')
|
||||
if isinstance(ref, str):
|
||||
yield ref
|
||||
for value in node.values():
|
||||
yield from _iter_refs(value)
|
||||
elif isinstance(node, (list, tuple)):
|
||||
for value in node:
|
||||
yield from _iter_refs(value)
|
||||
|
||||
|
||||
def _validate_component_refs(spec: Mapping[str, Any]) -> None:
|
||||
"""Fail fast on references to missing ``components`` entries.
|
||||
|
||||
Every ``#/components/<section>/<name>`` reference found in the operations
|
||||
or in the components themselves must resolve against the document;
|
||||
references in any other form (relative files, absolute URLs, other
|
||||
pointers) are ignored. Raises :class:`ValueError` naming the offending
|
||||
reference and the operation it appears in.
|
||||
"""
|
||||
components = spec.get('components')
|
||||
known: Mapping[str, Any] = components if isinstance(components, Mapping) else {}
|
||||
|
||||
def check(node: Any, location: str) -> None:
|
||||
for ref in _iter_refs(node):
|
||||
if not ref.startswith('#/components/'):
|
||||
continue
|
||||
parts = [_unescape_pointer_token(part) for part in ref[len('#/components/'):].split('/')]
|
||||
if len(parts) < 2:
|
||||
raise ValueError(f'invalid component reference {ref!r} in {location}')
|
||||
section, name = parts[0], parts[1]
|
||||
bucket = known.get(section)
|
||||
if not isinstance(bucket, Mapping) or name not in bucket:
|
||||
raise ValueError(f'unknown component reference {ref!r} in {location}')
|
||||
|
||||
paths = spec.get('paths')
|
||||
if isinstance(paths, Mapping):
|
||||
for path, item in paths.items():
|
||||
if not isinstance(item, Mapping):
|
||||
continue
|
||||
for method, operation in item.items():
|
||||
check(operation, f'{method.upper()} {path}')
|
||||
if isinstance(components, Mapping):
|
||||
check(components, 'components')
|
||||
|
||||
|
||||
def generate_spec(app: KayaApp,
|
||||
title: str,
|
||||
version: str,
|
||||
description: str = '',
|
||||
servers: Optional[Sequence[Mapping[str, Any]]] = None,
|
||||
exclude_paths: AbstractSet[str] = frozenset(),
|
||||
openapi_version: str = '3.1.0') -> Mapping[str, Any]:
|
||||
openapi_version: str = '3.1.0',
|
||||
components: Optional[Mapping[str, Any]] = None) -> Mapping[str, Any]:
|
||||
"""Generate an OpenAPI specification document from a :class:`KayaApp`.
|
||||
|
||||
The application's routing tree is walked and every route is converted to
|
||||
@@ -147,6 +212,9 @@ def generate_spec(app: KayaApp,
|
||||
:param servers: list of OpenAPI server objects
|
||||
:param exclude_paths: Kaya paths (e.g. ``/openapi.json``) to omit
|
||||
:param openapi_version: OpenAPI version to declare
|
||||
:param components: OpenAPI ``components`` object merged verbatim into the
|
||||
document; references to ``#/components/<section>/<name>`` must resolve
|
||||
against it (e.g. :func:`schema_ref` for reusable schemas)
|
||||
:return: the OpenAPI document as a JSON-serializable mapping
|
||||
"""
|
||||
routes: list[_Route] = []
|
||||
@@ -174,4 +242,7 @@ def generate_spec(app: KayaApp,
|
||||
}
|
||||
if servers:
|
||||
spec['servers'] = [dict(server) for server in servers]
|
||||
if components:
|
||||
spec['components'] = deepcopy(dict(components))
|
||||
_validate_component_refs(spec)
|
||||
return spec
|
||||
@@ -6,7 +6,7 @@ import httpx
|
||||
from pwo import async_test
|
||||
|
||||
from kaya.core import HttpContext, HttpMethod, KayaApp, WebSocket
|
||||
from kaya.openapi import OpenAPIMixin, operation
|
||||
from kaya.openapi import OpenAPIMixin, generate_spec, operation, schema_ref
|
||||
|
||||
|
||||
class OpenAPITest(unittest.TestCase):
|
||||
@@ -163,5 +163,127 @@ class OpenAPITest(unittest.TestCase):
|
||||
self.assertIn('/spec.json', response.text)
|
||||
|
||||
|
||||
class ComponentsTest(unittest.TestCase):
|
||||
"""Reusable schemas through ``components`` and ``schema_ref``."""
|
||||
|
||||
async def _spec_of(self, app: KayaApp) -> Mapping[str, Any]:
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(transport=transport, base_url='http://127.0.0.1:80') as client:
|
||||
response = await client.get('/openapi.json')
|
||||
self.assertEqual(200, response.status_code)
|
||||
return json.loads(response.text)
|
||||
|
||||
def test_schema_ref_helper(self) -> None:
|
||||
self.assertEqual({'$ref': '#/components/schemas/User'}, schema_ref('User'))
|
||||
|
||||
@async_test
|
||||
async def test_components_merged_and_refs_preserved(self) -> None:
|
||||
user = {'type': 'object', 'properties': {'id': {'type': 'integer'}}}
|
||||
page = {'type': 'object',
|
||||
'properties': {'results': {'type': 'array', 'items': schema_ref('User')}}}
|
||||
app = KayaApp(mixins=[OpenAPIMixin(
|
||||
title='Components API',
|
||||
version='1.0.0',
|
||||
components={'schemas': {'User': user, 'UserPage': page}},
|
||||
)])
|
||||
|
||||
@app.GET('/users')
|
||||
@operation(responses={200: {
|
||||
'description': 'A page of users',
|
||||
'content': {'application/json': {'schema': schema_ref('UserPage')}},
|
||||
}})
|
||||
async def list_users(ctx: HttpContext) -> None:
|
||||
await ctx.send_str(200, '[]')
|
||||
|
||||
spec = await self._spec_of(app)
|
||||
self.assertEqual({'schemas': {'User': user, 'UserPage': page}}, spec['components'])
|
||||
schema = spec['paths']['/users']['get']['responses']['200']['content']['application/json']['schema']
|
||||
self.assertEqual(schema_ref('UserPage'), schema)
|
||||
|
||||
@async_test
|
||||
async def test_request_body_ref_preserved(self) -> None:
|
||||
app = KayaApp(mixins=[OpenAPIMixin(
|
||||
title='Components API',
|
||||
version='1.0.0',
|
||||
components={'schemas': {'User': {'type': 'object'}}},
|
||||
)])
|
||||
|
||||
@app.POST('/users')
|
||||
@operation(request_body={'required': True,
|
||||
'content': {'application/json': {'schema': schema_ref('User')}}},
|
||||
responses={201: {'description': 'Created'}})
|
||||
async def create_user(ctx: HttpContext) -> None:
|
||||
await ctx.send_str(201, '{}')
|
||||
|
||||
spec = await self._spec_of(app)
|
||||
schema = spec['paths']['/users']['post']['requestBody']['content']['application/json']['schema']
|
||||
self.assertEqual(schema_ref('User'), schema)
|
||||
|
||||
@async_test
|
||||
async def test_default_spec_has_no_components(self) -> None:
|
||||
app = KayaApp(mixins=[OpenAPIMixin(title='Plain API', version='1.0.0')])
|
||||
|
||||
@app.GET('/plain')
|
||||
async def plain(ctx: HttpContext) -> None:
|
||||
await ctx.send_str(200, 'ok')
|
||||
|
||||
spec = await self._spec_of(app)
|
||||
self.assertNotIn('components', spec)
|
||||
|
||||
def test_unknown_schema_ref_raises(self) -> None:
|
||||
app = KayaApp()
|
||||
|
||||
@app.GET('/broken')
|
||||
@operation(responses={200: {
|
||||
'description': 'x',
|
||||
'content': {'application/json': {'schema': schema_ref('Missing')}},
|
||||
}})
|
||||
async def broken(ctx: HttpContext) -> None:
|
||||
await ctx.send_str(200, 'x')
|
||||
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
generate_spec(app, title='Broken', version='1.0.0',
|
||||
components={'schemas': {'User': {}}})
|
||||
message = str(caught.exception)
|
||||
self.assertIn('#/components/schemas/Missing', message)
|
||||
self.assertIn('GET /broken', message)
|
||||
|
||||
def test_component_to_component_ref_validates(self) -> None:
|
||||
app = KayaApp()
|
||||
spec = generate_spec(app, title='Nested', version='1.0.0', components={'schemas': {
|
||||
'User': {'type': 'object'},
|
||||
'Page': {'type': 'object',
|
||||
'properties': {'results': {'type': 'array', 'items': schema_ref('User')}}},
|
||||
}})
|
||||
self.assertIn('components', spec)
|
||||
|
||||
def test_external_refs_are_ignored(self) -> None:
|
||||
app = KayaApp()
|
||||
|
||||
@app.GET('/external')
|
||||
@operation(responses={200: {
|
||||
'description': 'x',
|
||||
'content': {'application/json': {'schema': {'$ref': './other.json#/Thing'}}},
|
||||
}})
|
||||
async def external(ctx: HttpContext) -> None:
|
||||
await ctx.send_str(200, 'x')
|
||||
|
||||
spec = generate_spec(app, title='External', version='1.0.0')
|
||||
self.assertNotIn('components', spec)
|
||||
|
||||
def test_generic_component_section_validated(self) -> None:
|
||||
app = KayaApp()
|
||||
|
||||
@app.GET('/p')
|
||||
@operation(parameters=[{'name': 'q', 'in': 'query',
|
||||
'schema': {'$ref': '#/components/parameters/Missing'}}])
|
||||
async def p(ctx: HttpContext) -> None:
|
||||
await ctx.send_str(200, 'x')
|
||||
|
||||
with self.assertRaises(ValueError) as caught:
|
||||
generate_spec(app, title='P', version='1.0.0', components={'parameters': {}})
|
||||
self.assertIn('#/components/parameters/Missing', str(caught.exception))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user