|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import re |
| 4 | +from typing import Dict, List, Optional |
| 5 | +from urllib.parse import urlparse |
| 6 | + |
| 7 | +from stoobly_agent.app.cli.helpers.openapi_endpoint_adapter import OpenApiEndpointAdapter |
| 8 | +from stoobly_agent.app.proxy.intercept_settings import InterceptSettings |
| 9 | +from stoobly_agent.app.proxy.mock.hashed_request_decorator import COMPONENT_TYPES |
| 10 | +from stoobly_agent.lib.api.interfaces.endpoints import EndpointShowResponse, IgnoredComponent |
| 11 | + |
| 12 | +logger = logging.getLogger(__name__) |
| 13 | + |
| 14 | +class OpenApiEndpointCache: |
| 15 | + """Lazy cache of parsed endpoints keyed by resolved absolute spec path.""" |
| 16 | + |
| 17 | + def __init__(self): |
| 18 | + self._by_path: Dict[str, List[EndpointShowResponse]] = {} |
| 19 | + |
| 20 | + def endpoints_for(self, open_api_spec: str) -> List[EndpointShowResponse]: |
| 21 | + key = _normalize_open_api_spec_path(open_api_spec) |
| 22 | + if key not in self._by_path: |
| 23 | + self._by_path[key] = load_openapi_endpoints_from_file(key) |
| 24 | + return self._by_path[key] |
| 25 | + |
| 26 | + |
| 27 | +_endpoint_cache = OpenApiEndpointCache() |
| 28 | + |
| 29 | +def load_openapi_endpoints_from_file(open_api_spec: str) -> List[EndpointShowResponse]: |
| 30 | + """ |
| 31 | + Parse an OpenAPI spec file into a list of endpoint show responses. |
| 32 | + """ |
| 33 | + try: |
| 34 | + return OpenApiEndpointAdapter().adapt_from_file(open_api_spec) |
| 35 | + except Exception as e: |
| 36 | + logger.warning("Failed to load OpenAPI spec %s: %s", open_api_spec, e) |
| 37 | + return [] |
| 38 | + |
| 39 | + |
| 40 | +def sql_like(value: str, pattern: str) -> bool: |
| 41 | + """ |
| 42 | + SQLite LIKE semantics for ASCII: % = any sequence, _ = single character. |
| 43 | + """ |
| 44 | + parts: List[str] = [] |
| 45 | + for c in pattern: |
| 46 | + if c == "%": |
| 47 | + parts.append(".*") |
| 48 | + elif c == "_": |
| 49 | + parts.append(".") |
| 50 | + else: |
| 51 | + parts.append(re.escape(c)) |
| 52 | + regex = "".join(parts) |
| 53 | + return re.fullmatch(regex, value, flags=re.DOTALL) is not None |
| 54 | + |
| 55 | + |
| 56 | +def _normalize_open_api_spec_path(open_api_spec: str) -> str: |
| 57 | + return os.path.abspath(os.path.normpath(open_api_spec)) |
| 58 | + |
| 59 | +def _request_port_str(uri) -> str: |
| 60 | + if uri.port is not None: |
| 61 | + return str(uri.port) |
| 62 | + if uri.scheme == "https": |
| 63 | + return "443" |
| 64 | + if uri.scheme == "http": |
| 65 | + return "80" |
| 66 | + return "0" |
| 67 | + |
| 68 | + |
| 69 | +def _endpoint_hostname_from_netloc(host_field: str) -> Optional[str]: |
| 70 | + """ |
| 71 | + OpenApiEndpointAdapter stores server netloc in host (e.g. 'localhost:80', 'petstore.swagger.io'). |
| 72 | + Requests use urlparse().hostname without port when the URL omits :port. |
| 73 | + """ |
| 74 | + if "://" in host_field: |
| 75 | + parsed = urlparse(host_field) |
| 76 | + else: |
| 77 | + parsed = urlparse("http://" + host_field) |
| 78 | + return parsed.hostname.lower() if parsed.hostname else None |
| 79 | + |
| 80 | + |
| 81 | +def _host_matches(endpoint: EndpointShowResponse, request_hostname: Optional[str]) -> bool: |
| 82 | + host = endpoint.get("host") or "" |
| 83 | + if not host or host == "%": |
| 84 | + return True |
| 85 | + if host == "-": |
| 86 | + return True |
| 87 | + if not request_hostname: |
| 88 | + return False |
| 89 | + ep_hostname = _endpoint_hostname_from_netloc(host) |
| 90 | + if ep_hostname is None: |
| 91 | + return True |
| 92 | + return ep_hostname == request_hostname.lower() |
| 93 | + |
| 94 | + |
| 95 | +def _port_matches(endpoint: EndpointShowResponse, request_port: str) -> bool: |
| 96 | + port = endpoint.get("port") or "" |
| 97 | + if not port or port == "%": |
| 98 | + return True |
| 99 | + return port == request_port |
| 100 | + |
| 101 | + |
| 102 | +def _path_matches(endpoint: EndpointShowResponse, request_path: str) -> bool: |
| 103 | + match_pattern = endpoint.get("match_pattern") or "" |
| 104 | + like_pattern = f"%{match_pattern}" |
| 105 | + return sql_like(request_path, like_pattern) |
| 106 | + |
| 107 | + |
| 108 | +def _find_matching_endpoint( |
| 109 | + endpoints: List[EndpointShowResponse], |
| 110 | + method: str, |
| 111 | + url: str, |
| 112 | +) -> Optional[EndpointShowResponse]: |
| 113 | + uri = urlparse(url) |
| 114 | + request_path = uri.path or "" |
| 115 | + request_path = request_path.rstrip("/") or "/" |
| 116 | + request_hostname = uri.hostname |
| 117 | + request_port = _request_port_str(uri) |
| 118 | + method_u = method.upper() |
| 119 | + |
| 120 | + for endpoint in endpoints: |
| 121 | + if endpoint.get("method", "").upper() != method_u: |
| 122 | + continue |
| 123 | + if not _host_matches(endpoint, request_hostname): |
| 124 | + continue |
| 125 | + if not _port_matches(endpoint, request_port): |
| 126 | + continue |
| 127 | + if not _path_matches(endpoint, request_path): |
| 128 | + continue |
| 129 | + return endpoint |
| 130 | + |
| 131 | + return None |
| 132 | + |
| 133 | + |
| 134 | +def _component_matches_ignoreable_ignored(component: dict) -> bool: |
| 135 | + """ |
| 136 | + Mirrors stoobly-api Ignoreable#ignored?: !is_deterministic || !is_required |
| 137 | + (see app/models/endpoint.rb ignored_components and app/models/concerns/ignoreable.rb). |
| 138 | + """ |
| 139 | + is_deterministic = component.get("is_deterministic", True) |
| 140 | + is_required = component.get("is_required", True) |
| 141 | + return (not is_deterministic) or (not is_required) |
| 142 | + |
| 143 | + |
| 144 | +def build_ignored_components_from_openapi_endpoint(endpoint: EndpointShowResponse) -> List[IgnoredComponent]: |
| 145 | + """ |
| 146 | + Mirrors Endpoint#ignored_components: query/header/body/response_header names where ignored?, |
| 147 | + serialized like endpoints/_ignored_component.json.jbuilder (name, query, type). |
| 148 | + """ |
| 149 | + out: List[IgnoredComponent] = [] |
| 150 | + |
| 151 | + for row in endpoint.get("query_param_names") or []: |
| 152 | + if _component_matches_ignoreable_ignored(row): |
| 153 | + out.append( |
| 154 | + { |
| 155 | + "name": row["name"], |
| 156 | + "query": row["name"], |
| 157 | + "type": COMPONENT_TYPES["QUERY_PARAM"], |
| 158 | + } |
| 159 | + ) |
| 160 | + |
| 161 | + for row in endpoint.get("header_names") or []: |
| 162 | + if _component_matches_ignoreable_ignored(row): |
| 163 | + out.append( |
| 164 | + { |
| 165 | + "name": row["name"], |
| 166 | + "query": row["name"], |
| 167 | + "type": COMPONENT_TYPES["HEADER"], |
| 168 | + } |
| 169 | + ) |
| 170 | + |
| 171 | + for row in endpoint.get("body_param_names") or []: |
| 172 | + if _component_matches_ignoreable_ignored(row): |
| 173 | + out.append( |
| 174 | + { |
| 175 | + "name": row["name"], |
| 176 | + "query": row["query"], |
| 177 | + "type": COMPONENT_TYPES["BODY_PARAM"], |
| 178 | + } |
| 179 | + ) |
| 180 | + |
| 181 | + for row in endpoint.get("response_header_names") or []: |
| 182 | + if _component_matches_ignoreable_ignored(row): |
| 183 | + out.append( |
| 184 | + { |
| 185 | + "name": row["name"], |
| 186 | + "query": row["name"], |
| 187 | + "type": COMPONENT_TYPES["RESPONSE_HEADER"], |
| 188 | + } |
| 189 | + ) |
| 190 | + |
| 191 | + return out |
| 192 | + |
| 193 | + |
| 194 | +def search_open_api_endpoint( |
| 195 | + open_api_spec: str, |
| 196 | + method: str, |
| 197 | + url: str, |
| 198 | + **_query_params, |
| 199 | +) -> Optional[EndpointShowResponse]: |
| 200 | + endpoints = _endpoint_cache.endpoints_for(open_api_spec) |
| 201 | + if not endpoints: |
| 202 | + return None |
| 203 | + ep = _find_matching_endpoint(endpoints, method, url) |
| 204 | + if ep is None: |
| 205 | + return None |
| 206 | + merged: EndpointShowResponse = dict(ep) |
| 207 | + merged["ignored_components"] = build_ignored_components_from_openapi_endpoint(ep) |
| 208 | + return merged |
| 209 | + |
| 210 | + |
| 211 | +def inject_search_open_api_endpoint(intercept_settings: InterceptSettings): |
| 212 | + def _search(method: str, url: str, **_query_params): |
| 213 | + open_api_spec = intercept_settings.openapi_specification_path |
| 214 | + if not open_api_spec: |
| 215 | + return None |
| 216 | + return search_open_api_endpoint(open_api_spec, method, url, **_query_params) |
| 217 | + |
| 218 | + return _search |
0 commit comments