1"""Client ID Metadata Documents (CIMD).
2
3A `client_id` may be an HTTPS URL pointing at a small JSON document the client
4hosts on its own domain (draft-ietf-oauth-client-id-metadata-document, adopted
5by MCP as SEP-991). Instead of registering, the client presents the URL; we
6fetch the document, check that it claims that exact URL as its `client_id`,
7and use its `redirect_uris` as the registration. Claude, Claude Code, ChatGPT,
8and VS Code all do this when the server advertises support.
9
10The risk of this feature is that it makes the server fetch an attacker-chosen
11URL, so the fetch is deliberately narrow:
12
13- HTTPS only, ASCII hostnames only, no IP literals, no redirects followed.
14- The connection is made by `_GuardedNetworkBackend`, which resolves the host
15 itself and connects only to addresses that are publicly routable. The check
16 and the connection use the same addresses, so DNS rebinding can't swap one
17 in between.
18- One deadline covers the whole fetch: DNS, connect, TLS, headers, and body.
19- The body is read undecoded (`Accept-Encoding: identity`, and any other
20 `Content-Encoding` is refused) and capped at 5 KB.
21- Only a few fetches run at once per process.
22
23Fetched documents are stored on the `OAuthApplication` row keyed by the URL —
24one row per client product, not per install — with a TTL from the document's
25`Cache-Control`. When a refetch fails transiently (timeout, connection error,
265xx), the last good copy keeps being served for a grace period, because
27Claude's metadata endpoints have had outages.
28"""
29
30import ipaddress
31import json
32import logging
33import socket
34import ssl
35import threading
36import time
37from collections.abc import Iterable
38from dataclasses import dataclass
39from datetime import timedelta
40from typing import Any
41from urllib.parse import unquote, urlsplit
42
43import httpcore
44from plain.runtime import settings
45from plain.utils import timezone
46
47from .models import (
48 OAuthApplication,
49 _clean_client_name,
50 _validate_redirect_uris,
51)
52
53logger = logging.getLogger(__name__)
54
55# Every reason a fetch didn't get a response shares this message, so a
56# client_id can't be used to learn which hosts exist or answer.
57_FETCH_FAILED = "Could not fetch the client's metadata document"
58
59# Loading the CA bundle is slow, and one context is safe to share.
60_SSL_CONTEXT = ssl.create_default_context()
61
62# Draft -03 recommends a 5 KB read cap. Claude's document is ~350 bytes.
63MAX_DOCUMENT_BYTES = 5 * 1024
64
65# Total time allowed for a fetch: DNS, connect, TLS, response headers, and body.
66FETCH_DEADLINE_SECONDS = 5.0
67
68# Fetches allowed at once in one process. When they're all busy, a new one
69# fails immediately rather than waiting.
70MAX_CONCURRENT_FETCHES = 8
71
72# The document's Cache-Control is honored within these bounds. No directive
73# (or no-store / no-cache) gets the default.
74MIN_CACHE_SECONDS = 5 * 60
75MAX_CACHE_SECONDS = 24 * 60 * 60
76DEFAULT_CACHE_SECONDS = 60 * 60
77
78# After the stored document expires, a transient refetch failure keeps serving
79# it for this long, measured from the last successful fetch.
80STALE_GRACE_PERIOD = timedelta(days=7)
81
82# While serving a stored document through a failure, wait this long before
83# trying the client's URL again.
84REFETCH_BACKOFF = timedelta(minutes=5)
85
86MAX_CLIENT_ID_LENGTH = 2048
87
88# Hosts under these TLDs are never public (RFC 2606, RFC 6761, RFC 8375), so a
89# URL naming one is rejected before any DNS lookup. The address check is the
90# real guard; this only avoids pointless lookups.
91_NON_PUBLIC_TLDS = {
92 "localhost",
93 "local",
94 "test",
95 "invalid",
96 "example",
97 "internal",
98 "lan",
99 "home",
100 "corp",
101 "arpa",
102}
103
104_USER_AGENT = "plain.oauthserver (+https://plainframework.com)"
105
106# Global unicast IPv6. Everything outside it (IPv4-compatible ::/96, SIIT
107# ::ffff:0:0:0/96, deprecated site-local fec0::/10, local-use NAT64
108# 64:ff9b:1::/48, ...) is refused, because `is_global` alone lets some of
109# those through.
110_IPV6_GLOBAL_UNICAST = ipaddress.IPv6Network("2000::/3")
111
112# Well-known NAT64 (RFC 6052). DNS64 resolvers on IPv6-only hosts answer with
113# these, so they're allowed when the IPv4 address inside is public.
114_NAT64_WELL_KNOWN = ipaddress.IPv6Network("64:ff9b::/96")
115
116_fetch_slots = threading.BoundedSemaphore(MAX_CONCURRENT_FETCHES)
117
118
119class ClientMetadataError(Exception):
120 """A client_id URL or its metadata document can't be used.
121
122 The message is safe to show to the end user on the consent screen — it
123 names what was wrong, never the fetched content or why a host couldn't be
124 reached. `transient` marks failures worth retrying (timeouts, connection
125 errors, 5xx) as opposed to a document that is missing or invalid.
126 """
127
128 def __init__(self, message: str, *, transient: bool = False):
129 super().__init__(message)
130 self.transient = transient
131
132
133@dataclass(frozen=True)
134class ClientMetadata:
135 """What we keep from a validated document."""
136
137 name: str
138 redirect_uris: list[str]
139
140
141def is_client_id_url(client_id: str) -> bool:
142 """Whether a client_id is a metadata-document URL rather than a registered id."""
143 return client_id.startswith("https://")
144
145
146def is_client_id_url_allowed(client_id: str) -> bool:
147 """Whether the settings let this URL client_id be used at all.
148
149 Checked at the authorization endpoint before any fetch, and at the token
150 endpoint so that turning the feature off (or narrowing the allowed hosts)
151 also stops refreshes for clients that were already stored.
152 """
153 if not settings.OAUTH_SERVER_ALLOW_CLIENT_ID_METADATA_DOCUMENTS:
154 return False
155 allowed_hosts = settings.OAUTH_SERVER_CLIENT_ID_METADATA_ALLOWED_HOSTS
156 if allowed_hosts is None:
157 return True
158 try:
159 host = urlsplit(client_id).hostname
160 except ValueError:
161 return False
162 return host in allowed_hosts
163
164
165def validate_client_id_url(client_id: str) -> str:
166 """Enforce the draft's Client Identifier URL rules before we go anywhere near it.
167
168 Returns the URL unchanged — it's compared and stored by simple string
169 comparison, never normalized.
170 """
171 if len(client_id) > MAX_CLIENT_ID_LENGTH:
172 raise ClientMetadataError("client_id URL is too long")
173 if not client_id.startswith("https://"):
174 raise ClientMetadataError("client_id URL must use https")
175 if not client_id.isascii():
176 raise ClientMetadataError("client_id URL must be ASCII")
177 if any(ord(c) <= 0x20 or ord(c) == 0x7F or c == "\\" for c in client_id):
178 raise ClientMetadataError(
179 "client_id URL must not contain whitespace, control characters, or backslashes"
180 )
181 if "#" in client_id:
182 raise ClientMetadataError("client_id URL must not contain a fragment")
183 if "?" in client_id:
184 raise ClientMetadataError("client_id URL must not contain a query string")
185 if ";" in client_id:
186 # The HTTP client would drop ";params" from the path and fetch a
187 # different URL than the one the document has to claim.
188 raise ClientMetadataError("client_id URL must not contain a semicolon")
189
190 try:
191 split = urlsplit(client_id)
192 host = split.hostname
193 port = split.port
194 except ValueError:
195 raise ClientMetadataError("client_id URL is malformed") from None
196 if "@" in split.netloc:
197 raise ClientMetadataError("client_id URL must not contain credentials")
198 if port is not None and not 1 <= port <= 65535:
199 raise ClientMetadataError("client_id URL has an invalid port")
200
201 if not host:
202 raise ClientMetadataError("client_id URL must have a host")
203 try:
204 ipaddress.ip_address(host)
205 except ValueError:
206 pass
207 else:
208 raise ClientMetadataError(
209 "client_id URL must use a hostname, not an IP address"
210 )
211 labels = host.rstrip(".").split(".")
212 if len(labels) < 2 or labels[-1] in _NON_PUBLIC_TLDS:
213 raise ClientMetadataError("client_id URL must use a public hostname")
214 if len(host) > 253 or any(not 1 <= len(label) <= 63 for label in labels):
215 raise ClientMetadataError("client_id URL has an invalid hostname")
216
217 # Check the raw path: a parser that normalizes "." / ".." would hide them.
218 if not split.path or split.path == "/":
219 raise ClientMetadataError("client_id URL must have a path")
220 for segment in split.path.split("/"):
221 if unquote(segment) in (".", ".."):
222 raise ClientMetadataError("client_id URL must not contain dot segments")
223
224 return client_id
225
226
227def is_public_address(address: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
228 """Whether an address is publicly routable — the only kind we'll connect to."""
229 if isinstance(address, ipaddress.IPv6Address):
230 # See through the encodings that carry an IPv4 address inside IPv6.
231 if address in _NAT64_WELL_KNOWN:
232 return is_public_address(ipaddress.IPv4Address(int(address) & 0xFFFFFFFF))
233 if address.ipv4_mapped is not None:
234 return is_public_address(address.ipv4_mapped)
235 if address.sixtofour is not None:
236 return is_public_address(address.sixtofour)
237 if address.teredo is not None:
238 return False
239 if address not in _IPV6_GLOBAL_UNICAST:
240 return False
241 return address.is_global and not address.is_multicast
242
243
244def _getaddrinfo_within(host: str, port: int, timeout: float) -> list[Any]:
245 """`socket.getaddrinfo`, but giving up after `timeout` seconds.
246
247 getaddrinfo has no timeout of its own, so it runs on a daemon thread and
248 we stop waiting at the deadline. A lookup that never answers leaves only
249 that thread behind, blocked until the system resolver gives up.
250 """
251 outcome: dict[str, Any] = {}
252
253 def lookup() -> None:
254 try:
255 outcome["infos"] = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
256 except (OSError, UnicodeError) as exc:
257 outcome["error"] = exc
258
259 thread = threading.Thread(target=lookup, name="oauthserver-cimd-dns", daemon=True)
260 thread.start()
261 thread.join(timeout)
262 if thread.is_alive():
263 raise ClientMetadataError(_FETCH_FAILED, transient=True)
264 if "error" in outcome:
265 error = outcome["error"]
266 logger.info(
267 "Client metadata host did not resolve",
268 extra={"host": host, "reason": str(error)},
269 )
270 # EAI_AGAIN is the resolver saying "try again later".
271 transient = (
272 isinstance(error, socket.gaierror) and error.errno == socket.EAI_AGAIN
273 )
274 raise ClientMetadataError(_FETCH_FAILED, transient=transient)
275 return outcome["infos"]
276
277
278def resolve_public_addresses(*, host: str, port: int, timeout: float) -> list[str]:
279 """Resolve a hostname, refusing it unless every answer is public.
280
281 Every answer has to pass, not just the one we'll use: a host that mixes a
282 public address with an internal one is exactly what a rebinding attack
283 looks like. Returns the addresses in resolver order, without duplicates.
284 """
285 addresses: list[str] = []
286 for info in _getaddrinfo_within(host, port, timeout):
287 # Link-local IPv6 answers carry a "%scope" suffix ip_address won't parse.
288 raw = str(info[4][0]).split("%", 1)[0]
289 if not is_public_address(ipaddress.ip_address(raw)):
290 logger.warning(
291 "Client metadata host resolves to a non-public address",
292 extra={"host": host, "address": raw},
293 )
294 # Same message as an unresolvable host, so the consent screen
295 # can't be used to learn which internal names exist.
296 raise ClientMetadataError(_FETCH_FAILED)
297 if raw not in addresses:
298 addresses.append(raw)
299 if not addresses:
300 raise ClientMetadataError(_FETCH_FAILED)
301 return addresses
302
303
304class _DeadlineStream(httpcore.NetworkStream):
305 """A connection whose every read, write, and TLS handshake ends by one deadline.
306
307 httpcore's own timeouts apply to each socket operation separately, so a
308 server sending one byte at a time could hold a fetch open indefinitely.
309 """
310
311 def __init__(self, stream: httpcore.NetworkStream, deadline: float):
312 self._stream = stream
313 self._deadline = deadline
314
315 def _timeout(self, timeout: float | None) -> float:
316 remaining = self._deadline - time.monotonic()
317 if remaining <= 0:
318 raise httpcore.ReadTimeout("Client metadata fetch deadline passed")
319 return remaining if timeout is None else min(timeout, remaining)
320
321 def read(self, max_bytes: int, timeout: float | None = None) -> bytes:
322 return self._stream.read(max_bytes, self._timeout(timeout))
323
324 def write(self, buffer: bytes, timeout: float | None = None) -> None:
325 self._stream.write(buffer, self._timeout(timeout))
326
327 def close(self) -> None:
328 self._stream.close()
329
330 def start_tls(
331 self,
332 ssl_context: ssl.SSLContext,
333 server_hostname: str | None = None,
334 timeout: float | None = None,
335 ) -> httpcore.NetworkStream:
336 stream = self._stream.start_tls(
337 ssl_context, server_hostname, self._timeout(timeout)
338 )
339 return _DeadlineStream(stream, self._deadline)
340
341 def get_extra_info(self, info: str) -> Any:
342 return self._stream.get_extra_info(info)
343
344
345class _GuardedNetworkBackend(httpcore.NetworkBackend):
346 """Opens connections only to checked public addresses, all within one deadline.
347
348 httpcore hands this the hostname from the URL; we resolve it ourselves,
349 refuse it unless every address is public, and connect to those addresses
350 directly. TLS still verifies the certificate against the hostname, since
351 httpcore passes it as the server name.
352
353 `inner` is the backend that actually opens sockets — tests hand in an
354 `httpcore.MockBackend`.
355 """
356
357 def __init__(
358 self, *, deadline: float, inner: httpcore.NetworkBackend | None = None
359 ):
360 self._deadline = deadline
361 self._inner = inner or httpcore.SyncBackend()
362
363 def _remaining(self) -> float:
364 remaining = self._deadline - time.monotonic()
365 if remaining <= 0:
366 raise httpcore.ConnectTimeout("Client metadata fetch deadline passed")
367 return remaining
368
369 def connect_tcp(
370 self,
371 host: str,
372 port: int,
373 timeout: float | None = None,
374 local_address: str | None = None,
375 socket_options: Iterable[Any] | None = None,
376 ) -> httpcore.NetworkStream:
377 addresses = resolve_public_addresses(
378 host=host, port=port, timeout=self._remaining()
379 )
380 last_error: Exception | None = None
381 for address in addresses:
382 try:
383 stream = self._inner.connect_tcp(
384 address,
385 port,
386 timeout=self._remaining(),
387 local_address=local_address,
388 socket_options=socket_options,
389 )
390 except httpcore.ConnectError as exc:
391 last_error = exc
392 continue
393 return _DeadlineStream(stream, self._deadline)
394 assert last_error is not None # addresses is never empty
395 raise last_error
396
397 def connect_unix_socket(
398 self,
399 path: str,
400 timeout: float | None = None,
401 socket_options: Iterable[Any] | None = None,
402 ) -> httpcore.NetworkStream:
403 raise httpcore.ConnectError(
404 "Client metadata is never fetched over a socket file"
405 )
406
407
408def cache_ttl_seconds(cache_control: str) -> int:
409 """How long to trust a document, from its Cache-Control header, within our bounds."""
410 directives: dict[str, str] = {}
411 for part in cache_control.split(","):
412 name, _, value = part.strip().partition("=")
413 directives[name.strip().lower()] = value.strip().strip('"')
414
415 if "no-store" in directives or "no-cache" in directives:
416 return DEFAULT_CACHE_SECONDS
417
418 for name in ("s-maxage", "max-age"):
419 value = directives.get(name)
420 # The length check keeps int() away from absurdly long digit strings.
421 if (
422 value is not None
423 and value.isascii()
424 and value.isdigit()
425 and len(value) <= 10
426 ):
427 return max(MIN_CACHE_SECONDS, min(int(value), MAX_CACHE_SECONDS))
428
429 return DEFAULT_CACHE_SECONDS
430
431
432def fetch_metadata_document(
433 url: str, *, network_backend: httpcore.NetworkBackend | None = None
434) -> tuple[dict[str, Any], int]:
435 """GET a metadata document with the SSRF guard on. Returns (document, ttl seconds).
436
437 `url` must already have passed `validate_client_id_url`.
438 `network_backend` exists so tests can hand in an `httpcore.MockBackend`;
439 address checks and the deadline apply either way.
440 """
441 if not _fetch_slots.acquire(blocking=False):
442 logger.warning("Client metadata fetch refused, too many in progress")
443 raise ClientMetadataError(_FETCH_FAILED, transient=True)
444 try:
445 return _fetch(url, network_backend=network_backend)
446 finally:
447 _fetch_slots.release()
448
449
450def _fetch(
451 url: str, *, network_backend: httpcore.NetworkBackend | None
452) -> tuple[dict[str, Any], int]:
453 deadline = time.monotonic() + FETCH_DEADLINE_SECONDS
454 try:
455 with (
456 httpcore.ConnectionPool(
457 ssl_context=_SSL_CONTEXT,
458 network_backend=_GuardedNetworkBackend(
459 deadline=deadline, inner=network_backend
460 ),
461 max_connections=1,
462 retries=0,
463 ) as pool,
464 pool.stream(
465 "GET",
466 url,
467 headers=[
468 (b"Accept", b"application/json"),
469 # Read the body exactly as sent, so the size cap applies to
470 # what we parse. httpcore never decodes; we refuse anything
471 # encoded below.
472 (b"Accept-Encoding", b"identity"),
473 (b"User-Agent", _USER_AGENT.encode("ascii")),
474 ],
475 ) as response,
476 ):
477 headers = {
478 name.decode("latin-1").lower(): value.decode("latin-1")
479 for name, value in response.headers
480 }
481 status = response.status
482 if status != 200:
483 # Only 404 and 410 say the document is gone. Anything else
484 # (a 403 or a redirect from bot protection, a 5xx) may be a
485 # blip in front of a document that still exists.
486 raise ClientMetadataError(
487 f"The client's metadata document responded with status {status}",
488 transient=status not in (404, 410),
489 )
490 encoding = headers.get("content-encoding", "identity").strip().lower()
491 if encoding != "identity":
492 # A CDN that ignores Accept-Encoding is a configuration
493 # problem on the client's side, not a sign the document changed.
494 raise ClientMetadataError(
495 "The client's metadata document must not be compressed",
496 transient=True,
497 )
498 content_type = headers.get("content-type", "").split(";", 1)[0]
499 content_type = content_type.strip().lower()
500 if content_type != "application/json" and not content_type.endswith(
501 "+json"
502 ):
503 # An HTML challenge page from bot protection lands here.
504 raise ClientMetadataError(
505 "The client's metadata document is not JSON", transient=True
506 )
507 declared_length = headers.get("content-length", "")
508 if declared_length.isdigit() and int(declared_length) > MAX_DOCUMENT_BYTES:
509 raise ClientMetadataError("The client's metadata document is too large")
510
511 body = bytearray()
512 for chunk in response.iter_stream():
513 body.extend(chunk)
514 if len(body) > MAX_DOCUMENT_BYTES:
515 raise ClientMetadataError(
516 "The client's metadata document is too large"
517 )
518 except (
519 httpcore.TimeoutException,
520 httpcore.NetworkError,
521 httpcore.ProtocolError,
522 ) as exc:
523 logger.info(
524 "Client metadata fetch failed",
525 extra={"client_id": url, "reason": type(exc).__name__},
526 )
527 raise ClientMetadataError(_FETCH_FAILED, transient=True) from None
528
529 try:
530 document = json.loads(bytes(body))
531 except ValueError, RecursionError:
532 raise ClientMetadataError(
533 "The client's metadata document is not valid JSON"
534 ) from None
535 if not isinstance(document, dict):
536 raise ClientMetadataError(
537 "The client's metadata document must be a JSON object"
538 )
539
540 return document, cache_ttl_seconds(headers.get("cache-control", ""))
541
542
543def _string_list(value: object) -> list[str] | None:
544 """`value` if it is a list of strings, else None."""
545 if isinstance(value, list) and all(isinstance(item, str) for item in value):
546 return value
547 return None
548
549
550def validate_metadata_document(*, url: str, document: dict[str, Any]) -> ClientMetadata:
551 """Check a fetched document and pull out what we register.
552
553 The rules are draft -03's plus MCP's: the document must claim this exact
554 URL, name itself, list HTTPS-or-loopback redirect URIs, and be usable as a
555 public client. Fields this server doesn't act on (`jwks_uri`, `logo_uri`,
556 extra grant types like Claude's jwt-bearer) are ignored, not fetched.
557 """
558 if document.get("client_id") != url:
559 raise ClientMetadataError(
560 "The client's metadata document has a client_id that does not match its URL"
561 )
562
563 if any(key.startswith("client_secret") for key in document):
564 raise ClientMetadataError(
565 "The client's metadata document must not contain a client secret"
566 )
567
568 name = _clean_client_name(document.get("client_name"))
569 if not name:
570 raise ClientMetadataError(
571 "The client's metadata document must have a client_name"
572 )
573
574 try:
575 redirect_uris = _validate_redirect_uris(document.get("redirect_uris"))
576 except ValueError as exc:
577 raise ClientMetadataError(str(exc)) from None
578
579 # Draft -03: the plural list is preferred, the singular field is the RFC
580 # 7591 one, and neither means "none". This server only does public
581 # clients, so "none" has to be on offer — ChatGPT's document offers
582 # private_key_jwt and none, and gets none.
583 if "token_endpoint_auth_methods_supported" in document:
584 methods = _string_list(document["token_endpoint_auth_methods_supported"])
585 if methods is None:
586 raise ClientMetadataError(
587 "token_endpoint_auth_methods_supported must be a list"
588 )
589 single = document.get("token_endpoint_auth_method")
590 if single is not None and single not in methods:
591 raise ClientMetadataError(
592 "token_endpoint_auth_method must be one of token_endpoint_auth_methods_supported"
593 )
594 else:
595 methods = [document.get("token_endpoint_auth_method", "none")]
596 if any(str(method).startswith("client_secret") for method in methods):
597 # A document is public, so a shared secret in it would be no secret.
598 raise ClientMetadataError(
599 "The client's metadata document must not use a client secret method"
600 )
601 if "none" not in methods:
602 raise ClientMetadataError(
603 "This server only supports public clients (token_endpoint_auth_method 'none')"
604 )
605
606 if "jwks" in document and "jwks_uri" in document:
607 raise ClientMetadataError(
608 "The client's metadata document must not have both jwks and jwks_uri"
609 )
610 jwks = document.get("jwks")
611 keys = jwks.get("keys") if isinstance(jwks, dict) else None
612 if isinstance(keys, list) and any(
613 isinstance(key, dict) and ("d" in key or "k" in key) for key in keys
614 ):
615 # "d" is a private key, "k" a symmetric one: neither belongs in a public document.
616 raise ClientMetadataError(
617 "The client's metadata document must not contain private key material"
618 )
619
620 if "grant_types" in document:
621 grant_types = _string_list(document["grant_types"])
622 if grant_types is None or "authorization_code" not in grant_types:
623 raise ClientMetadataError("grant_types must include authorization_code")
624
625 if "response_types" in document:
626 response_types = _string_list(document["response_types"])
627 if response_types is None or "code" not in response_types:
628 raise ClientMetadataError("response_types must include code")
629
630 return ClientMetadata(name=name, redirect_uris=redirect_uris)
631
632
633def resolve_client_metadata(client_id: str) -> OAuthApplication:
634 """The one entry point: a URL client_id in, a current `OAuthApplication` out.
635
636 Uses the stored row while it's fresh and refetches when it has expired.
637 A transient refetch failure serves the stored row for a grace period
638 (retrying every few minutes); a document that's gone or invalid fails at
639 once. Raises `ClientMetadataError` when there's nothing usable.
640
641 The caller checks `is_client_id_url_allowed` first.
642 """
643 url = validate_client_id_url(client_id)
644
645 application = OAuthApplication.query.get_or_none(
646 OAuthApplication.client_id.equals(url)
647 )
648
649 now = timezone.now()
650 if (
651 application is not None
652 and application.metadata_expires_at is not None
653 and application.metadata_expires_at > now
654 ):
655 return application
656
657 try:
658 document, ttl = fetch_metadata_document(url)
659 metadata = validate_metadata_document(url=url, document=document)
660 except ClientMetadataError as exc:
661 if (
662 exc.transient
663 and application is not None
664 and application.metadata_fetched_at is not None
665 and now - application.metadata_fetched_at < STALE_GRACE_PERIOD
666 ):
667 logger.warning(
668 "Client metadata refetch failed, serving the stored document",
669 extra={"client_id": url, "reason": str(exc)},
670 )
671 application.metadata_expires_at = now + REFETCH_BACKOFF
672 application.update(fields=["metadata_expires_at"])
673 return application
674 logger.warning(
675 "Client metadata rejected",
676 extra={"client_id": url, "reason": str(exc)},
677 )
678 if not exc.transient and application is not None:
679 # The client's document is gone (404/410) or no longer valid. Forget the
680 # stored copy so a later outage can't bring it back, and so the
681 # token endpoint stops refreshing for this client until a
682 # successful fetch (draft -03 §6.2).
683 application.metadata_fetched_at = None
684 application.metadata_expires_at = None
685 application.update(fields=["metadata_fetched_at", "metadata_expires_at"])
686 raise
687
688 fields = {
689 "name": metadata.name,
690 "redirect_uris": " ".join(metadata.redirect_uris),
691 "metadata_fetched_at": now,
692 "metadata_expires_at": now + timedelta(seconds=ttl),
693 }
694
695 if application is None:
696 # Two first-time authorizations for the same URL can race here; the
697 # unique constraint on client_id makes the loser get the winner's row.
698 application, created = OAuthApplication.query.get_or_create(
699 client_id=url, defaults=fields
700 )
701 if created:
702 logger.info("Client metadata registered", extra={"client_id": url})
703 return application
704
705 if application.redirect_uris != fields["redirect_uris"]:
706 logger.info(
707 "Client metadata redirect_uris changed",
708 extra={"client_id": url, "redirect_uris": fields["redirect_uris"]},
709 )
710 for field, value in fields.items():
711 setattr(application, field, value)
712 application.update(fields=list(fields))
713 return application