|
| 1 | +# Copyright 2025 Zeppelin Bend Pty Ltd |
| 2 | +# |
| 3 | +# This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | +# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | +# file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 6 | + |
| 7 | +__all__ = ['BaseAuthMethod', 'TokenAuth'] |
| 8 | + |
| 9 | + |
| 10 | +from hashlib import sha256 |
| 11 | +from typing import Optional, overload |
| 12 | + |
| 13 | +from aiohttp import ClientSession |
| 14 | +from zepben.auth import ZepbenTokenFetcher, create_token_fetcher, AuthMethod, create_token_fetcher_managed_identity |
| 15 | + |
| 16 | + |
| 17 | +class EasClient: |
| 18 | + protocol: str = "https", |
| 19 | + verify_certificate: bool = True, |
| 20 | + ca_filename: Optional[str] = None, |
| 21 | + session: ClientSession = None, |
| 22 | + json_serialiser=None |
| 23 | + |
| 24 | + |
| 25 | +class BaseAuthMethod: |
| 26 | + def __init__(self, host, port, protocol='https', verify_certificate=True): |
| 27 | + """ |
| 28 | +
|
| 29 | + :param host: The domain of the Evolve App Server, e.g. "evolve.local" |
| 30 | + :param port: The port on which to make requests to the Evolve App Server, e.g. 7624 |
| 31 | + :param protocol: The protocol of the Evolve App Server. Should be either "http" or "https". Must be "https" if |
| 32 | + auth is configured. (Defaults to "https") |
| 33 | + :param verify_certificate: Set this to "False" to disable certificate verification. This will also apply to the |
| 34 | + auth provider if auth is initialised via client id + username + password or |
| 35 | + client_id + client_secret. (Defaults to True) |
| 36 | + """ |
| 37 | + self._host = host |
| 38 | + self._port = port |
| 39 | + self.protocol = protocol |
| 40 | + self.verify_certificate = verify_certificate |
| 41 | + |
| 42 | + @property |
| 43 | + def base_url_args(self) -> dict: |
| 44 | + return dict(host=self._host, port=self._port, protocol=self.protocol) |
| 45 | + |
| 46 | + |
| 47 | +class TokenAuth(BaseAuthMethod): |
| 48 | + """ |
| 49 | + Token Auth Method for Evolve App Server python client when connecting to HTTPS servers. |
| 50 | +
|
| 51 | + Token Authentication may be configured in one of three ways: |
| 52 | + - Providing an access token via the access_token parameter |
| 53 | + - Specifying the client ID of the Auth0 application via the client_id parameter, plus one of the following: |
| 54 | + - A username and password pair via the username and password parameters (account authentication) |
| 55 | + - The client secret via the client_secret parameter (M2M authentication) |
| 56 | + If this method is used, the auth configuration will be fetched from the Evolve App Server at the path |
| 57 | + "/api/config/auth". |
| 58 | + - Specifying a ZepbenTokenFetcher directly via the token_fetcher parameter |
| 59 | +
|
| 60 | + ..code-block:: python:: |
| 61 | +
|
| 62 | + TokenAuth(access_token='...') |
| 63 | + TokenAuth(token_fetcher='...') |
| 64 | + TokenAuth(client_id='...' username='...' password='...') |
| 65 | + TokenAuth(client_id='...', client_secret='...') |
| 66 | +
|
| 67 | + """ |
| 68 | + @overload |
| 69 | + def __init__(self, host, port, protocol='https', verify_certificate=True, *, access_token: str): |
| 70 | + """ |
| 71 | + :param access_token: The access token used for authentication, generated by Evolve App Server. |
| 72 | + """ |
| 73 | + ... |
| 74 | + |
| 75 | + @overload |
| 76 | + def __init__(self, host, port, protocol='https', verify_certificate=True, *, token_fetcher: ZepbenTokenFetcher): |
| 77 | + """ |
| 78 | + :param token_fetcher: A ZepbenTokenFetcher used to fetch auth tokens for access to the Evolve App Server. |
| 79 | + """ |
| 80 | + ... |
| 81 | + |
| 82 | + @overload |
| 83 | + def __init__(self, host, port, protocol='https', verify_certificate=True, *, client_id: str, username: str, password: str, client_secret: Optional[str]): |
| 84 | + """ |
| 85 | + :param client_id: The Auth0 client ID used to specify to the auth server which application to request a token for. |
| 86 | + :param username: The username used for account authentication. |
| 87 | + :param password: The password used for account authentication. |
| 88 | + :param client_secret: The Auth0 client secret used for M2M authentication. (Optional) |
| 89 | + """ |
| 90 | + ... |
| 91 | + |
| 92 | + @overload |
| 93 | + def __init__(self, host, port, protocol='https', verify_certificate=True, *, client_id: str, client_secret: str): |
| 94 | + """ |
| 95 | + :param client_id: The Auth0 client ID used to specify to the auth server which application to request a token for. |
| 96 | + :param client_secret: The Auth0 client secret used for M2M authentication. |
| 97 | + """ |
| 98 | + ... |
| 99 | + |
| 100 | + def __init__(self, host, port, protocol='https', verify_certificate=True, **kwargs): |
| 101 | + if protocol != 'https': # TODO: this exists because of an existing test, but given we can force it, we should |
| 102 | + raise ValueError( |
| 103 | + "Incompatible arguments passed to connect to secured Evolve App Server. " |
| 104 | + "Authentication tokens must be sent via https. " |
| 105 | + "To resolve this issue, exclude the \"protocol\" argument when initialising the EasClient.") |
| 106 | + |
| 107 | + super().__init__(host, port, protocol, verify_certificate) |
| 108 | + self._token_fetcher = None |
| 109 | + self._access_token = None |
| 110 | + self._init_func = None |
| 111 | + self._configure(kwargs) |
| 112 | + |
| 113 | + @property |
| 114 | + def token(self) -> Optional[str]: |
| 115 | + if self._access_token: |
| 116 | + return f"Bearer {self._access_token}" |
| 117 | + elif self._token_fetcher: |
| 118 | + return self._token_fetcher.fetch_token() |
| 119 | + raise AttributeError("access_token or token_fetcher method not configured") |
| 120 | + |
| 121 | + def _configure(self, kwargs: dict): |
| 122 | + """ |
| 123 | + Validates that the kwargs that end up being passed to the non-overloaded `__init__` method are of a valid |
| 124 | + combination. |
| 125 | + """ |
| 126 | + match list(kwargs.keys()): |
| 127 | + case ['access_token']: |
| 128 | + self._access_token = kwargs['access_token'] |
| 129 | + case ['token_fetcher']: |
| 130 | + self._token_fetcher = kwargs['token_fetcher'] |
| 131 | + case ['client_id', 'client_secret', 'username', 'password']: |
| 132 | + self._configure_client_id(**kwargs) |
| 133 | + case ['client_id', 'username', 'password']: |
| 134 | + self._configure_client_id(**kwargs) |
| 135 | + case ['client_id', 'client_secret']: |
| 136 | + self._configure_client_id(**kwargs) |
| 137 | + case _: |
| 138 | + raise ValueError("Incompatible arguments passed to connect to secured Evolve App Server.") |
| 139 | + |
| 140 | + if kwargs.get('client_id'): |
| 141 | + self._token_fetcher = create_token_fetcher( |
| 142 | + conf_address=f"{self.protocol}://{self._host}:{self._port}/api/config/auth", |
| 143 | + verify_conf=self.verify_certificate, |
| 144 | + ) |
| 145 | + |
| 146 | + def _configure_client_id( |
| 147 | + self, client_id: str = None, |
| 148 | + username: str = None, |
| 149 | + password: str = None, |
| 150 | + client_secret: str = None |
| 151 | + ): |
| 152 | + self._token_fetcher = create_token_fetcher( |
| 153 | + conf_address=f"{self.protocol}://{self._host}:{self._port}/api/config/auth", |
| 154 | + verify_conf=self.verify_certificate, |
| 155 | + ) |
| 156 | + if self._token_fetcher: |
| 157 | + scope = ( |
| 158 | + 'trusted' if self._token_fetcher.auth_method is AuthMethod.SELF else 'offline_access openid profile email0' |
| 159 | + ) |
| 160 | + |
| 161 | + self._token_fetcher.token_request_data.update({ |
| 162 | + 'client_id': client_id, |
| 163 | + 'scope': scope |
| 164 | + }) |
| 165 | + self._token_fetcher.refresh_request_data.update({ |
| 166 | + "grant_type": "refresh_token", |
| 167 | + 'client_id': client_id, |
| 168 | + 'scope': scope |
| 169 | + }) |
| 170 | + if username and password: |
| 171 | + self._token_fetcher.token_request_data.update({ |
| 172 | + 'grant_type': 'password', |
| 173 | + 'username': username, |
| 174 | + 'password': |
| 175 | + sha256(password.encode('utf-8')).hexdigest() |
| 176 | + if self._token_fetcher.auth_method is AuthMethod.SELF |
| 177 | + else password |
| 178 | + }) |
| 179 | + if client_secret: |
| 180 | + self._token_fetcher.token_request_data.update({'client_secret': client_secret}) |
| 181 | + |
| 182 | + elif client_secret: |
| 183 | + self._token_fetcher.token_request_data.update({ |
| 184 | + 'grant_type': 'client_credentials', |
| 185 | + 'client_secret': client_secret |
| 186 | + }) |
| 187 | + else: |
| 188 | + # Attempt azure managed identity (what a hack) |
| 189 | + url = "http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01" |
| 190 | + self._token_fetcher = create_token_fetcher_managed_identity( |
| 191 | + identity_url=f"{url}&resource={client_id}", |
| 192 | + verify_auth=self.verify_certificate |
| 193 | + ) |
0 commit comments