| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import enum |
| 4 |
import logging |
| 5 |
import sys |
| 6 |
import textwrap |
| 7 |
import typing as t |
| 8 |
|
| 9 |
from globus_sdk._internal import guards |
| 10 |
|
| 11 |
from .base import GlobusError |
| 12 |
from .err_info import ErrorInfoContainer |
| 13 |
|
| 14 |
if t.TYPE_CHECKING: |
| 15 |
import requests |
| 16 |
|
| 17 |
log = logging.getLogger(__name__) |
| 18 |
|
| 19 |
_CACHE_SENTINEL = object() |
| 20 |
|
| 21 |
|
| 22 |
class _ErrorFormat(enum.Enum): |
| 23 |
undefined = enum.auto() |
| 24 |
jsonapi = enum.auto() |
| 25 |
type_zero = enum.auto() |
| 26 |
|
| 27 |
|
| 28 |
class GlobusAPIError(GlobusError): |
| 29 |
""" |
| 30 |
Wraps errors returned by a REST API. |
| 31 |
|
| 32 |
:ivar int http_status: HTTP status code |
| 33 |
:ivar str code: Error code from the API or ``None`` for unclassified errors |
| 34 |
:ivar str request_id: The 'request_id' included in the error data, if any. |
| 35 |
:ivar list[str] messages: A list of error messages, extracted from the response |
| 36 |
data. If the data cannot be parsed or does not contain any clear message fields, |
| 37 |
this list may be empty. |
| 38 |
:ivar list[GlobusSubError] errors: A list of sub-error documents, as would be |
| 39 |
presented by JSON:API APIs and similar interfaces. |
| 40 |
""" |
| 41 |
|
| 42 |
MESSAGE_FIELDS = ["message", "detail", "title"] |
| 43 |
RECOGNIZED_AUTHZ_SCHEMES = ["bearer", "basic", "globus-goauthtoken"] |
| 44 |
|
| 45 |
def __init__(self, r: requests.Response, *args: t.Any, **kwargs: t.Any) -> None: |
| 46 |
self._cached_raw_json: t.Any = _CACHE_SENTINEL |
| 47 |
|
| 48 |
self.http_status = r.status_code |
| 49 |
# defaults, may be rewritten during parsing |
| 50 |
self.code: str | None = None |
| 51 |
self.request_id: str | None = None |
| 52 |
self.messages: list[str] = [] |
| 53 |
self.errors: list[ErrorSubdocument] = [] |
| 54 |
|
| 55 |
self._info: ErrorInfoContainer | None = None |
| 56 |
self._underlying_response = r |
| 57 |
self._parse_response() |
| 58 |
|
| 59 |
if sys.version_info >= (3, 11): |
| 60 |
self.add_note( # pylint: disable=no-member |
| 61 |
( |
| 62 |
"This exception was caused by an API error. " |
| 63 |
"The response body is as follows:\n\n" |
| 64 |
) |
| 65 |
+ textwrap.indent(self.text, " ") |
| 66 |
) |
| 67 |
super().__init__(*self._get_args()) |
| 68 |
|
| 69 |
@property |
| 70 |
def message(self) -> str | None: |
| 71 |
""" |
| 72 |
An error message from the API. |
| 73 |
|
| 74 |
If there are multiple messages available, this will contain all messages joined |
| 75 |
with semicolons. If there is no message available, this will be ``None``. |
| 76 |
""" |
| 77 |
if self.messages: |
| 78 |
return "; ".join(self.messages) |
| 79 |
return None |
| 80 |
|
| 81 |
@property |
| 82 |
def http_reason(self) -> str: |
| 83 |
""" |
| 84 |
The HTTP reason string from the response. |
| 85 |
|
| 86 |
This is the part of the status line after the status code, and typically is a |
| 87 |
string description of the status. If the status line is |
| 88 |
``HTTP/1.1 404 Not Found``, then this is the string ``"Not Found"``. |
| 89 |
""" |
| 90 |
return self._underlying_response.reason |
| 91 |
|
| 92 |
@property |
| 93 |
def headers(self) -> t.Mapping[str, str]: |
| 94 |
""" |
| 95 |
The HTTP response headers as a case-insensitive mapping. |
| 96 |
|
| 97 |
For example, ``headers["Content-Length"]`` and ``headers["content-length"]`` are |
| 98 |
treated as equivalent. |
| 99 |
""" |
| 100 |
return self._underlying_response.headers |
| 101 |
|
| 102 |
@property |
| 103 |
def content_type(self) -> str | None: |
| 104 |
return self.headers.get("Content-Type") |
| 105 |
|
| 106 |
def _get_mimetype(self, content_type: str) -> str: |
| 107 |
return content_type.split(";")[0].strip() |
| 108 |
|
| 109 |
def _jsonapi_mimetype(self) -> bool: |
| 110 |
if self.content_type is None: |
| 111 |
return False |
| 112 |
return self._get_mimetype(self.content_type) == "application/vnd.api+json" |
| 113 |
|
| 114 |
def _json_mimetype(self) -> bool: |
| 115 |
if self.content_type is None: |
| 116 |
return False |
| 117 |
mimetype = self._get_mimetype(self.content_type) |
| 118 |
if mimetype == "application/json": |
| 119 |
return True |
| 120 |
if mimetype.startswith("application/") and mimetype.endswith("+json"): |
| 121 |
return True |
| 122 |
return False |
| 123 |
|
| 124 |
@property |
| 125 |
def raw_json(self) -> dict[str, t.Any] | None: |
| 126 |
""" |
| 127 |
Get the verbatim error message received from a Globus API, interpreted |
| 128 |
as JSON data |
| 129 |
|
| 130 |
If the body cannot be loaded as JSON, this is None |
| 131 |
""" |
| 132 |
if self._cached_raw_json == _CACHE_SENTINEL: |
| 133 |
self._cached_raw_json = None |
| 134 |
if self._json_mimetype(): |
| 135 |
try: |
| 136 |
# technically, this could be a non-dict JSON type, like a list or |
| 137 |
# string but in those cases the user can just cast -- the "normal" |
| 138 |
# case is a dict |
| 139 |
self._cached_raw_json = self._underlying_response.json() |
| 140 |
except ValueError: |
| 141 |
log.error( |
| 142 |
"Error body could not be JSON decoded! " |
| 143 |
"This means the Content-Type is wrong, or the " |
| 144 |
"body is malformed!" |
| 145 |
) |
| 146 |
return t.cast("dict[str, t.Any]", self._cached_raw_json) |
| 147 |
|
| 148 |
@property |
| 149 |
def _dict_data(self) -> dict[str, t.Any]: |
| 150 |
""" |
| 151 |
A "type asserting" wrapper over raw_json which errors if the type is not dict. |
| 152 |
""" |
| 153 |
if not isinstance(self.raw_json, dict): |
| 154 |
raise ValueError("cannot use _dict_data when data is non-dict type") |
| 155 |
return self.raw_json |
| 156 |
|
| 157 |
@property |
| 158 |
def text(self) -> str: |
| 159 |
""" |
| 160 |
Get the verbatim error message received from a Globus API as a *string* |
| 161 |
""" |
| 162 |
return self._underlying_response.text |
| 163 |
|
| 164 |
@property |
| 165 |
def binary_content(self) -> bytes: |
| 166 |
""" |
| 167 |
The error message received from a Globus API in bytes. |
| 168 |
""" |
| 169 |
return self._underlying_response.content |
| 170 |
|
| 171 |
@property |
| 172 |
def info(self) -> ErrorInfoContainer: |
| 173 |
""" |
| 174 |
An ``ErrorInfoContainer`` with parsed error data. The ``info`` of an error is |
| 175 |
guaranteed to be present, but all of its contents may be falsey if the error |
| 176 |
could not be parsed. |
| 177 |
""" |
| 178 |
if self._info is None: |
| 179 |
json_data = self.raw_json if isinstance(self.raw_json, dict) else None |
| 180 |
self._info = ErrorInfoContainer(json_data) |
| 181 |
return self._info |
| 182 |
|
| 183 |
def _get_request_authorization_scheme(self) -> str | None: |
| 184 |
try: |
| 185 |
authz_h = self._underlying_response.request.headers["Authorization"] |
| 186 |
authz_scheme = authz_h.split()[0] |
| 187 |
if authz_scheme.lower() in self.RECOGNIZED_AUTHZ_SCHEMES: |
| 188 |
return authz_scheme |
| 189 |
except (IndexError, KeyError): |
| 190 |
pass |
| 191 |
return None |
| 192 |
|
| 193 |
def _get_args(self) -> list[t.Any]: |
| 194 |
""" |
| 195 |
Get arguments to pass to the Exception base class. These args are |
| 196 |
displayed in stack traces. |
| 197 |
""" |
| 198 |
args = [ |
| 199 |
self._underlying_response.request.method, |
| 200 |
self._underlying_response.url, |
| 201 |
self._get_request_authorization_scheme(), |
| 202 |
self.http_status, |
| 203 |
self.code, |
| 204 |
# if the message is "", try using response reason |
| 205 |
# for details on these, and some examples, see |
| 206 |
# https://datatracker.ietf.org/doc/html/rfc7231#section-6.1 |
| 207 |
self.message or self._underlying_response.reason, |
| 208 |
] |
| 209 |
if self.request_id: |
| 210 |
args.append(self.request_id) |
| 211 |
return args |
| 212 |
|
| 213 |
def _parse_response(self) -> bool: |
| 214 |
""" |
| 215 |
This is an intermediate step between 'raw_json' (loading bare JSON data) |
| 216 |
and the "real" parsing methods. |
| 217 |
|
| 218 |
In order to better support subclassing with short-circuiting behaviors if |
| 219 |
parsing goes awry, all of the parsing methods return True if parsing should |
| 220 |
continue or False if it was aborted. |
| 221 |
|
| 222 |
_parse_response() pulls the JSON body and does the following: |
| 223 |
|
| 224 |
- on non-dict JSON data, log and abort early. Don't error since this |
| 225 |
is already part of exception construction, just stop parsing. |
| 226 |
|
| 227 |
- Attempt to detect the error format in use, then dispatch to the relevant |
| 228 |
subparser: JSON:API, Type Zero, or Undefined |
| 229 |
|
| 230 |
- if subparsing succeeded, call the `_post_parse_hook` hook to allow |
| 231 |
subclasses to trivially add more computed attributes. This could also be |
| 232 |
done by altering `__init__` but it's nicer to have a dedicated hook because |
| 233 |
it is guaranteed to only be called if the rest of parsing succeeded |
| 234 |
""" |
| 235 |
if self.raw_json is None: |
| 236 |
log.debug("Error body was not parsed as JSON") |
| 237 |
return False |
| 238 |
if not isinstance(self.raw_json, dict): |
| 239 |
log.warning( # type: ignore[unreachable] |
| 240 |
"Error body could not be parsed as JSON because it was not a dict" |
| 241 |
) |
| 242 |
return False |
| 243 |
|
| 244 |
error_format = self._detect_error_format() |
| 245 |
subparse_result: bool |
| 246 |
if error_format == _ErrorFormat.jsonapi: |
| 247 |
subparse_result = self._parse_jsonapi_error_format() |
| 248 |
elif error_format == _ErrorFormat.type_zero: |
| 249 |
subparse_result = self._parse_type_zero_error_format() |
| 250 |
else: |
| 251 |
subparse_result = self._parse_undefined_error_format() |
| 252 |
|
| 253 |
if not subparse_result: |
| 254 |
return False |
| 255 |
return self._post_parse_hook() |
| 256 |
|
| 257 |
def _post_parse_hook(self) -> bool: |
| 258 |
""" |
| 259 |
An internal callback for extra customizations after fully successful parsing. |
| 260 |
|
| 261 |
By default, does nothing. |
| 262 |
""" |
| 263 |
return True |
| 264 |
|
| 265 |
def _detect_error_format(self) -> _ErrorFormat: |
| 266 |
# if the JSON:API mimetype was used, inspect the data to make sure it is |
| 267 |
# well-formed |
| 268 |
if self._jsonapi_mimetype(): |
| 269 |
errors = self._dict_data.get("errors") |
| 270 |
if not guards.is_list_of(errors, dict): |
| 271 |
return _ErrorFormat.undefined |
| 272 |
elif len(errors) < 1: |
| 273 |
return _ErrorFormat.undefined |
| 274 |
elif not all(isinstance(error_doc, dict) for error_doc in errors): |
| 275 |
return _ErrorFormat.undefined |
| 276 |
|
| 277 |
# only use 'jsonapi' if everything checked out |
| 278 |
return _ErrorFormat.jsonapi |
| 279 |
|
| 280 |
# now evaluate attributes for Type Zero errors under the same paradigm |
| 281 |
# check each attribute and only return 'type_zero' if nothing failed |
| 282 |
|
| 283 |
if not isinstance(self._dict_data.get("code"), str): |
| 284 |
return _ErrorFormat.undefined |
| 285 |
elif not isinstance(self._dict_data.get("message"), str): |
| 286 |
return _ErrorFormat.undefined |
| 287 |
# request_id is not required, but must be a string if present |
| 288 |
elif "request_id" in self._dict_data and not isinstance( |
| 289 |
self._dict_data["request_id"], str |
| 290 |
): |
| 291 |
return _ErrorFormat.undefined |
| 292 |
|
| 293 |
return _ErrorFormat.type_zero |
| 294 |
|
| 295 |
def _parse_jsonapi_error_format(self) -> bool: |
| 296 |
""" |
| 297 |
Parsing a JSON:API Error |
| 298 |
|
| 299 |
This is only called after the field type for 'errors' has been checked. |
| 300 |
However, the nested/underlying fields will not have been checked yet. |
| 301 |
""" |
| 302 |
self.errors = [ErrorSubdocument(e) for e in self._dict_data["errors"]] |
| 303 |
self.code = self._extract_code_from_error_array(self.errors) |
| 304 |
self.messages = self._extract_messages_from_error_array(self.errors) |
| 305 |
return True |
| 306 |
|
| 307 |
def _parse_type_zero_error_format(self) -> bool: |
| 308 |
""" |
| 309 |
Parsing a Type Zero Error |
| 310 |
|
| 311 |
This is only called after Type Zero has been detected. Therefore, we already |
| 312 |
have assurances about the values in 'code' and 'message'. |
| 313 |
Note that 'request_id' could be absent but *must* be a string if present. |
| 314 |
""" |
| 315 |
self.code = self._dict_data["code"] |
| 316 |
self.messages = [self._dict_data["message"]] |
| 317 |
self.request_id = self._dict_data.get("request_id") |
| 318 |
if guards.is_list_of(self._dict_data.get("errors"), dict): |
| 319 |
raw_errors = self._dict_data["errors"] |
| 320 |
else: |
| 321 |
raw_errors = [self._dict_data] |
| 322 |
self.errors = [ |
| 323 |
ErrorSubdocument(e, message_fields=self.MESSAGE_FIELDS) for e in raw_errors |
| 324 |
] |
| 325 |
return True |
| 326 |
|
| 327 |
def _parse_undefined_error_format(self) -> bool: |
| 328 |
""" |
| 329 |
Undefined Parsing: best effort support for unknown data shapes |
| 330 |
|
| 331 |
This is also a great place for custom parsing to hook in for different APIs |
| 332 |
if we know that there's an unusual format in use |
| 333 |
""" |
| 334 |
|
| 335 |
# attempt to pull out errors if possible and valid |
| 336 |
if guards.is_list_of(self._dict_data.get("errors"), dict): |
| 337 |
raw_errors = self._dict_data["errors"] |
| 338 |
# if no 'errors' were found, or 'errors' is invalid, then |
| 339 |
# 'errors' should be set to contain the root document |
| 340 |
else: |
| 341 |
raw_errors = [self._dict_data] |
| 342 |
self.errors = [ |
| 343 |
ErrorSubdocument(e, message_fields=self.MESSAGE_FIELDS) for e in raw_errors |
| 344 |
] |
| 345 |
|
| 346 |
# use 'code' if present and correct type |
| 347 |
if isinstance(self._dict_data.get("code"), str): |
| 348 |
self.code = t.cast(str, self._dict_data["code"]) |
| 349 |
# otherwise, pull 'code' from the sub-errors array |
| 350 |
elif self.errors: |
| 351 |
# in undefined parse cases, the code will be left as `"Error"` for |
| 352 |
# a higher degree of backwards compatibility |
| 353 |
maybe_code = self._extract_code_from_error_array(self.errors) |
| 354 |
if maybe_code is not None: |
| 355 |
self.code = maybe_code |
| 356 |
|
| 357 |
# either there is an array of subdocument errors or there is not, |
| 358 |
# in which case we load only from the root doc |
| 359 |
self.messages = self._extract_messages_from_error_array( |
| 360 |
self.errors |
| 361 |
or [ErrorSubdocument(self._dict_data, message_fields=self.MESSAGE_FIELDS)] |
| 362 |
) |
| 363 |
|
| 364 |
return True |
| 365 |
|
| 366 |
def _extract_messages_from_error_array( |
| 367 |
self, errors: list[ErrorSubdocument] |
| 368 |
) -> list[str]: |
| 369 |
""" |
| 370 |
Extract 'messages' from an array of errors (JSON:API or otherwise) |
| 371 |
|
| 372 |
Each subdocument *may* define its messages, so this is the aggregate of messages |
| 373 |
from those documents which had messages. |
| 374 |
|
| 375 |
Note that subdocuments may be instructed about their `message_fields` by the |
| 376 |
error class and parsing path which they take. Therefore, this may be extracting |
| 377 |
`"message"`, `"detail"`, or `"title"` in the base implementation and other |
| 378 |
fields if a subclass customizes this further. |
| 379 |
""" |
| 380 |
ret: list[str] = [] |
| 381 |
for doc in errors: |
| 382 |
if doc.message is not None: |
| 383 |
ret.append(doc.message) |
| 384 |
return ret |
| 385 |
|
| 386 |
def _extract_code_from_error_array( |
| 387 |
self, errors: list[ErrorSubdocument] |
| 388 |
) -> str | None: |
| 389 |
""" |
| 390 |
Extract a 'code' field from an array of errors (JSON:API or otherwise) |
| 391 |
|
| 392 |
This is done by checking if each error document has the same 'code' |
| 393 |
""" |
| 394 |
codes: set[str] = set() |
| 395 |
for error in errors: |
| 396 |
if error.code is not None: |
| 397 |
codes.add(error.code) |
| 398 |
if len(codes) == 1: |
| 399 |
return codes.pop() |
| 400 |
return None |
| 401 |
|
| 402 |
|
| 403 |
class ErrorSubdocument: |
| 404 |
""" |
| 405 |
Error subdocuments as returned by Globus APIs. |
| 406 |
|
| 407 |
:ivar dict raw: The unparsed error subdocument |
| 408 |
""" |
| 409 |
|
| 410 |
# the default set of fields to use for message extraction, in order |
| 411 |
# selected to match the fields defined by JSON:API by default |
| 412 |
DEFAULT_MESSAGE_FIELDS: tuple[str, ...] = ("detail", "title") |
| 413 |
|
| 414 |
def __init__( |
| 415 |
self, data: dict[str, t.Any], *, message_fields: t.Sequence[str] | None = None |
| 416 |
) -> None: |
| 417 |
self.raw = data |
| 418 |
self._message_fields: tuple[str, ...] |
| 419 |
|
| 420 |
if message_fields is not None: |
| 421 |
self._message_fields = tuple(message_fields) |
| 422 |
else: |
| 423 |
self._message_fields = self.DEFAULT_MESSAGE_FIELDS |
| 424 |
|
| 425 |
@property |
| 426 |
def message(self) -> str | None: |
| 427 |
""" |
| 428 |
The 'message' string of this subdocument, derived from its data based on the |
| 429 |
parsing context. |
| 430 |
|
| 431 |
May be `None` if no message is defined. |
| 432 |
""" |
| 433 |
return _extract_message_from_dict(self.raw, self._message_fields) |
| 434 |
|
| 435 |
@property |
| 436 |
def code(self) -> str | None: |
| 437 |
""" |
| 438 |
The 'code' string of this subdocument, derived from its data based on the |
| 439 |
parsing context. |
| 440 |
|
| 441 |
May be `None` if no code is defined. |
| 442 |
""" |
| 443 |
if isinstance(self.raw.get("code"), str): |
| 444 |
return t.cast(str, self.raw["code"]) |
| 445 |
return None |
| 446 |
|
| 447 |
def get(self, key: str, default: t.Any = None) -> t.Any | None: |
| 448 |
""" |
| 449 |
A dict-like getter for the raw data. |
| 450 |
|
| 451 |
:param key: The string key to use for lookup |
| 452 |
:param default: The default value to use |
| 453 |
""" |
| 454 |
return self.raw.get(key, default) |
| 455 |
|
| 456 |
|
| 457 |
def _extract_message_from_dict( |
| 458 |
data: dict[str, t.Any], message_fields: tuple[str, ...] |
| 459 |
) -> str | None: |
| 460 |
""" |
| 461 |
Extract a single message string from a dict if one is present. |
| 462 |
""" |
| 463 |
for f in message_fields: |
| 464 |
if isinstance(data.get(f), str): |
| 465 |
return t.cast(str, data[f]) |
| 466 |
return None |