|
| 1 | +import json |
| 2 | +import logging |
| 3 | + |
| 4 | +from asgiref.typing import ( |
| 5 | + ASGI3Application, |
| 6 | + ASGIReceiveCallable, |
| 7 | + ASGIReceiveEvent, |
| 8 | + ASGISendCallable, |
| 9 | + Scope, |
| 10 | +) |
| 11 | +from typing import List, Tuple, Optional |
| 12 | + |
| 13 | +from mauth_client.authenticator import LocalAuthenticator |
| 14 | +from mauth_client.config import Config |
| 15 | +from mauth_client.consts import ( |
| 16 | + ENV_APP_UUID, |
| 17 | + ENV_AUTHENTIC, |
| 18 | + ENV_PROTOCOL_VERSION, |
| 19 | +) |
| 20 | +from mauth_client.signable import RequestSignable |
| 21 | +from mauth_client.signed import Signed |
| 22 | +from mauth_client.utils import decode |
| 23 | + |
| 24 | +logger = logging.getLogger("mauth_asgi") |
| 25 | + |
| 26 | + |
| 27 | +class MAuthASGIMiddleware: |
| 28 | + def __init__(self, app: ASGI3Application, exempt: Optional[set] = None) -> None: |
| 29 | + self._validate_configs() |
| 30 | + self.app = app |
| 31 | + self.exempt = exempt.copy() if exempt else set() |
| 32 | + |
| 33 | + async def __call__( |
| 34 | + self, scope: Scope, receive: ASGIReceiveCallable, send: ASGISendCallable |
| 35 | + ) -> None: |
| 36 | + path = scope["path"] |
| 37 | + |
| 38 | + if scope["type"] != "http" or path in self.exempt: |
| 39 | + return await self.app(scope, receive, send) |
| 40 | + |
| 41 | + query_string = scope["query_string"] |
| 42 | + url = f"{path}?{decode(query_string)}" if query_string else path |
| 43 | + headers = {decode(k): decode(v) for k, v in scope["headers"]} |
| 44 | + |
| 45 | + events, body = await self._get_body(receive) |
| 46 | + |
| 47 | + signable = RequestSignable( |
| 48 | + method=scope["method"], |
| 49 | + url=url, |
| 50 | + body=body, |
| 51 | + ) |
| 52 | + signed = Signed.from_headers(headers) |
| 53 | + authenticator = LocalAuthenticator(signable, signed, logger) |
| 54 | + is_authentic, status, message = authenticator.is_authentic() |
| 55 | + |
| 56 | + if is_authentic: |
| 57 | + # asgi spec calls for passing a copy of the scope rather than mutating it |
| 58 | + # note: deepcopy will blow up with infi recursion due to objects in some values |
| 59 | + scope_copy = scope.copy() |
| 60 | + scope_copy[ENV_APP_UUID] = signed.app_uuid |
| 61 | + scope_copy[ENV_AUTHENTIC] = True |
| 62 | + scope_copy[ENV_PROTOCOL_VERSION] = signed.protocol_version() |
| 63 | + await self.app(scope_copy, self._fake_receive(events), send) |
| 64 | + else: |
| 65 | + await self._send_response(send, status, message) |
| 66 | + |
| 67 | + def _validate_configs(self) -> None: |
| 68 | + # Validate the client settings (APP_UUID, PRIVATE_KEY) |
| 69 | + if not all([Config.APP_UUID, Config.PRIVATE_KEY]): |
| 70 | + raise TypeError("MAuthASGIMiddleware requires APP_UUID and PRIVATE_KEY") |
| 71 | + # Validate the mauth settings (MAUTH_BASE_URL, MAUTH_API_VERSION) |
| 72 | + if not all([Config.MAUTH_URL, Config.MAUTH_API_VERSION]): |
| 73 | + raise TypeError("MAuthASGIMiddleware requires MAUTH_URL and MAUTH_API_VERSION") |
| 74 | + |
| 75 | + async def _get_body( |
| 76 | + self, receive: ASGIReceiveCallable |
| 77 | + ) -> Tuple[List[ASGIReceiveEvent], bytes]: |
| 78 | + body = b"" |
| 79 | + more_body = True |
| 80 | + events = [] |
| 81 | + |
| 82 | + while more_body: |
| 83 | + event = await receive() |
| 84 | + body += event.get("body", b"") |
| 85 | + more_body = event.get("more_body", False) |
| 86 | + events.append(event) |
| 87 | + return (events, body) |
| 88 | + |
| 89 | + async def _send_response(self, send: ASGISendCallable, status: int, msg: str) -> None: |
| 90 | + await send({ |
| 91 | + "type": "http.response.start", |
| 92 | + "status": status, |
| 93 | + "headers": [(b"content-type", b"application/json")], |
| 94 | + }) |
| 95 | + body = {"errors": {"mauth": [msg]}} |
| 96 | + await send({ |
| 97 | + "type": "http.response.body", |
| 98 | + "body": json.dumps(body).encode("utf-8"), |
| 99 | + }) |
| 100 | + |
| 101 | + def _fake_receive(self, events: List[ASGIReceiveEvent]) -> ASGIReceiveCallable: |
| 102 | + """ |
| 103 | + Create a fake, async receive function using an iterator of the events |
| 104 | + we've already read. This will be passed to downstream middlewares/apps |
| 105 | + instead of the usual receive fn, so that they can also "receive" the |
| 106 | + body events. |
| 107 | + """ |
| 108 | + events_iter = iter(events) |
| 109 | + |
| 110 | + async def _receive() -> ASGIReceiveEvent: |
| 111 | + try: |
| 112 | + return next(events_iter) |
| 113 | + except StopIteration: |
| 114 | + pass |
| 115 | + return _receive |
0 commit comments