|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import hashlib |
| 4 | +import hmac |
| 5 | +import logging |
| 6 | +import re |
| 7 | +from collections.abc import Mapping, Sequence |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +import sqlalchemy as sa |
| 11 | +import trafaret as t |
| 12 | +from aiohttp import web |
| 13 | +from dateutil.parser import parse as dateutil_parse |
| 14 | + |
| 15 | +from ai.backend.common.logging_utils import BraceStyleAdapter |
| 16 | +from ai.backend.common.plugin.hook import HookHandler, HookPlugin, Reject |
| 17 | +from ai.backend.common.utils import nmget |
| 18 | +from ai.backend.manager.errors.auth import AuthorizationFailed, InvalidAuthParameters |
| 19 | +from ai.backend.manager.models.keypair import KeyPairRow, keypairs |
| 20 | +from ai.backend.manager.models.user import UserStatus, users |
| 21 | + |
| 22 | +from .utils import deserialize_stoken |
| 23 | + |
| 24 | +log = BraceStyleAdapter(logging.getLogger(__spec__.name)) |
| 25 | + |
| 26 | +plugin_config_checker = t.Dict({ |
| 27 | + t.Key("auth_token_name", default="sToken"): t.Null | t.String, |
| 28 | +}).allow_extra("*") |
| 29 | + |
| 30 | + |
| 31 | +DEFAULT_STOKEN_COOKIE_VALUE = "BackendAI" |
| 32 | + |
| 33 | + |
| 34 | +class KeypairAuthHookPlugin(HookPlugin): |
| 35 | + def __init__(self, plugin_config: Mapping[str, Any], local_config: Mapping[str, Any]) -> None: |
| 36 | + super().__init__(plugin_config, local_config) |
| 37 | + self.plugin_config = plugin_config_checker.check(self.plugin_config) |
| 38 | + |
| 39 | + def get_handlers(self) -> Sequence[tuple[str, HookHandler]]: |
| 40 | + return [ |
| 41 | + ("AUTHORIZE", self.authorize), |
| 42 | + ] |
| 43 | + |
| 44 | + async def update_plugin_config(self, plugin_config: Mapping[str, Any]) -> None: |
| 45 | + self.plugin_config = plugin_config |
| 46 | + |
| 47 | + async def init(self, context: Any = None) -> None: |
| 48 | + pass |
| 49 | + |
| 50 | + async def cleanup(self) -> None: |
| 51 | + pass |
| 52 | + |
| 53 | + def parse_token(self, token: str) -> tuple[str, str, str] | None: |
| 54 | + pattern = r"BackendAI signMethod=(?P<sign_method>[A-Z0-9-]+), credential=(?P<access_key>\w+):(?P<signature>\w+)" |
| 55 | + match = re.search(pattern, token) |
| 56 | + if match: |
| 57 | + sign_method = match.group("sign_method") |
| 58 | + access_key = match.group("access_key") |
| 59 | + signature = match.group("signature") |
| 60 | + return (sign_method, access_key, signature) |
| 61 | + return None |
| 62 | + |
| 63 | + async def sign_token(self, sign_method: str, secret_key: str, params: Mapping[str, Any]) -> str: |
| 64 | + try: |
| 65 | + mac_type, hash_type = map(lambda s: s.lower(), sign_method.split("-")) |
| 66 | + if mac_type != "hmac": |
| 67 | + raise InvalidAuthParameters("Unsupported signing method (MAC type)") |
| 68 | + if hash_type not in hashlib.algorithms_guaranteed: |
| 69 | + raise InvalidAuthParameters("Unsupported signing method (hash type)") |
| 70 | + |
| 71 | + date_obj = dateutil_parse(params["date"]) |
| 72 | + date = date_obj.isoformat() |
| 73 | + endpoint = params["endpoint"] |
| 74 | + api_version = params["api_version"] |
| 75 | + if date is None: |
| 76 | + raise InvalidAuthParameters("Request date is missing") |
| 77 | + if endpoint is None: |
| 78 | + raise InvalidAuthParameters("Request endpoint is missing") |
| 79 | + if api_version is None: |
| 80 | + raise InvalidAuthParameters("API version is missing") |
| 81 | + |
| 82 | + body = b"" |
| 83 | + body_hash = hashlib.new(hash_type, body).hexdigest() |
| 84 | + sign_bytes = ( |
| 85 | + "{0}\n{1}\n{2}\nhost:{3}\ncontent-type:{4}\nx-{name}-version:{5}\n{6}".format( |
| 86 | + "POST", |
| 87 | + "/authorize/keypair", |
| 88 | + date, |
| 89 | + endpoint, |
| 90 | + "application/json", |
| 91 | + api_version, |
| 92 | + body_hash, |
| 93 | + name="backendai", |
| 94 | + ) |
| 95 | + ).encode() |
| 96 | + sign_key = hmac.new( |
| 97 | + secret_key.encode(), date_obj.strftime("%Y%m%d").encode(), hash_type |
| 98 | + ).digest() |
| 99 | + sign_key = hmac.new(sign_key, endpoint.encode(), hash_type).digest() |
| 100 | + return hmac.new(sign_key, sign_bytes, hash_type).hexdigest() |
| 101 | + except ValueError: |
| 102 | + raise AuthorizationFailed("Invalid signature") from None |
| 103 | + |
| 104 | + async def authorize( |
| 105 | + self, |
| 106 | + request: web.Request, |
| 107 | + params: Mapping[str, Any], |
| 108 | + ) -> Any: |
| 109 | + root_app = request.app["_root_app"] |
| 110 | + db = root_app["_db"] |
| 111 | + config_provider = root_app["_config_provider"] |
| 112 | + shared_config = await config_provider.legacy_etcd_config_loader.load() |
| 113 | + plugin_config = nmget(shared_config, "plugins.webapp.keypair_auth") |
| 114 | + auth_token_name = self.plugin_config["auth_token_name"] |
| 115 | + |
| 116 | + stoken = params[auth_token_name] |
| 117 | + if stoken: |
| 118 | + secret = plugin_config["secret"] |
| 119 | + try: |
| 120 | + payload = deserialize_stoken(stoken, secret) |
| 121 | + query = sa.select(KeyPairRow).where(KeyPairRow.access_key == payload.access_key) |
| 122 | + async with db.begin_readonly_session() as db_session: |
| 123 | + keypair_row = await db_session.scalar(query) |
| 124 | + user_id = keypair_row.user |
| 125 | + |
| 126 | + except Exception: |
| 127 | + try: |
| 128 | + result = self.parse_token(stoken) |
| 129 | + if not result: |
| 130 | + raise Reject("invalid authentication token") |
| 131 | + sign_method, access_key, signature = result |
| 132 | + |
| 133 | + async with db.begin() as conn: |
| 134 | + query = ( |
| 135 | + sa.select(keypairs.c.user, keypairs.c.secret_key) |
| 136 | + .select_from(keypairs) |
| 137 | + .where(keypairs.c.access_key == access_key) |
| 138 | + ) |
| 139 | + result = await conn.execute(query) |
| 140 | + keypair = result.fetchone() |
| 141 | + |
| 142 | + sign_params = { |
| 143 | + "date": params["date"], |
| 144 | + "endpoint": params["endpoint"], |
| 145 | + "api_version": params["api_version"], |
| 146 | + } |
| 147 | + generated_token = await self.sign_token( |
| 148 | + sign_method, keypair["secret_key"], sign_params |
| 149 | + ) |
| 150 | + if generated_token != signature: |
| 151 | + raise Reject("Invalid auth token") |
| 152 | + user_id = keypair["user"] |
| 153 | + |
| 154 | + except Exception as e: |
| 155 | + log.error("AUTHORIZE_KEYPAIR_HOOK: invalid auth token {}", stoken) |
| 156 | + log.error(repr(e)) |
| 157 | + raise Reject("Invalid auth token") from None |
| 158 | + |
| 159 | + else: |
| 160 | + return None |
| 161 | + |
| 162 | + async with db.begin() as conn: |
| 163 | + query = ( |
| 164 | + sa.select(users.c.uuid, users.c.status) |
| 165 | + .select_from(users) |
| 166 | + .where(users.c.uuid == user_id) |
| 167 | + ) |
| 168 | + result = await conn.execute(query) |
| 169 | + user = result.fetchone() |
| 170 | + if not user: |
| 171 | + raise Reject("No such user with access key") |
| 172 | + if user["status"] != UserStatus.ACTIVE: |
| 173 | + raise Reject("user is inactivated with access key") |
| 174 | + return user |
0 commit comments