deapi-mcp 0.7.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,973 @@
1
+ """OAuth 2.0 endpoints for Authorization Code flow.
2
+
3
+ This module provides minimal OAuth 2.0 server functionality to support
4
+ MCP clients (like Claude Desktop) that require OAuth authentication.
5
+
6
+ Flow (Authorization Code):
7
+ 1. Client discovers OAuth metadata at /.well-known/oauth-authorization-server
8
+ 2. User clicks "Connect" in Claude Desktop
9
+ 3. Browser opens /authorize with client_id, redirect_uri, state, code_challenge
10
+ 4. Server immediately redirects back with authorization code (no UI needed)
11
+ 5. Client POSTs to /token with authorization code grant
12
+ - code: authorization code from step 4
13
+ - client_id: "deapi-mcp"
14
+ - client_secret: user's Deapi API token
15
+ - code_verifier: for PKCE verification
16
+ 6. Server validates and returns JWT containing the Deapi token
17
+ 7. Client uses JWT for MCP requests
18
+ 8. Auth middleware extracts Deapi token from JWT and forwards to Deapi API
19
+ """
20
+
21
+ import base64
22
+ import binascii
23
+ import hashlib
24
+ import logging
25
+ import os
26
+ import re
27
+ import secrets
28
+ import time
29
+ from datetime import datetime, timedelta, timezone
30
+ from typing import Any, Optional
31
+ from urllib.parse import unquote, urlencode, urlparse
32
+
33
+ import jwt
34
+ from cryptography.fernet import Fernet
35
+ from starlette.datastructures import FormData
36
+ from starlette.requests import Request
37
+ from starlette.responses import JSONResponse, RedirectResponse, Response
38
+
39
+ from . import auth_code_store
40
+ from .auth_code_store import AUTHORIZATION_CODE_MAX_ENTRIES, AuthCodeStoreUnavailable
41
+ from .config import settings
42
+ from .consent import error_page as consent_error_page
43
+ from .consent import show_consent, submit_consent
44
+ from .key_verifier import is_api_key_rejected
45
+ from .oauth_clients import OAuthClient, looks_like_public_client_id, resolve_client
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+ # OAuth Configuration
50
+ DEFAULT_CLIENT_ID = "deapi-mcp"
51
+ JWT_ALGORITHM = "HS256"
52
+ JWT_EXPIRATION_SECONDS = 3600 # 1 hour
53
+ REFRESH_TOKEN_EXPIRATION_SECONDS = 2592000 # 30 days
54
+ AUTHORIZATION_CODE_EXPIRATION_SECONDS = 600 # 10 minutes
55
+ # Retry-After on a 503 from /token while the authorization code store is unreachable
56
+ CODE_STORE_RETRY_AFTER_SECONDS = 5
57
+
58
+ # Allowed redirect URI schemes (prevent javascript:, data:, etc.)
59
+ ALLOWED_REDIRECT_SCHEMES = {"http", "https"}
60
+ # Native-app callbacks on a private-use scheme (RFC 8252 §7.1), accepted only as these
61
+ # exact strings. Cursor's documented callback for a pre-registered OAuth client.
62
+ ALLOWED_NATIVE_REDIRECT_URIS = frozenset({"cursor://anysphere.cursor-mcp/oauth/callback"})
63
+ # An S256 code_challenge is the unpadded base64url of a SHA-256 digest: 43 characters.
64
+ S256_CHALLENGE = re.compile(r"[A-Za-z0-9_-]{43}")
65
+ # RFC 6749 §5.1: token responses must not be cached.
66
+ NO_STORE_HEADERS = {"Cache-Control": "no-store", "Pragma": "no-cache"}
67
+ DOCS_URL = "https://docs.deapi.ai/execution-modes-and-integrations/mcp-server"
68
+
69
+ # JWT signing key - derive from environment or generate
70
+ # In production, set DEAPI_JWT_SECRET_KEY environment variable
71
+ _jwt_secret_key: Optional[str] = None
72
+
73
+ # Fernet encryption key derived from JWT secret (for encrypting tokens in JWT claims)
74
+ _fernet: Optional[Fernet] = None
75
+
76
+
77
+ def get_jwt_secret_key() -> str:
78
+ """Get or generate JWT signing key.
79
+
80
+ Returns:
81
+ JWT signing key as string
82
+ """
83
+ global _jwt_secret_key
84
+
85
+ if _jwt_secret_key is None:
86
+ # Try to get from environment
87
+ _jwt_secret_key = os.getenv("DEAPI_JWT_SECRET_KEY")
88
+
89
+ if _jwt_secret_key is None:
90
+ # Generate a random key for this session
91
+ # WARNING: Tokens will be invalid after server restart
92
+ _jwt_secret_key = secrets.token_urlsafe(32)
93
+ logger.warning(
94
+ "Using ephemeral JWT signing key. "
95
+ "Set DEAPI_JWT_SECRET_KEY environment variable for production."
96
+ )
97
+
98
+ return _jwt_secret_key
99
+
100
+
101
+ def _get_fernet() -> Fernet:
102
+ """Get Fernet cipher for encrypting/decrypting tokens in JWT claims.
103
+
104
+ Derives a Fernet-compatible key from the JWT secret key using SHA-256.
105
+
106
+ Returns:
107
+ Fernet cipher instance
108
+ """
109
+ global _fernet
110
+
111
+ if _fernet is None:
112
+ secret = get_jwt_secret_key()
113
+ # Derive a 32-byte key from the JWT secret, then base64-encode for Fernet
114
+ derived_key = hashlib.sha256(secret.encode()).digest()
115
+ fernet_key = base64.urlsafe_b64encode(derived_key)
116
+ _fernet = Fernet(fernet_key)
117
+
118
+ return _fernet
119
+
120
+
121
+ def encrypt_token(token: str) -> str:
122
+ """Encrypt a token for safe embedding in JWT claims.
123
+
124
+ Args:
125
+ token: Plaintext token to encrypt
126
+
127
+ Returns:
128
+ Encrypted token as base64 string
129
+ """
130
+ return _get_fernet().encrypt(token.encode()).decode()
131
+
132
+
133
+ def decrypt_token(encrypted_token: str) -> str:
134
+ """Decrypt a token from JWT claims.
135
+
136
+ Args:
137
+ encrypted_token: Encrypted token string
138
+
139
+ Returns:
140
+ Decrypted plaintext token
141
+
142
+ Raises:
143
+ Exception: If decryption fails (invalid key or corrupted data)
144
+ """
145
+ return _get_fernet().decrypt(encrypted_token.encode()).decode()
146
+
147
+
148
+ def issuer_url(request: Request) -> str:
149
+ """This server's public base URL: PUBLIC_BASE_URL, else the request's own."""
150
+ return (os.getenv("PUBLIC_BASE_URL") or f"{request.url.scheme}://{request.url.netloc}").rstrip(
151
+ "/"
152
+ )
153
+
154
+
155
+ def resource_is_ours(resource: Optional[str], request: Request) -> bool:
156
+ """RFC 8707: a ``resource`` the client names must be this MCP server.
157
+
158
+ Host and path decide; scheme and port do not, so a proxy that hides the original
159
+ scheme (``http`` behind TLS termination) cannot turn a correct request away.
160
+ """
161
+ if not resource:
162
+ return True
163
+ try:
164
+ named = urlparse(resource)
165
+ ours = urlparse(issuer_url(request))
166
+ except ValueError:
167
+ return False
168
+ if (named.hostname or "").lower() != (ours.hostname or "").lower():
169
+ return False
170
+ return named.path.rstrip("/") in ("", "/mcp")
171
+
172
+
173
+ def authorization_redirect(
174
+ request: Request,
175
+ redirect_uri: str,
176
+ params: dict[str, str],
177
+ state: Optional[str],
178
+ status_code: int = 307,
179
+ ) -> RedirectResponse:
180
+ """Redirect back to the client with ``params``, its ``state`` and our ``iss`` (RFC 9207)."""
181
+ query = dict(params)
182
+ if state:
183
+ query["state"] = state
184
+ query["iss"] = issuer_url(request)
185
+ separator = "&" if "?" in redirect_uri else "?"
186
+ return RedirectResponse(f"{redirect_uri}{separator}{urlencode(query)}", status_code=status_code)
187
+
188
+
189
+ def _validate_redirect_uri(redirect_uri: str) -> bool:
190
+ """Validate that a redirect URI uses an allowed scheme.
191
+
192
+ Prevents open redirect attacks via javascript:, data:, or other dangerous schemes.
193
+ A private-use scheme is accepted only for the exact native-app callbacks listed in
194
+ ALLOWED_NATIVE_REDIRECT_URIS.
195
+
196
+ Args:
197
+ redirect_uri: The redirect URI to validate
198
+
199
+ Returns:
200
+ True if the URI uses an allowed scheme
201
+ """
202
+ if redirect_uri in ALLOWED_NATIVE_REDIRECT_URIS:
203
+ return True
204
+ try:
205
+ parsed = urlparse(redirect_uri)
206
+ return parsed.scheme.lower() in ALLOWED_REDIRECT_SCHEMES and bool(parsed.netloc)
207
+ except Exception:
208
+ return False
209
+
210
+
211
+ def create_jwt(deapi_token: str, client_id: str = DEFAULT_CLIENT_ID) -> str:
212
+ """Create JWT token containing Deapi API token.
213
+
214
+ Args:
215
+ deapi_token: User's Deapi API token (from client_secret)
216
+ client_id: OAuth client ID
217
+
218
+ Returns:
219
+ Signed JWT token string
220
+ """
221
+ now = datetime.now(timezone.utc)
222
+ expiration = now + timedelta(seconds=JWT_EXPIRATION_SECONDS)
223
+
224
+ payload = {
225
+ "iss": str(settings.deapi_api_base_url), # Issuer
226
+ "sub": client_id, # Subject (client ID)
227
+ "aud": "deapi-mcp-api", # Audience
228
+ "exp": int(expiration.timestamp()), # Expiration time
229
+ "iat": int(now.timestamp()), # Issued at
230
+ "deapi_token_enc": encrypt_token(deapi_token), # Encrypted Deapi token
231
+ }
232
+
233
+ token = jwt.encode(
234
+ payload,
235
+ get_jwt_secret_key(),
236
+ algorithm=JWT_ALGORITHM,
237
+ )
238
+
239
+ return token
240
+
241
+
242
+ def decode_jwt(token: str) -> Optional[dict[str, Any]]:
243
+ """Decode and validate JWT token.
244
+
245
+ Args:
246
+ token: JWT token string
247
+
248
+ Returns:
249
+ Decoded payload dict if valid, None otherwise
250
+ """
251
+ try:
252
+ payload = jwt.decode(
253
+ token,
254
+ get_jwt_secret_key(),
255
+ algorithms=[JWT_ALGORITHM],
256
+ audience="deapi-mcp-api",
257
+ )
258
+ return payload
259
+ except jwt.InvalidTokenError:
260
+ return None
261
+
262
+
263
+ def is_jwt(token: str) -> bool:
264
+ """Check if a token is a JWT (vs plain Bearer token).
265
+
266
+ Args:
267
+ token: Token string to check
268
+
269
+ Returns:
270
+ True if token appears to be JWT format
271
+ """
272
+ # JWT has 3 parts separated by dots: header.payload.signature
273
+ return token.count(".") == 2
274
+
275
+
276
+ def create_refresh_token(deapi_token: str, client_id: str = DEFAULT_CLIENT_ID) -> str:
277
+ """Create a refresh token containing Deapi API token.
278
+
279
+ The refresh token is a JWT with a longer expiration time and different audience
280
+ to distinguish it from access tokens.
281
+
282
+ Args:
283
+ deapi_token: User's Deapi API token
284
+ client_id: OAuth client ID
285
+
286
+ Returns:
287
+ Signed refresh token string
288
+ """
289
+ now = datetime.now(timezone.utc)
290
+ expiration = now + timedelta(seconds=REFRESH_TOKEN_EXPIRATION_SECONDS)
291
+
292
+ payload = {
293
+ "iss": str(settings.deapi_api_base_url), # Issuer
294
+ "sub": client_id, # Subject (client ID)
295
+ "aud": "deapi-mcp-refresh", # Different audience for refresh tokens
296
+ "exp": int(expiration.timestamp()), # Expiration time
297
+ "iat": int(now.timestamp()), # Issued at
298
+ "deapi_token_enc": encrypt_token(deapi_token), # Encrypted Deapi token
299
+ "token_type": "refresh", # Explicit token type marker
300
+ }
301
+
302
+ token = jwt.encode(
303
+ payload,
304
+ get_jwt_secret_key(),
305
+ algorithm=JWT_ALGORITHM,
306
+ )
307
+
308
+ return token
309
+
310
+
311
+ def decode_refresh_token(token: str) -> Optional[dict[str, Any]]:
312
+ """Decode and validate a refresh token.
313
+
314
+ Args:
315
+ token: Refresh token string
316
+
317
+ Returns:
318
+ Decoded payload dict if valid, None otherwise
319
+ """
320
+ try:
321
+ payload = jwt.decode(
322
+ token,
323
+ get_jwt_secret_key(),
324
+ algorithms=[JWT_ALGORITHM],
325
+ audience="deapi-mcp-refresh",
326
+ )
327
+ # Verify it's actually a refresh token
328
+ if payload.get("token_type") != "refresh":
329
+ return None
330
+ return payload
331
+ except jwt.InvalidTokenError:
332
+ return None
333
+
334
+
335
+ async def oauth_authorization_server_metadata(request: Request) -> JSONResponse:
336
+ """OAuth 2.0 Authorization Server Metadata endpoint.
337
+
338
+ Returns OAuth server metadata as per RFC 8414.
339
+ Mounted at: /.well-known/oauth-authorization-server
340
+
341
+ Args:
342
+ request: Starlette request object
343
+
344
+ Returns:
345
+ JSON response with OAuth metadata
346
+ """
347
+ # Get base URL - prefer explicit PUBLIC_BASE_URL env var, fallback to request URL
348
+ # This is important for production deployments behind reverse proxies/ingress
349
+ base_url = os.getenv("PUBLIC_BASE_URL")
350
+ if not base_url:
351
+ # Derive from request (works for direct connections)
352
+ base_url = f"{request.url.scheme}://{request.url.netloc}"
353
+
354
+ metadata: dict[str, Any] = {
355
+ "issuer": base_url,
356
+ "authorization_endpoint": f"{base_url}/authorize",
357
+ "token_endpoint": f"{base_url}/token",
358
+ "grant_types_supported": ["authorization_code", "client_credentials", "refresh_token"],
359
+ "response_types_supported": ["code"],
360
+ "token_endpoint_auth_methods_supported": ["client_secret_post", "client_secret_basic"],
361
+ "code_challenge_methods_supported": ["S256"],
362
+ "scopes_supported": [], # No scopes for our use case
363
+ "authorization_response_iss_parameter_supported": True,
364
+ "service_documentation": DOCS_URL,
365
+ }
366
+ if settings.oauth_public_clients:
367
+ # Clients that register themselves (DCR) or are identified by a metadata URL (CIMD)
368
+ # are public: no secret, PKCE, and the user signs in with a key on our screen.
369
+ metadata["registration_endpoint"] = f"{base_url}/register"
370
+ metadata["client_id_metadata_document_supported"] = True
371
+ metadata["token_endpoint_auth_methods_supported"] = [
372
+ "none",
373
+ "client_secret_post",
374
+ "client_secret_basic",
375
+ ]
376
+
377
+ return JSONResponse(metadata)
378
+
379
+
380
+ async def oauth_protected_resource_metadata(request: Request) -> JSONResponse:
381
+ """OAuth 2.0 Protected Resource Metadata endpoint.
382
+
383
+ Returns protected resource metadata as per RFC 9728.
384
+ This tells MCP clients which authorization servers are trusted
385
+ to issue tokens for this resource.
386
+
387
+ Mounted at: /.well-known/oauth-protected-resource
388
+
389
+ Args:
390
+ request: Starlette request object
391
+
392
+ Returns:
393
+ JSON response with protected resource metadata
394
+ """
395
+ # Get base URL - prefer explicit PUBLIC_BASE_URL env var, fallback to request URL
396
+ base_url = os.getenv("PUBLIC_BASE_URL")
397
+ if not base_url:
398
+ # Derive from request (works for direct connections)
399
+ base_url = f"{request.url.scheme}://{request.url.netloc}"
400
+
401
+ # The actual MCP resource is at /mcp (HTTP transport)
402
+ resource_url = f"{base_url}/mcp"
403
+
404
+ metadata = {
405
+ "resource": resource_url, # Point to the actual MCP endpoint
406
+ "authorization_servers": [base_url], # We are our own authorization server
407
+ "scopes_supported": [], # No scopes for our use case
408
+ }
409
+
410
+ return JSONResponse(metadata)
411
+
412
+
413
+ def _form_str(form: FormData, key: str) -> Optional[str]:
414
+ """A text form field, or None when it is missing or was sent as a file part.
415
+
416
+ A file part arrives as an UploadFile; treating it as absent turns it into the usual
417
+ 400/401 instead of a crash further down.
418
+ """
419
+ value = form.get(key)
420
+ return value if isinstance(value, str) else None
421
+
422
+
423
+ def _basic_credentials(request: Request) -> Optional[tuple[str, str]]:
424
+ """The client_id and client_secret from an ``Authorization: Basic`` header.
425
+
426
+ RFC 6749 §2.3.1 (``client_secret_basic``): base64 of ``id:secret``, each part
427
+ form-urlencoded first. Returns None when there is no Basic header; raises
428
+ ValueError when there is one that cannot be decoded.
429
+ """
430
+ header = request.headers.get("authorization", "")
431
+ scheme, _, value = header.partition(" ")
432
+ if scheme.lower() != "basic":
433
+ return None
434
+ try:
435
+ decoded = base64.b64decode(value.strip(), validate=True).decode("utf-8")
436
+ except (binascii.Error, UnicodeDecodeError) as exc:
437
+ raise ValueError("malformed Basic credentials") from exc
438
+ client_id, sep, client_secret = decoded.partition(":")
439
+ if not sep:
440
+ raise ValueError("malformed Basic credentials")
441
+ # unquote, not unquote_plus: a client that skips the encoding step must not have a
442
+ # literal '+' in the key turned into a space.
443
+ return unquote(client_id), unquote(client_secret)
444
+
445
+
446
+ async def token_endpoint(request: Request) -> JSONResponse:
447
+ """OAuth 2.0 token endpoint: the grant handling below, plus the headers every answer needs.
448
+
449
+ Token responses are never cached (RFC 6749 §5.1), and a client that authenticated with
450
+ HTTP Basic and failed gets the Basic challenge back (RFC 6749 §5.2).
451
+ """
452
+ response = await _token_response(request)
453
+ response.headers.update(NO_STORE_HEADERS)
454
+ if response.status_code == 401 and request.headers.get("authorization", "").lower().startswith(
455
+ "basic "
456
+ ):
457
+ response.headers["WWW-Authenticate"] = f'Basic realm="{DEFAULT_CLIENT_ID}"'
458
+ return response
459
+
460
+
461
+ async def _token_response(request: Request) -> JSONResponse:
462
+ """OAuth 2.0 Token endpoint for Authorization Code, Client Credentials, and Refresh Token grants.
463
+
464
+ Mounted at: /token
465
+
466
+ Accepts three grant types:
467
+ 1. authorization_code:
468
+ - code: authorization code from /authorize
469
+ - client_id: "deapi-mcp"
470
+ - client_secret: user's Deapi API token
471
+ - code_verifier: PKCE verifier
472
+ - redirect_uri: must match authorization request
473
+
474
+ 2. client_credentials:
475
+ - client_id: "deapi-mcp"
476
+ - client_secret: user's Deapi API token
477
+
478
+ 3. refresh_token:
479
+ - refresh_token: refresh token from previous token response
480
+ - client_id: "deapi-mcp"
481
+
482
+ The client authenticates with client_id and client_secret in the form
483
+ (``client_secret_post``) or in an ``Authorization: Basic`` header
484
+ (``client_secret_basic``); the header wins when both are sent.
485
+
486
+ Returns JWT containing the Deapi token, plus a refresh token for non-refresh grants.
487
+
488
+ Args:
489
+ request: Starlette request object
490
+
491
+ Returns:
492
+ JSON response with access_token, refresh_token, or error
493
+ """
494
+ # Parse form data
495
+ form_data = await request.form()
496
+ grant_type = _form_str(form_data, "grant_type")
497
+ client_id = _form_str(form_data, "client_id")
498
+ client_secret = _form_str(form_data, "client_secret")
499
+ try:
500
+ basic = _basic_credentials(request)
501
+ except ValueError:
502
+ return JSONResponse(
503
+ {"error": "invalid_client", "error_description": "Malformed Basic credentials"},
504
+ status_code=401,
505
+ )
506
+ if basic is not None:
507
+ if client_id and client_id != basic[0]:
508
+ return JSONResponse(
509
+ {
510
+ "error": "invalid_request",
511
+ "error_description": "client_id in the form and in Basic credentials differ",
512
+ },
513
+ status_code=400,
514
+ )
515
+ client_id, client_secret = basic
516
+
517
+ # Validate grant_type
518
+ if grant_type not in ["authorization_code", "client_credentials", "refresh_token"]:
519
+ return JSONResponse(
520
+ {
521
+ "error": "unsupported_grant_type",
522
+ "error_description": "Supported grant types: authorization_code, client_credentials, refresh_token",
523
+ },
524
+ status_code=400,
525
+ )
526
+
527
+ # Validate client_id: the pre-registered client, or a public one (CIMD / DCR)
528
+ public_client: Optional[OAuthClient] = None
529
+ if client_id and client_id != DEFAULT_CLIENT_ID and settings.oauth_public_clients:
530
+ public_client = await resolve_client(client_id)
531
+ if not client_id or (client_id != DEFAULT_CLIENT_ID and public_client is None):
532
+ return JSONResponse(
533
+ {
534
+ "error": "invalid_client",
535
+ "error_description": "Unknown client_id: register the client, use a client ID "
536
+ f"metadata document, or use '{DEFAULT_CLIENT_ID}' with your API key as secret",
537
+ },
538
+ status_code=401,
539
+ )
540
+ if public_client is not None and grant_type == "client_credentials":
541
+ return JSONResponse(
542
+ {
543
+ "error": "unauthorized_client",
544
+ "error_description": "A public client cannot use client_credentials",
545
+ },
546
+ status_code=400,
547
+ )
548
+ if not resource_is_ours(_form_str(form_data, "resource"), request):
549
+ if public_client is None:
550
+ # 0.6.x ignored resource; keep the pre-registered client working, but say so
551
+ logger.warning("Token request for client deapi-mcp names another resource")
552
+ else:
553
+ return JSONResponse(
554
+ {"error": "invalid_target", "error_description": "resource is not this MCP server"},
555
+ status_code=400,
556
+ )
557
+
558
+ # Handle refresh_token grant
559
+ if grant_type == "refresh_token":
560
+ refresh_token = _form_str(form_data, "refresh_token")
561
+
562
+ if not refresh_token:
563
+ return JSONResponse(
564
+ {"error": "invalid_request", "error_description": "refresh_token is required"},
565
+ status_code=400,
566
+ )
567
+
568
+ # Decode and validate refresh token
569
+ payload = decode_refresh_token(refresh_token)
570
+ if not payload:
571
+ logger.error("Invalid or expired refresh token")
572
+ return JSONResponse(
573
+ {"error": "invalid_grant", "error_description": "Invalid or expired refresh token"},
574
+ status_code=400,
575
+ )
576
+
577
+ # A refresh token belongs to the client it was issued to
578
+ if payload.get("sub") != client_id:
579
+ logger.warning("Refresh token presented by another client")
580
+ return JSONResponse(
581
+ {"error": "invalid_grant", "error_description": "Invalid refresh token"},
582
+ status_code=400,
583
+ )
584
+
585
+ # Extract and decrypt the deapi token from the refresh token
586
+ encrypted_token = payload.get("deapi_token_enc")
587
+ if not encrypted_token:
588
+ logger.error("Refresh token missing deapi_token_enc claim")
589
+ return JSONResponse(
590
+ {"error": "invalid_grant", "error_description": "Invalid refresh token"},
591
+ status_code=400,
592
+ )
593
+
594
+ try:
595
+ deapi_token = decrypt_token(encrypted_token)
596
+ except Exception:
597
+ logger.error("Failed to decrypt deapi token from refresh token")
598
+ return JSONResponse(
599
+ {"error": "invalid_grant", "error_description": "Invalid refresh token"},
600
+ status_code=400,
601
+ )
602
+
603
+ # The grant carries the key it was issued for. A key deAPI now refuses (revoked
604
+ # or rotated) ends the grant, so the client signs in again with a working key
605
+ # instead of minting access tokens no tool call can use.
606
+ if await is_api_key_rejected(deapi_token):
607
+ logger.warning("Refresh with an API key deAPI rejects")
608
+ return JSONResponse(
609
+ {
610
+ "error": "invalid_grant",
611
+ "error_description": "The API key of this grant was rejected by deAPI; "
612
+ "authorize again",
613
+ },
614
+ status_code=400,
615
+ )
616
+
617
+ return _token_success(deapi_token, client_id)
618
+
619
+ # Handle authorization_code grant
620
+ if grant_type == "authorization_code":
621
+ code = _form_str(form_data, "code")
622
+ code_verifier = _form_str(form_data, "code_verifier")
623
+ redirect_uri = _form_str(form_data, "redirect_uri")
624
+
625
+ # Validate required parameters
626
+ if not code:
627
+ return JSONResponse(
628
+ {"error": "invalid_request", "error_description": "code is required"},
629
+ status_code=400,
630
+ )
631
+
632
+ # Fetch and burn the code in one step: a code is single-use even if a later check fails
633
+ try:
634
+ auth_data = await auth_code_store.get_auth_code_store().consume(code)
635
+ except AuthCodeStoreUnavailable as exc:
636
+ cause = exc.__cause__ or exc
637
+ logger.error(
638
+ "Authorization code store unavailable during token exchange: %s: %s",
639
+ type(cause).__name__,
640
+ cause,
641
+ )
642
+ return JSONResponse(
643
+ {
644
+ "error": "temporarily_unavailable",
645
+ "error_description": "Authorization temporarily unavailable, try again",
646
+ },
647
+ status_code=503,
648
+ headers={"Retry-After": str(CODE_STORE_RETRY_AFTER_SECONDS)},
649
+ )
650
+ if not auth_data:
651
+ logger.error("Invalid authorization code")
652
+ return JSONResponse(
653
+ {"error": "invalid_grant", "error_description": "Invalid authorization code"},
654
+ status_code=400,
655
+ )
656
+
657
+ # Check expiration
658
+ if time.time() > auth_data["expires_at"]:
659
+ logger.error("Authorization code expired")
660
+ return JSONResponse(
661
+ {"error": "invalid_grant", "error_description": "Authorization code expired"},
662
+ status_code=400,
663
+ )
664
+
665
+ # A code belongs to the client it was issued to
666
+ if auth_data.get("client_id") != client_id:
667
+ logger.warning("Authorization code presented by another client")
668
+ return JSONResponse(
669
+ {"error": "invalid_grant", "error_description": "Invalid authorization code"},
670
+ status_code=400,
671
+ )
672
+
673
+ # Verify redirect_uri matches. RFC 6749 §4.1.3: required here only when the
674
+ # authorization request carried one; when it was left out, it may be left out again.
675
+ supplied = auth_data.get("redirect_uri_supplied", True)
676
+ if (supplied or redirect_uri is not None) and redirect_uri != auth_data["redirect_uri"]:
677
+ logger.error("Redirect URI mismatch: %r vs %r", redirect_uri, auth_data["redirect_uri"])
678
+ return JSONResponse(
679
+ {"error": "invalid_grant", "error_description": "redirect_uri mismatch"},
680
+ status_code=400,
681
+ )
682
+
683
+ # Verify PKCE
684
+ if not code_verifier:
685
+ logger.error("Missing code_verifier")
686
+ return JSONResponse(
687
+ {"error": "invalid_request", "error_description": "code_verifier is required"},
688
+ status_code=400,
689
+ )
690
+
691
+ if not verify_pkce_challenge(code_verifier, auth_data["code_challenge"]):
692
+ logger.error("PKCE verification failed")
693
+ return JSONResponse(
694
+ {"error": "invalid_grant", "error_description": "Invalid code_verifier"},
695
+ status_code=400,
696
+ )
697
+
698
+ if public_client is not None:
699
+ # The key came from the sign-in screen, where it was already checked
700
+ try:
701
+ deapi_token = decrypt_token(str(auth_data["key_enc"]))
702
+ except Exception:
703
+ logger.error("Authorization code without a usable key")
704
+ return JSONResponse(
705
+ {"error": "invalid_grant", "error_description": "Invalid authorization code"},
706
+ status_code=400,
707
+ )
708
+ return _token_success(deapi_token, client_id)
709
+
710
+ # Client secret IS the Deapi token
711
+ if not client_secret or len(client_secret) < 10:
712
+ return JSONResponse(
713
+ {
714
+ "error": "invalid_client",
715
+ "error_description": "Invalid client_secret (Deapi token)",
716
+ },
717
+ status_code=401,
718
+ )
719
+
720
+ deapi_token = client_secret
721
+
722
+ # Handle client_credentials grant
723
+ else: # client_credentials
724
+ # Validate client_secret (Deapi token)
725
+ if not client_secret:
726
+ return JSONResponse(
727
+ {
728
+ "error": "invalid_client",
729
+ "error_description": "client_secret is required (your Deapi API token)",
730
+ },
731
+ status_code=401,
732
+ )
733
+
734
+ if len(client_secret) < 10:
735
+ return JSONResponse(
736
+ {
737
+ "error": "invalid_client",
738
+ "error_description": "client_secret appears invalid (Deapi API token expected)",
739
+ },
740
+ status_code=401,
741
+ )
742
+
743
+ deapi_token = client_secret
744
+
745
+ # The secret IS the deAPI key: ask the API once whether it knows it, so a wrong
746
+ # key fails here, where the client can show it, not on every later tool call.
747
+ if await is_api_key_rejected(deapi_token):
748
+ logger.warning("Token request with a client_secret deAPI rejects")
749
+ return JSONResponse(
750
+ {
751
+ "error": "invalid_client",
752
+ "error_description": "client_secret was rejected by deAPI (invalid API key)",
753
+ },
754
+ status_code=401,
755
+ )
756
+
757
+ return _token_success(deapi_token, client_id)
758
+
759
+
760
+ def _token_success(deapi_token: str, client_id: str) -> JSONResponse:
761
+ """An access token and a refresh token for ``client_id``, both carrying the key."""
762
+ try:
763
+ access_token = create_jwt(deapi_token, client_id)
764
+ refresh_token = create_refresh_token(deapi_token, client_id)
765
+ except Exception as e:
766
+ logger.error(f"Failed to create tokens: {str(e)}")
767
+ return JSONResponse(
768
+ {
769
+ "error": "server_error",
770
+ "error_description": f"Failed to create tokens: {str(e)}",
771
+ },
772
+ status_code=500,
773
+ )
774
+ return JSONResponse(
775
+ {
776
+ "access_token": access_token,
777
+ "token_type": "Bearer",
778
+ "expires_in": JWT_EXPIRATION_SECONDS,
779
+ "refresh_token": refresh_token,
780
+ }
781
+ )
782
+
783
+
784
+ def verify_pkce_challenge(code_verifier: str, code_challenge: str) -> bool:
785
+ """Verify PKCE code_challenge matches code_verifier.
786
+
787
+ Args:
788
+ code_verifier: The code verifier from token request
789
+ code_challenge: The code challenge from authorization request
790
+
791
+ Returns:
792
+ True if challenge matches verifier
793
+ """
794
+ # Compute SHA256 hash of verifier
795
+ verifier_hash = hashlib.sha256(code_verifier.encode()).digest()
796
+ # Base64-URL encode (without padding)
797
+ computed_challenge = base64.urlsafe_b64encode(verifier_hash).decode().rstrip("=")
798
+ return computed_challenge == code_challenge
799
+
800
+
801
+ async def authorize_endpoint(request: Request) -> Response:
802
+ """OAuth 2.0 authorization endpoint (``GET`` and, for the sign-in form, ``POST``).
803
+
804
+ - ``client_id=deapi-mcp`` (pre-registered; the API key is its secret at /token): the
805
+ code is issued at once and the browser is sent straight back, as before.
806
+ - Any other client_id, when public clients are enabled, must be a client ID metadata
807
+ document URL or a dynamically registered client: the user signs in with an API key
808
+ on the screen in ``consent.py``, which posts back here.
809
+
810
+ Query parameters: client_id, redirect_uri, state, code_challenge,
811
+ code_challenge_method (S256), response_type (code), resource (optional, RFC 8707).
812
+ """
813
+ if request.method == "POST":
814
+ if not settings.oauth_public_clients:
815
+ return JSONResponse(
816
+ {"error": "invalid_request", "error_description": "Unsupported method"},
817
+ status_code=405,
818
+ )
819
+ return await submit_consent(request)
820
+
821
+ client_id = request.query_params.get("client_id")
822
+ redirect_uri = request.query_params.get("redirect_uri")
823
+ state = request.query_params.get("state")
824
+ code_challenge = request.query_params.get("code_challenge")
825
+ code_challenge_method = request.query_params.get("code_challenge_method")
826
+ response_type = request.query_params.get("response_type")
827
+ resource = request.query_params.get("resource")
828
+
829
+ public_client: Optional[OAuthClient] = None
830
+ redirect_uri_supplied = True
831
+ if settings.oauth_public_clients and looks_like_public_client_id(client_id):
832
+ public_client = await resolve_client(client_id)
833
+ if public_client is None:
834
+ return consent_error_page(
835
+ "This application is not registered with deAPI MCP, or its registration could "
836
+ "not be read."
837
+ )
838
+ if not redirect_uri and len(public_client.redirect_uris) == 1:
839
+ redirect_uri = public_client.redirect_uris[0]
840
+ redirect_uri_supplied = False
841
+ if not redirect_uri or not public_client.allows_redirect(redirect_uri):
842
+ # Never redirect to a URI the client did not register (open redirect)
843
+ return consent_error_page(
844
+ "The application asked to return to an address it has not registered."
845
+ )
846
+ elif not client_id or client_id != DEFAULT_CLIENT_ID:
847
+ logger.error("Invalid client_id: %r", (client_id or "")[:80])
848
+ # RFC 6749 4.1.2.1: never redirect to a redirect_uri that is not tied to a valid
849
+ # client (open redirect), so answer directly.
850
+ return JSONResponse(
851
+ {"error": "unauthorized_client", "error_description": "Invalid client_id"},
852
+ status_code=400,
853
+ )
854
+ else:
855
+ if not redirect_uri:
856
+ logger.error("Missing redirect_uri")
857
+ return JSONResponse(
858
+ {"error": "invalid_request", "error_description": "redirect_uri is required"},
859
+ status_code=400,
860
+ )
861
+ if not _validate_redirect_uri(redirect_uri):
862
+ logger.error("Invalid redirect_uri scheme: %r", redirect_uri[:200])
863
+ return JSONResponse(
864
+ {
865
+ "error": "invalid_request",
866
+ "error_description": "redirect_uri must use http or https scheme",
867
+ },
868
+ status_code=400,
869
+ )
870
+
871
+ # From here on the redirect URI is trusted for this client, so errors go back to it
872
+ if response_type != "code":
873
+ logger.error("Invalid response_type: %s", response_type)
874
+ return authorization_redirect(
875
+ request,
876
+ redirect_uri,
877
+ {
878
+ "error": "unsupported_response_type",
879
+ "error_description": "Only 'code' response_type is supported",
880
+ },
881
+ state,
882
+ )
883
+
884
+ # PKCE: S256 only (no "plain"), and a well-formed S256 value
885
+ if (
886
+ not code_challenge
887
+ or code_challenge_method != "S256"
888
+ or not S256_CHALLENGE.fullmatch(code_challenge)
889
+ ):
890
+ logger.error("Invalid PKCE: method=%s", code_challenge_method)
891
+ return authorization_redirect(
892
+ request,
893
+ redirect_uri,
894
+ {"error": "invalid_request", "error_description": "PKCE with S256 is required"},
895
+ state,
896
+ )
897
+
898
+ if not resource_is_ours(resource, request) and public_client is None:
899
+ logger.warning("Authorization request for client deapi-mcp names another resource")
900
+ elif not resource_is_ours(resource, request):
901
+ return authorization_redirect(
902
+ request,
903
+ redirect_uri,
904
+ {"error": "invalid_target", "error_description": "resource is not this MCP server"},
905
+ state,
906
+ )
907
+
908
+ if public_client is not None:
909
+ return await show_consent(
910
+ request,
911
+ public_client,
912
+ redirect_uri,
913
+ {
914
+ "client_id": public_client.client_id,
915
+ "redirect_uri": redirect_uri,
916
+ "redirect_uri_supplied": redirect_uri_supplied,
917
+ "state": state,
918
+ "code_challenge": code_challenge,
919
+ "resource": resource,
920
+ },
921
+ )
922
+
923
+ # Pre-registered client: issue the code at once
924
+ auth_code = secrets.token_urlsafe(32)
925
+ expires_at = time.time() + AUTHORIZATION_CODE_EXPIRATION_SECONDS
926
+
927
+ try:
928
+ stored = await auth_code_store.get_auth_code_store().put(
929
+ auth_code,
930
+ {
931
+ "client_id": client_id,
932
+ "redirect_uri": redirect_uri,
933
+ "code_challenge": code_challenge,
934
+ "expires_at": expires_at,
935
+ "state": state,
936
+ "resource": resource,
937
+ },
938
+ AUTHORIZATION_CODE_EXPIRATION_SECONDS,
939
+ )
940
+ except AuthCodeStoreUnavailable as exc:
941
+ cause = exc.__cause__ or exc
942
+ logger.error(
943
+ "Authorization code store unavailable, rejecting authorize request: %s: %s",
944
+ type(cause).__name__,
945
+ cause,
946
+ )
947
+ return authorization_redirect(
948
+ request,
949
+ redirect_uri,
950
+ {
951
+ "error": "temporarily_unavailable",
952
+ "error_description": "Authorization temporarily unavailable, try again",
953
+ },
954
+ state,
955
+ )
956
+
957
+ if not stored:
958
+ # Capacity protects against DoS via excessive authorize requests
959
+ logger.warning(
960
+ "Authorization code store at capacity (%d), rejecting new request",
961
+ AUTHORIZATION_CODE_MAX_ENTRIES,
962
+ )
963
+ return authorization_redirect(
964
+ request,
965
+ redirect_uri,
966
+ {
967
+ "error": "server_error",
968
+ "error_description": "Server is busy, please try again later",
969
+ },
970
+ state,
971
+ )
972
+
973
+ return authorization_redirect(request, redirect_uri, {"code": auth_code}, state)