|
| 1 | +# |
| 2 | +# Licensed to the Apache Software Foundation (ASF) under one |
| 3 | +# or more contributor license agreements. See the NOTICE file |
| 4 | +# distributed with this work for additional information |
| 5 | +# regarding copyright ownership. The ASF licenses this file |
| 6 | +# to you under the Apache License, Version 2.0 (the |
| 7 | +# "License"); you may not use this file except in compliance |
| 8 | +# with the License. You may obtain a copy of the License at |
| 9 | +# |
| 10 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | +# |
| 12 | +# Unless required by applicable law or agreed to in writing, |
| 13 | +# software distributed under the License is distributed on an |
| 14 | +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 15 | +# KIND, either express or implied. See the License for the |
| 16 | +# specific language governing permissions and limitations |
| 17 | +# under the License. |
| 18 | +# |
| 19 | + |
| 20 | +"""Authorization helpers for the Polaris MCP server.""" |
| 21 | + |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +import json |
| 25 | +import threading |
| 26 | +import time |
| 27 | +from abc import ABC, abstractmethod |
| 28 | +from typing import Optional |
| 29 | +from urllib.parse import urlencode |
| 30 | + |
| 31 | +import urllib3 |
| 32 | + |
| 33 | + |
| 34 | +class AuthorizationProvider(ABC): |
| 35 | + """Return Authorization header values for outgoing requests.""" |
| 36 | + |
| 37 | + @abstractmethod |
| 38 | + def authorization_header(self) -> Optional[str]: ... |
| 39 | + |
| 40 | + |
| 41 | +class StaticAuthorizationProvider(AuthorizationProvider): |
| 42 | + """Wrap a static bearer token.""" |
| 43 | + |
| 44 | + def __init__(self, token: Optional[str]) -> None: |
| 45 | + value = (token or "").strip() |
| 46 | + self._header = f"Bearer {value}" if value else None |
| 47 | + |
| 48 | + def authorization_header(self) -> Optional[str]: |
| 49 | + return self._header |
| 50 | + |
| 51 | + |
| 52 | +class ClientCredentialsAuthorizationProvider(AuthorizationProvider): |
| 53 | + """Implements the OAuth client-credentials flow with caching.""" |
| 54 | + |
| 55 | + def __init__( |
| 56 | + self, |
| 57 | + token_endpoint: str, |
| 58 | + client_id: str, |
| 59 | + client_secret: str, |
| 60 | + scope: Optional[str], |
| 61 | + http: urllib3.PoolManager, |
| 62 | + ) -> None: |
| 63 | + self._token_endpoint = token_endpoint |
| 64 | + self._client_id = client_id |
| 65 | + self._client_secret = client_secret |
| 66 | + self._scope = scope |
| 67 | + self._http = http |
| 68 | + self._lock = threading.Lock() |
| 69 | + self._cached: Optional[tuple[str, float]] = None # (token, expires_at_epoch) |
| 70 | + |
| 71 | + def authorization_header(self) -> Optional[str]: |
| 72 | + token = self._current_token() |
| 73 | + return f"Bearer {token}" if token else None |
| 74 | + |
| 75 | + def _current_token(self) -> Optional[str]: |
| 76 | + now = time.time() |
| 77 | + cached = self._cached |
| 78 | + if not cached or cached[1] - 60 <= now: |
| 79 | + with self._lock: |
| 80 | + cached = self._cached |
| 81 | + if not cached or cached[1] - 60 <= time.time(): |
| 82 | + self._cached = cached = self._fetch_token() |
| 83 | + return cached[0] if cached else None |
| 84 | + |
| 85 | + def _fetch_token(self) -> tuple[str, float]: |
| 86 | + payload = { |
| 87 | + "grant_type": "client_credentials", |
| 88 | + "client_id": self._client_id, |
| 89 | + "client_secret": self._client_secret, |
| 90 | + } |
| 91 | + if self._scope: |
| 92 | + payload["scope"] = self._scope |
| 93 | + |
| 94 | + encoded = urlencode(payload) |
| 95 | + response = self._http.request( |
| 96 | + "POST", |
| 97 | + self._token_endpoint, |
| 98 | + body=encoded, |
| 99 | + headers={"Content-Type": "application/x-www-form-urlencoded"}, |
| 100 | + timeout=urllib3.Timeout(connect=20.0, read=20.0), |
| 101 | + ) |
| 102 | + |
| 103 | + if response.status != 200: |
| 104 | + raise RuntimeError( |
| 105 | + f"OAuth token endpoint returned {response.status}: {response.data.decode('utf-8', errors='ignore')}" |
| 106 | + ) |
| 107 | + |
| 108 | + try: |
| 109 | + document = json.loads(response.data.decode("utf-8")) |
| 110 | + except json.JSONDecodeError as error: |
| 111 | + raise RuntimeError("OAuth token endpoint returned invalid JSON") from error |
| 112 | + |
| 113 | + token = document.get("access_token") |
| 114 | + if not isinstance(token, str) or not token: |
| 115 | + raise RuntimeError("OAuth token response missing access_token") |
| 116 | + |
| 117 | + expires_in = document.get("expires_in", 3600) |
| 118 | + try: |
| 119 | + ttl = float(expires_in) |
| 120 | + except (TypeError, ValueError): |
| 121 | + ttl = 3600.0 |
| 122 | + ttl = max(ttl, 60.0) |
| 123 | + expires_at = time.time() + ttl |
| 124 | + return token, expires_at |
| 125 | + |
| 126 | + |
| 127 | +class _NoneAuthorizationProvider(AuthorizationProvider): |
| 128 | + def authorization_header(self) -> Optional[str]: |
| 129 | + return None |
| 130 | + |
| 131 | + |
| 132 | +def none() -> AuthorizationProvider: |
| 133 | + """Return an AuthorizationProvider that never supplies a header.""" |
| 134 | + |
| 135 | + return _NoneAuthorizationProvider() |
0 commit comments