|
| 1 | +import json |
| 2 | +import secrets |
| 3 | +import hashlib |
| 4 | +from typing import Any, Optional |
| 5 | +from sqlalchemy import text |
| 6 | +from database.db import get_db |
| 7 | + |
| 8 | + |
| 9 | +def generate_agent_key() -> dict: |
| 10 | + plain_key = "sk-mcp-" + secrets.token_hex(16) |
| 11 | + key_hash = hashlib.sha256(plain_key.encode()).hexdigest() |
| 12 | + prefix = plain_key[:13] + "..." |
| 13 | + return { |
| 14 | + "plain_key": plain_key, |
| 15 | + "key_hash": key_hash, |
| 16 | + "prefix": prefix, |
| 17 | + } |
| 18 | + |
| 19 | + |
| 20 | +async def get_all_agent_keys(org_id: int) -> list[dict]: |
| 21 | + async with get_db() as db: |
| 22 | + result = await db.execute( |
| 23 | + text(""" |
| 24 | + SELECT |
| 25 | + ak.id, |
| 26 | + ak.key_prefix, |
| 27 | + ak.name, |
| 28 | + ak.description, |
| 29 | + ak.allowed_tools, |
| 30 | + ak.blocked_tools, |
| 31 | + ak.allowed_server_ids, |
| 32 | + ak.rate_limit_rpm, |
| 33 | + ak.metadata, |
| 34 | + ak.expires_at, |
| 35 | + ak.is_active, |
| 36 | + ak.revoked_at, |
| 37 | + ak.created_by, |
| 38 | + ak.created_at, |
| 39 | + ak.updated_at, |
| 40 | + u.name AS created_by_name |
| 41 | + FROM ai_gateway_mcp_agent_keys ak |
| 42 | + LEFT JOIN users u ON u.id = ak.created_by |
| 43 | + WHERE ak.organization_id = :org_id |
| 44 | + ORDER BY ak.created_at DESC |
| 45 | + """), |
| 46 | + {"org_id": org_id}, |
| 47 | + ) |
| 48 | + rows = result.mappings().all() |
| 49 | + return [dict(row) for row in rows] |
| 50 | + return [] |
| 51 | + |
| 52 | + |
| 53 | +async def create_agent_key(org_id: int, data: dict) -> Optional[dict]: |
| 54 | + key_data = generate_agent_key() |
| 55 | + |
| 56 | + allowed_server_ids = data.get("allowed_server_ids") or [] |
| 57 | + metadata_value = data.get("metadata") |
| 58 | + metadata_json = json.dumps(metadata_value) if metadata_value is not None else "{}" |
| 59 | + expires_at = data.get("expires_at") |
| 60 | + created_by = data.get("created_by") |
| 61 | + rate_limit_rpm = data.get("rate_limit_rpm") |
| 62 | + name = data.get("name") |
| 63 | + description = data.get("description") |
| 64 | + allowed_tools = data.get("allowed_tools") or [] |
| 65 | + blocked_tools = data.get("blocked_tools") or [] |
| 66 | + |
| 67 | + async with get_db() as db: |
| 68 | + result = await db.execute( |
| 69 | + text(""" |
| 70 | + INSERT INTO ai_gateway_mcp_agent_keys ( |
| 71 | + organization_id, |
| 72 | + key_hash, |
| 73 | + key_prefix, |
| 74 | + name, |
| 75 | + description, |
| 76 | + allowed_tools, |
| 77 | + blocked_tools, |
| 78 | + allowed_server_ids, |
| 79 | + rate_limit_rpm, |
| 80 | + metadata, |
| 81 | + expires_at, |
| 82 | + created_by |
| 83 | + ) VALUES ( |
| 84 | + :org_id, |
| 85 | + :key_hash, |
| 86 | + :key_prefix, |
| 87 | + :name, |
| 88 | + :description, |
| 89 | + :allowed_tools, |
| 90 | + :blocked_tools, |
| 91 | + :allowed_server_ids, |
| 92 | + :rate_limit_rpm, |
| 93 | + CAST(:metadata AS jsonb), |
| 94 | + :expires_at, |
| 95 | + :created_by |
| 96 | + ) |
| 97 | + RETURNING |
| 98 | + id, |
| 99 | + key_prefix, |
| 100 | + name, |
| 101 | + description, |
| 102 | + allowed_tools, |
| 103 | + blocked_tools, |
| 104 | + allowed_server_ids, |
| 105 | + rate_limit_rpm, |
| 106 | + metadata, |
| 107 | + expires_at, |
| 108 | + is_active, |
| 109 | + revoked_at, |
| 110 | + created_by, |
| 111 | + created_at, |
| 112 | + updated_at |
| 113 | + """), |
| 114 | + { |
| 115 | + "org_id": org_id, |
| 116 | + "key_hash": key_data["key_hash"], |
| 117 | + "key_prefix": key_data["prefix"], |
| 118 | + "name": name, |
| 119 | + "description": description, |
| 120 | + "allowed_tools": allowed_tools, |
| 121 | + "blocked_tools": blocked_tools, |
| 122 | + "allowed_server_ids": allowed_server_ids, |
| 123 | + "rate_limit_rpm": rate_limit_rpm, |
| 124 | + "metadata": metadata_json, |
| 125 | + "expires_at": expires_at, |
| 126 | + "created_by": created_by, |
| 127 | + }, |
| 128 | + ) |
| 129 | + await db.commit() |
| 130 | + row = result.mappings().first() |
| 131 | + if row is None: |
| 132 | + return None |
| 133 | + record = dict(row) |
| 134 | + record["plain_key"] = key_data["plain_key"] |
| 135 | + return record |
| 136 | + return None |
| 137 | + |
| 138 | + |
| 139 | +async def update_agent_key(org_id: int, key_id: int, data: dict) -> Optional[dict]: |
| 140 | + set_clauses = [] |
| 141 | + params: dict[str, Any] = {"org_id": org_id, "key_id": key_id} |
| 142 | + |
| 143 | + if "name" in data: |
| 144 | + set_clauses.append("name = :name") |
| 145 | + params["name"] = data["name"] |
| 146 | + |
| 147 | + if "description" in data: |
| 148 | + set_clauses.append("description = :description") |
| 149 | + params["description"] = data["description"] |
| 150 | + |
| 151 | + for field in ("allowed_tools", "blocked_tools"): |
| 152 | + if field in data: |
| 153 | + set_clauses.append(f"{field} = :{field}") |
| 154 | + params[field] = data[field] if data[field] else [] |
| 155 | + |
| 156 | + if "allowed_server_ids" in data: |
| 157 | + set_clauses.append("allowed_server_ids = :allowed_server_ids") |
| 158 | + params["allowed_server_ids"] = data["allowed_server_ids"] or [] |
| 159 | + |
| 160 | + if "rate_limit_rpm" in data: |
| 161 | + set_clauses.append("rate_limit_rpm = :rate_limit_rpm") |
| 162 | + params["rate_limit_rpm"] = data["rate_limit_rpm"] |
| 163 | + |
| 164 | + if "metadata" in data: |
| 165 | + set_clauses.append("metadata = CAST(:metadata AS jsonb)") |
| 166 | + metadata_value = data["metadata"] |
| 167 | + params["metadata"] = json.dumps(metadata_value) if metadata_value is not None else "{}" |
| 168 | + |
| 169 | + if "expires_at" in data: |
| 170 | + set_clauses.append("expires_at = :expires_at") |
| 171 | + params["expires_at"] = data["expires_at"] |
| 172 | + |
| 173 | + if not set_clauses: |
| 174 | + return None |
| 175 | + |
| 176 | + set_clauses.append("updated_at = NOW()") |
| 177 | + |
| 178 | + sql = f""" |
| 179 | + UPDATE ai_gateway_mcp_agent_keys |
| 180 | + SET {", ".join(set_clauses)} |
| 181 | + WHERE organization_id = :org_id |
| 182 | + AND id = :key_id |
| 183 | + RETURNING |
| 184 | + id, |
| 185 | + key_prefix, |
| 186 | + name, |
| 187 | + description, |
| 188 | + allowed_tools, |
| 189 | + blocked_tools, |
| 190 | + allowed_server_ids, |
| 191 | + rate_limit_rpm, |
| 192 | + metadata, |
| 193 | + expires_at, |
| 194 | + is_active, |
| 195 | + revoked_at, |
| 196 | + created_by, |
| 197 | + created_at, |
| 198 | + updated_at |
| 199 | + """ |
| 200 | + |
| 201 | + async with get_db() as db: |
| 202 | + result = await db.execute(text(sql), params) |
| 203 | + await db.commit() |
| 204 | + row = result.mappings().first() |
| 205 | + if row is None: |
| 206 | + return None |
| 207 | + return dict(row) |
| 208 | + return None |
| 209 | + |
| 210 | + |
| 211 | +async def revoke_agent_key(org_id: int, key_id: int) -> bool: |
| 212 | + async with get_db() as db: |
| 213 | + result = await db.execute( |
| 214 | + text(""" |
| 215 | + UPDATE ai_gateway_mcp_agent_keys |
| 216 | + SET is_active = false, revoked_at = NOW(), updated_at = NOW() |
| 217 | + WHERE organization_id = :org_id |
| 218 | + AND id = :key_id |
| 219 | + AND is_active = true |
| 220 | + RETURNING id |
| 221 | + """), |
| 222 | + {"org_id": org_id, "key_id": key_id}, |
| 223 | + ) |
| 224 | + await db.commit() |
| 225 | + row = result.first() |
| 226 | + return row is not None |
| 227 | + return False |
| 228 | + |
| 229 | + |
| 230 | +async def delete_agent_key(org_id: int, key_id: int) -> bool: |
| 231 | + async with get_db() as db: |
| 232 | + result = await db.execute( |
| 233 | + text(""" |
| 234 | + DELETE FROM ai_gateway_mcp_agent_keys |
| 235 | + WHERE organization_id = :org_id |
| 236 | + AND id = :key_id |
| 237 | + AND is_active = false |
| 238 | + RETURNING id |
| 239 | + """), |
| 240 | + {"org_id": org_id, "key_id": key_id}, |
| 241 | + ) |
| 242 | + await db.commit() |
| 243 | + row = result.first() |
| 244 | + return row is not None |
| 245 | + return False |
0 commit comments