|
| 1 | +import logging |
| 2 | +import os |
| 3 | +from functools import lru_cache |
| 4 | +from typing import NamedTuple |
| 5 | +from typing import Optional |
| 6 | + |
| 7 | +import cachetools.func |
| 8 | +import requests |
| 9 | +from twisted.web.server import Request |
| 10 | + |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | +AUTH_CACHE_SIZE = 50000 |
| 14 | +AUTH_CACHE_TTL = 30 * 60 |
| 15 | + |
| 16 | + |
| 17 | +class AuthorizationOutcome(NamedTuple): |
| 18 | + authorized: bool |
| 19 | + reason: str |
| 20 | + |
| 21 | + |
| 22 | +class AuthorizationFilter: |
| 23 | + """API request authorization via external system""" |
| 24 | + |
| 25 | + def __init__(self, endpoint: str, enforce: bool): |
| 26 | + """Constructor |
| 27 | +
|
| 28 | + :param str endpoint: HTTP endpoint of external authorization system |
| 29 | + :param bool enforce: whether to enforce authorization decisions |
| 30 | + """ |
| 31 | + self.endpoint = endpoint |
| 32 | + self.enforce = enforce |
| 33 | + self.session = requests.Session() |
| 34 | + |
| 35 | + @classmethod |
| 36 | + @lru_cache(maxsize=1) |
| 37 | + def get_from_env(cls) -> "AuthorizationFilter": |
| 38 | + return cls( |
| 39 | + endpoint=os.getenv("API_AUTH_ENDPOINT", ""), |
| 40 | + enforce=bool(os.getenv("API_AUTH_ENFORCE", "")), |
| 41 | + ) |
| 42 | + |
| 43 | + def is_request_authorized(self, request: Request) -> AuthorizationOutcome: |
| 44 | + """Check if API request is authorized |
| 45 | +
|
| 46 | + :param Request request: API request object |
| 47 | + :return: auth outcome |
| 48 | + """ |
| 49 | + if not self.endpoint: |
| 50 | + return AuthorizationOutcome(True, "Auth not enabled") |
| 51 | + token = (request.getHeader("Authorization") or "").strip() |
| 52 | + token = token.split()[-1] if token else "" # removes "Bearer" prefix |
| 53 | + url_path = request.path.decode() |
| 54 | + service = url_path.split("/")[-1].split(".", 1)[0] if "/jobs/" in url_path else None |
| 55 | + auth_outcome = self._is_request_authorized_impl( |
| 56 | + # path and method are byte arrays in twisted |
| 57 | + path=url_path, |
| 58 | + token=token, |
| 59 | + method=request.method.decode(), |
| 60 | + service=service, |
| 61 | + ) |
| 62 | + return auth_outcome if self.enforce else AuthorizationOutcome(True, "Auth dry-run") |
| 63 | + |
| 64 | + @cachetools.func.ttl_cache(maxsize=AUTH_CACHE_SIZE, ttl=AUTH_CACHE_TTL) |
| 65 | + def _is_request_authorized_impl( |
| 66 | + self, |
| 67 | + path: str, |
| 68 | + token: str, |
| 69 | + method: str, |
| 70 | + service: Optional[str], |
| 71 | + ) -> AuthorizationOutcome: |
| 72 | + """Check if API request is authorized |
| 73 | +
|
| 74 | + :param str path: API path |
| 75 | + :param str token: authentication token |
| 76 | + :param str method: http method |
| 77 | + :return: auth outcome |
| 78 | + """ |
| 79 | + try: |
| 80 | + response = self.session.post( |
| 81 | + url=self.endpoint, |
| 82 | + json={ |
| 83 | + "input": { |
| 84 | + "path": path, |
| 85 | + "backend": "tron", |
| 86 | + "token": token, |
| 87 | + "method": method.lower(), |
| 88 | + "service": service, |
| 89 | + }, |
| 90 | + }, |
| 91 | + timeout=2, |
| 92 | + ).json() |
| 93 | + except Exception as e: |
| 94 | + logger.exception(f"Issue communicating with auth endpoint: {e}") |
| 95 | + return AuthorizationOutcome(False, "Auth backend error") |
| 96 | + |
| 97 | + auth_result_allowed = response.get("result", {}).get("allowed") |
| 98 | + if auth_result_allowed is None: |
| 99 | + return AuthorizationOutcome(False, "Malformed auth response") |
| 100 | + |
| 101 | + if not auth_result_allowed: |
| 102 | + reason = response["result"].get("reason", "Denied") |
| 103 | + return AuthorizationOutcome(False, reason) |
| 104 | + |
| 105 | + reason = response["result"].get("reason", "Ok") |
| 106 | + return AuthorizationOutcome(True, reason) |
0 commit comments