botversion-sdk 2.2.2__py3-none-any.whl → 2.2.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -28,6 +28,23 @@ def should_ignore(path, extra_ignore=None):
28
28
  return any(path.startswith(p) for p in ignore)
29
29
 
30
30
 
31
+ def is_multipart_content_type(value):
32
+ # True when the request carries a file-upload body that must not be read as JSON
33
+ return "multipart/form-data" in str(value or "").lower()
34
+
35
+
36
+ def raise_if_multipart(content_type):
37
+ # Placed first inside body-reading try blocks: skips reading uploads (existing except handles it)
38
+ if is_multipart_content_type(content_type):
39
+ raise ValueError("multipart body")
40
+
41
+
42
+ def with_multipart_marker(schema):
43
+ out = dict(schema) if schema else {"type": "object", "properties": {}}
44
+ out["x-content-type"] = "multipart/form-data"
45
+ return out
46
+
47
+
31
48
  def normalize_path(path):
32
49
  """
33
50
  Replace dynamic segments with :id
@@ -213,7 +230,7 @@ def extract_trpc_get_input_raw(path, query_string):
213
230
  return None
214
231
 
215
232
 
216
- def _report_single_endpoint(client, method, normalized_path, body_structure, options):
233
+ def _report_single_endpoint(client, method, normalized_path, body_structure, options, multipart=False):
217
234
  """
218
235
  Reports exactly one already-normalized, already-split endpoint.
219
236
  Uses body-key deduplication.
@@ -221,7 +238,7 @@ def _report_single_endpoint(client, method, normalized_path, body_structure, opt
221
238
  endpoint_key = f"{method}:{normalized_path}"
222
239
 
223
240
  body_fields = sorted(body_structure.keys()) if body_structure else []
224
- body_key = endpoint_key + ":" + ",".join(body_fields)
241
+ body_key = endpoint_key + ":" + ",".join(body_fields) + (":multipart" if multipart else "")
225
242
 
226
243
  with _lock:
227
244
  if body_key in _reported:
@@ -229,6 +246,8 @@ def _report_single_endpoint(client, method, normalized_path, body_structure, opt
229
246
  _reported.add(body_key)
230
247
 
231
248
  json_schema = body_structure_to_json_schema(body_structure)
249
+ if multipart:
250
+ json_schema = with_multipart_marker(json_schema)
232
251
 
233
252
  # update_endpoint only queues the update (sending happens in the background), so it never
234
253
  # blocks the request, and the queue order matches the order of calls.
@@ -243,7 +262,7 @@ def _report_single_endpoint(client, method, normalized_path, body_structure, opt
243
262
  return None
244
263
 
245
264
 
246
- def report_endpoint(client, method, path, body_data, query_string, options):
265
+ def report_endpoint(client, method, path, body_data, query_string, options, content_type=None):
247
266
  """
248
267
  Splits a (possibly batched) tRPC path into one clean endpoint per real
249
268
  procedure — instead of one garbled, comma-joined path — with each
@@ -254,6 +273,11 @@ def report_endpoint(client, method, path, body_data, query_string, options):
254
273
  body_data — the raw parsed JSON body (or None/empty for GET requests).
255
274
  query_string — the raw query string, used to recover tRPC GET input.
256
275
  """
276
+ multipart = is_multipart_content_type(content_type)
277
+ if multipart:
278
+ body_data = None
279
+ query_string = None
280
+
257
281
  split_paths = [normalize_path(p) for p in split_batch_path(path)]
258
282
 
259
283
  body_slots = None
@@ -272,7 +296,7 @@ def report_endpoint(client, method, path, body_data, query_string, options):
272
296
  for i, single_path in enumerate(split_paths):
273
297
  slot_body = body_slots[i] if i < len(body_slots) else None
274
298
  body_structure = build_body_structure(slot_body)
275
- _report_single_endpoint(client, method, single_path, body_structure, options)
299
+ _report_single_endpoint(client, method, single_path, body_structure, options, multipart)
276
300
 
277
301
 
278
302
  # ── FastAPI middleware ────────────────────────────────────────────────────────
@@ -316,6 +340,7 @@ def attach_fastapi_interceptor(app, client, options):
316
340
  if not should_ignore(path, options.get("exclude")):
317
341
  if not options.get("api_prefix") or path.startswith(options["api_prefix"]):
318
342
  try:
343
+ raise_if_multipart(request.headers.get("content-type"))
319
344
  body_bytes = await request.body()
320
345
  async def receive():
321
346
  return {"type": "http.request", "body": body_bytes}
@@ -325,7 +350,7 @@ def attach_fastapi_interceptor(app, client, options):
325
350
  body_data = None
326
351
 
327
352
  if response.status_code < 500:
328
- report_endpoint(client, method, path, body_data, request.url.query, options)
353
+ report_endpoint(client, method, path, body_data, request.url.query, options, request.headers.get("content-type"))
329
354
 
330
355
  return response
331
356
 
@@ -381,7 +406,7 @@ def attach_flask_interceptor(app, client, options):
381
406
  except Exception:
382
407
  body_data = None
383
408
 
384
- report_endpoint(client, method, path, body_data, flask_request.query_string.decode("utf-8"), options)
409
+ report_endpoint(client, method, path, body_data, flask_request.query_string.decode("utf-8"), options, flask_request.content_type)
385
410
 
386
411
  @app.after_request
387
412
  def botversion_response_capture(response):
@@ -443,6 +468,7 @@ class BotVersionDjangoMiddleware:
443
468
  if not should_ignore(path, self.__class__._options.get("exclude")):
444
469
  if not self.__class__._options.get("api_prefix") or path.startswith(self.__class__._options["api_prefix"]):
445
470
  try:
471
+ raise_if_multipart(request.META.get("CONTENT_TYPE"))
446
472
  body_data = json.loads(request.body) if request.body else None
447
473
  except Exception:
448
474
  body_data = None
@@ -455,6 +481,7 @@ class BotVersionDjangoMiddleware:
455
481
  body_data,
456
482
  request.META.get("QUERY_STRING", ""),
457
483
  self.__class__._options,
484
+ request.META.get("CONTENT_TYPE"),
458
485
  )
459
486
 
460
487
  # Drops cache-validation headers so the app sends a full reply instead of an empty 304
@@ -549,13 +576,14 @@ def attach_starlette_interceptor(app, client, options):
549
576
  if not should_ignore(path, options.get("exclude")):
550
577
  if not options.get("api_prefix") or path.startswith(options["api_prefix"]):
551
578
  try:
579
+ raise_if_multipart(request.headers.get("content-type"))
552
580
  body_bytes = await request.body()
553
581
  body_data = _json.loads(body_bytes) if body_bytes else None
554
582
  except Exception:
555
583
  body_data = None
556
584
 
557
585
  if response.status_code < 500:
558
- report_endpoint(client, method, path, body_data, request.url.query, options)
586
+ report_endpoint(client, method, path, body_data, request.url.query, options, request.headers.get("content-type"))
559
587
 
560
588
  return response
561
589
 
@@ -597,11 +625,12 @@ def attach_sanic_interceptor(app, client, options):
597
625
  return
598
626
 
599
627
  try:
628
+ raise_if_multipart(request.headers.get("content-type"))
600
629
  body_data = request.json if request.body else None
601
630
  except Exception:
602
631
  body_data = None
603
632
 
604
- report_endpoint(client, method, path, body_data, request.query_string, options)
633
+ report_endpoint(client, method, path, body_data, request.query_string, options, request.headers.get("content-type"))
605
634
 
606
635
  @app.middleware("response")
607
636
  async def botversion_sanic_response_capture(request, response):
@@ -661,6 +690,7 @@ def attach_falcon_interceptor(app, client, options):
661
690
  return
662
691
 
663
692
  try:
693
+ raise_if_multipart(req.content_type)
664
694
  body_bytes = req.bounded_stream.read()
665
695
  body_data = _json.loads(body_bytes) if body_bytes else None
666
696
  # Put body back so the actual handler can still read it
@@ -669,7 +699,7 @@ def attach_falcon_interceptor(app, client, options):
669
699
  except Exception:
670
700
  body_data = None
671
701
 
672
- report_endpoint(client, method, path, body_data, req.query_string, options)
702
+ report_endpoint(client, method, path, body_data, req.query_string, options, req.content_type)
673
703
 
674
704
  def process_response(self, req, resp, resource, req_succeeded):
675
705
  # Capture the shape of the successful JSON reply (field names only)
@@ -742,11 +772,12 @@ def attach_bottle_interceptor(app, client, options):
742
772
  return
743
773
 
744
774
  try:
775
+ raise_if_multipart(bottle_request.content_type)
745
776
  body_data = bottle_request.json
746
777
  except Exception:
747
778
  body_data = None
748
779
 
749
- report_endpoint(client, method, path, body_data, bottle_request.query_string, options)
780
+ report_endpoint(client, method, path, body_data, bottle_request.query_string, options, bottle_request.content_type)
750
781
 
751
782
  # Install on the specific app instance, not globally
752
783
  app.add_hook("before_request", botversion_bottle_interceptor)
@@ -826,13 +857,14 @@ def attach_aiohttp_interceptor(app, client, options):
826
857
  if not should_ignore(path, options.get("exclude")):
827
858
  if not options.get("api_prefix") or path.startswith(options["api_prefix"]):
828
859
  try:
860
+ raise_if_multipart(request.headers.get("Content-Type"))
829
861
  body_bytes = await request.read()
830
862
  body_data = _json.loads(body_bytes) if body_bytes else None
831
863
  except Exception:
832
864
  body_data = None
833
865
 
834
866
  if response.status < 500:
835
- report_endpoint(client, method, path, body_data, request.rel_url.query_string, options)
867
+ report_endpoint(client, method, path, body_data, request.rel_url.query_string, options, request.headers.get("Content-Type"))
836
868
 
837
869
  # Capture the shape of the successful JSON reply (field names only)
838
870
  try:
@@ -934,13 +966,14 @@ def attach_tornado_interceptor(app, client, options):
934
966
  if not should_ignore(path, options.get("exclude")):
935
967
  if not options.get("api_prefix") or path.startswith(options["api_prefix"]):
936
968
  try:
969
+ raise_if_multipart(self.request.headers.get("Content-Type"))
937
970
  body_bytes = self.request.body
938
971
  body_data = _json.loads(body_bytes) if body_bytes else None
939
972
  except Exception:
940
973
  body_data = None
941
974
 
942
975
  if self.get_status() < 500:
943
- report_endpoint(client, method, path, body_data, self.request.query, options)
976
+ report_endpoint(client, method, path, body_data, self.request.query, options, self.request.headers.get("Content-Type"))
944
977
 
945
978
  # Capture the shape of the successful JSON reply (field names only)
946
979
  if should_watch_response(method, path, options):
@@ -1006,12 +1039,13 @@ def botversion_pyramid_tween_factory(handler, registry):
1006
1039
  if _pyramid_client and not should_ignore(path, _pyramid_options.get("exclude")):
1007
1040
  if not _pyramid_options.get("api_prefix") or path.startswith(_pyramid_options["api_prefix"]):
1008
1041
  try:
1042
+ raise_if_multipart(request.content_type)
1009
1043
  body_data = request.json_body if request.content_length else None
1010
1044
  except Exception:
1011
1045
  body_data = None
1012
1046
 
1013
1047
  if response.status_int < 500:
1014
- report_endpoint(_pyramid_client, method, path, body_data, request.query_string, _pyramid_options)
1048
+ report_endpoint(_pyramid_client, method, path, body_data, request.query_string, _pyramid_options, request.content_type)
1015
1049
  except Exception:
1016
1050
  pass
1017
1051
 
@@ -1087,6 +1121,7 @@ def attach_cherrypy_interceptor(app, client, options):
1087
1121
  return
1088
1122
 
1089
1123
  try:
1124
+ raise_if_multipart(request.headers.get("Content-Type"))
1090
1125
  body_bytes = request.body.read() if request.body else None
1091
1126
  body_data = _json.loads(body_bytes) if body_bytes else None
1092
1127
  # Put body back so actual handler can still read it
@@ -1096,7 +1131,7 @@ def attach_cherrypy_interceptor(app, client, options):
1096
1131
  body_data = None
1097
1132
 
1098
1133
  query_string = request.query_string if hasattr(request, "query_string") else ""
1099
- report_endpoint(client, method, path, body_data, query_string, options)
1134
+ report_endpoint(client, method, path, body_data, query_string, options, request.headers.get("Content-Type"))
1100
1135
 
1101
1136
  # Register as a CherryPy tool
1102
1137
  cherrypy.tools.botversion = cherrypy.Tool(
botversion_sdk/scanner.py CHANGED
@@ -79,7 +79,7 @@ def scan_fastapi_routes(app):
79
79
  "method": method,
80
80
  "path": normalized_path,
81
81
  "description": generate_description(method, normalized_path, handler_name),
82
- "requestBody": extract_request_body_schema(route, method),
82
+ "requestBody": merge_body_with_multipart(extract_request_body_schema(route, method), extract_fastapi_multipart_schema(route, method)),
83
83
  "responseBody": extract_fastapi_response_schema(route) or extract_static_response_from_callable(_resolve_view_handler(getattr(route, "endpoint", None), method)),
84
84
  "detectedBy": "static-scan",
85
85
  })
@@ -131,10 +131,13 @@ def scan_flask_routes(app):
131
131
  "method": method,
132
132
  "path": path,
133
133
  "description": generate_description(method, path, handler_name),
134
- "requestBody": (
135
- extract_flask_schema(handler_fn, method) or
136
- extract_restx_resource_schema(app, rule, method) or
137
- (build_param_schema(params) if method != "GET" and params else None)
134
+ "requestBody": merge_body_with_multipart(
135
+ (
136
+ extract_flask_schema(handler_fn, method) or
137
+ extract_restx_resource_schema(app, rule, method) or
138
+ (build_param_schema(params) if method != "GET" and params else None)
139
+ ),
140
+ live_multipart(_resolve_view_handler(handler_fn, method), method),
138
141
  ),
139
142
  "responseBody": extract_static_response_from_callable(_resolve_view_handler(handler_fn, method)),
140
143
  "detectedBy": "static-scan",
@@ -214,6 +217,7 @@ def extract_drf_schema(callback, method):
214
217
  serializer = serializer_class()
215
218
  properties = {}
216
219
  required = []
220
+ has_file = False
217
221
 
218
222
  for field_name, field in serializer.fields.items():
219
223
  # Skip read-only fields — they don't go in request body
@@ -226,6 +230,10 @@ def extract_drf_schema(callback, method):
226
230
  "type": field_type,
227
231
  "description": field_name.replace("_", " ").title(),
228
232
  }
233
+ # File/image serializer fields are uploads, so mark them as binary
234
+ if any(c.__name__ in ("FileField", "ImageField") for c in type(field).__mro__):
235
+ properties[field_name]["format"] = "binary"
236
+ has_file = True
229
237
 
230
238
  # A field is required if it's not optional and has no default
231
239
  from rest_framework.fields import empty
@@ -243,6 +251,8 @@ def extract_drf_schema(callback, method):
243
251
  result = {"type": "object", "properties": properties}
244
252
  if required:
245
253
  result["required"] = required
254
+ if has_file:
255
+ result["x-content-type"] = "multipart/form-data"
246
256
 
247
257
  return result
248
258
 
@@ -628,7 +638,10 @@ def _walk_django_patterns(patterns, prefix, endpoints, seen):
628
638
  "method": method,
629
639
  "path": path,
630
640
  "description": generate_description(method, path, handler_name),
631
- "requestBody": extract_drf_schema(pattern.callback, method) or (build_param_schema(params) if method != "GET" and params else None),
641
+ "requestBody": merge_body_with_multipart(
642
+ extract_drf_schema(pattern.callback, method) or (build_param_schema(params) if method != "GET" and params else None),
643
+ live_multipart(_resolve_view_handler(pattern.callback, method), method),
644
+ ),
632
645
  "responseBody": extract_static_response_from_callable(_resolve_view_handler(pattern.callback, method)),
633
646
  "detectedBy": "static-scan",
634
647
  })
@@ -982,7 +995,7 @@ def scan_starlette_routes(app):
982
995
  "method": method,
983
996
  "path": normalized_path,
984
997
  "description": generate_description(method, normalized_path, handler_name),
985
- "requestBody": None,
998
+ "requestBody": live_multipart(_resolve_view_handler(getattr(route, "endpoint", None), method), method),
986
999
  "responseBody": extract_static_response_from_callable(_resolve_view_handler(getattr(route, "endpoint", None), method)),
987
1000
  "detectedBy": "static-scan",
988
1001
  })
@@ -1038,7 +1051,7 @@ def scan_sanic_routes(app):
1038
1051
  "method": method,
1039
1052
  "path": normalized_path,
1040
1053
  "description": generate_description(method, normalized_path, handler_name),
1041
- "requestBody": None,
1054
+ "requestBody": live_multipart(_resolve_view_handler(handler, method), method),
1042
1055
  "responseBody": extract_static_response_from_callable(_resolve_view_handler(handler, method)),
1043
1056
  "detectedBy": "static-scan",
1044
1057
  })
@@ -1086,7 +1099,7 @@ def scan_falcon_routes(app):
1086
1099
  "method": method,
1087
1100
  "path": normalized,
1088
1101
  "description": generate_description(method, normalized, None),
1089
- "requestBody": None,
1102
+ "requestBody": live_multipart(getattr(resource, f"on_{method.lower()}", None), method),
1090
1103
  "responseBody": extract_static_response_from_callable(getattr(resource, f"on_{method.lower()}", None)),
1091
1104
  "detectedBy": "static-scan",
1092
1105
  })
@@ -1140,7 +1153,7 @@ def scan_bottle_routes(app):
1140
1153
  "method": method,
1141
1154
  "path": normalized_path,
1142
1155
  "description": generate_description(method, normalized_path, handler_name),
1143
- "requestBody": None,
1156
+ "requestBody": live_multipart(route.callback, method),
1144
1157
  "responseBody": extract_static_response_from_callable(route.callback),
1145
1158
  "detectedBy": "static-scan",
1146
1159
  })
@@ -1183,7 +1196,7 @@ def scan_aiohttp_routes(app):
1183
1196
  "method": method,
1184
1197
  "path": normalized_path,
1185
1198
  "description": generate_description(method, normalized_path, handler_name),
1186
- "requestBody": None,
1199
+ "requestBody": live_multipart(_resolve_view_handler(handler, method), method),
1187
1200
  "responseBody": extract_static_response_from_callable(_resolve_view_handler(handler, method)),
1188
1201
  "detectedBy": "static-scan",
1189
1202
  })
@@ -1245,7 +1258,7 @@ def scan_tornado_routes(app):
1245
1258
  "method": method,
1246
1259
  "path": path,
1247
1260
  "description": generate_description(method, path, handler_class.__name__),
1248
- "requestBody": None,
1261
+ "requestBody": live_multipart(getattr(handler_class, method_name, None), method),
1249
1262
  "responseBody": extract_static_response_from_callable(getattr(handler_class, method_name, None)),
1250
1263
  "detectedBy": "static-scan",
1251
1264
  })
@@ -1314,7 +1327,7 @@ def scan_pyramid_routes(app):
1314
1327
  "method": method,
1315
1328
  "path": normalized_path,
1316
1329
  "description": generate_description(method, normalized_path, route_name),
1317
- "requestBody": None,
1330
+ "requestBody": live_multipart(_resolve_view_handler(view_callable, method), method),
1318
1331
  "responseBody": extract_static_response_from_callable(_resolve_view_handler(view_callable, method)),
1319
1332
  "detectedBy": "static-scan",
1320
1333
  })
@@ -1341,8 +1354,9 @@ def scan_cherrypy_routes(app):
1341
1354
  def walk_cherrypy_tree(obj, prefix=""):
1342
1355
  # Check if this object has exposed methods (HTTP handlers)
1343
1356
  for method_name in [m.lower() for m in HTTP_METHODS]:
1344
- fn = getattr(obj, method_name, None)
1345
- if fn and getattr(fn, "exposed", False):
1357
+ # MethodDispatcher resources name handlers in capitals (GET, POST) and expose the whole class
1358
+ fn = getattr(obj, method_name, None) or getattr(obj, method_name.upper(), None)
1359
+ if fn and (getattr(fn, "exposed", False) or getattr(obj, "exposed", False)):
1346
1360
  method = method_name.upper()
1347
1361
  path = prefix or "/"
1348
1362
  key = f"{method}:{path}"
@@ -1352,7 +1366,7 @@ def scan_cherrypy_routes(app):
1352
1366
  "method": method,
1353
1367
  "path": path,
1354
1368
  "description": generate_description(method, path, fn.__name__),
1355
- "requestBody": None,
1369
+ "requestBody": cherrypy_multipart(fn, method),
1356
1370
  "responseBody": extract_static_response_from_callable(fn),
1357
1371
  "detectedBy": "static-scan",
1358
1372
  })
@@ -1382,6 +1396,28 @@ def scan_cherrypy_routes(app):
1382
1396
  child = getattr(obj, attr_name, None)
1383
1397
  if child is None:
1384
1398
  continue
1399
+ # Ordinary exposed methods (e.g. def upload(self, ...)) are reachable by name with any HTTP method
1400
+ if (
1401
+ (inspect.ismethod(child) or inspect.isfunction(child))
1402
+ and getattr(child, "exposed", False)
1403
+ and attr_name.lower() not in ("index", "default", "favicon_ico") + tuple(m.lower() for m in HTTP_METHODS)
1404
+ ):
1405
+ child_path = prefix + "/" + attr_name
1406
+ upload = cherrypy_multipart(child, "POST")
1407
+ for named_method in (["POST"] if upload else ["GET", "POST"]):
1408
+ key = f"{named_method}:{child_path}"
1409
+ if key in seen:
1410
+ continue
1411
+ seen.add(key)
1412
+ endpoints.append({
1413
+ "method": named_method,
1414
+ "path": child_path,
1415
+ "description": generate_description(named_method, child_path, attr_name),
1416
+ "requestBody": upload if named_method == "POST" else None,
1417
+ "responseBody": extract_static_response_from_callable(child),
1418
+ "detectedBy": "static-scan",
1419
+ })
1420
+ continue
1385
1421
  child_id = id(child)
1386
1422
  if child_id in visited:
1387
1423
  continue
@@ -1491,7 +1527,7 @@ def _scan_decorator_style_static(cwd):
1491
1527
  "method": method,
1492
1528
  "path": normalized,
1493
1529
  "description": generate_description(method, normalized, None),
1494
- "requestBody": body_fields,
1530
+ "requestBody": merge_body_with_multipart(body_fields, extract_multipart_static_at(tree, content, match.start(), method)),
1495
1531
  "responseBody": extract_static_response_at(tree, content, match.start()),
1496
1532
  "detectedBy": "static-scan-file",
1497
1533
  })
@@ -1588,7 +1624,7 @@ def _scan_flask_static(cwd):
1588
1624
  "method": method,
1589
1625
  "path": normalized,
1590
1626
  "description": generate_description(method, normalized, None),
1591
- "requestBody": body_fields,
1627
+ "requestBody": merge_body_with_multipart(body_fields, extract_multipart_static_at(tree, content, start_match.start(), method)),
1592
1628
  "responseBody": extract_static_response_at(tree, content, start_match.start(), method),
1593
1629
  "detectedBy": "static-scan-file",
1594
1630
  })
@@ -1737,7 +1773,7 @@ def _scan_bottle_static(cwd):
1737
1773
  "method": method,
1738
1774
  "path": normalized,
1739
1775
  "description": generate_description(method, normalized, None),
1740
- "requestBody": body_fields,
1776
+ "requestBody": merge_body_with_multipart(body_fields, extract_multipart_static_at(tree, content, match.start(), method)),
1741
1777
  "responseBody": extract_static_response_at(tree, content, match.start()),
1742
1778
  "detectedBy": "static-scan-file",
1743
1779
  })
@@ -1770,7 +1806,7 @@ def _scan_bottle_static(cwd):
1770
1806
  "method": method,
1771
1807
  "path": normalized,
1772
1808
  "description": generate_description(method, normalized, None),
1773
- "requestBody": body_fields,
1809
+ "requestBody": merge_body_with_multipart(body_fields, extract_multipart_static_at(tree, content, start_match.start(), method)),
1774
1810
  "responseBody": extract_static_response_at(tree, content, start_match.start()),
1775
1811
  "detectedBy": "static-scan-file",
1776
1812
  })
@@ -2313,5 +2349,223 @@ def extract_fastapi_response_schema(route):
2313
2349
  return None
2314
2350
  simplified["_source"] = "static"
2315
2351
  return simplified
2352
+ except Exception:
2353
+ return None
2354
+
2355
+
2356
+
2357
+ # ── Multipart / file-upload detection (mirrors JS extractMultipartFieldsFromFile) ──
2358
+ _MULTIPART_METHODS = ("POST", "PUT", "PATCH")
2359
+ _MP_KEY = r"""['"]([A-Za-z_][\w.\-]*)['"]"""
2360
+
2361
+
2362
+ def build_multipart_schema(fields):
2363
+ # Needs at least one real file field, so plain urlencoded form routes are left alone
2364
+ if not any(kind in ("file", "files") for kind in fields.values()):
2365
+ return None
2366
+ properties = {}
2367
+ for name, kind in fields.items():
2368
+ if kind == "files":
2369
+ properties[name] = {"type": "array", "items": {"type": "string", "format": "binary"}}
2370
+ elif kind == "file":
2371
+ properties[name] = {"type": "string", "format": "binary"}
2372
+ else:
2373
+ properties[name] = {"type": "string"}
2374
+ return {"type": "object", "properties": properties, "x-content-type": "multipart/form-data"}
2375
+
2376
+
2377
+ def merge_body_with_multipart(body_fields, multipart_fields):
2378
+ if not multipart_fields:
2379
+ return body_fields
2380
+ if not body_fields:
2381
+ return multipart_fields
2382
+ merged = {
2383
+ "type": "object",
2384
+ "properties": {**body_fields.get("properties", {}), **multipart_fields["properties"]},
2385
+ "x-content-type": "multipart/form-data",
2386
+ }
2387
+ if body_fields.get("required"):
2388
+ merged["required"] = body_fields["required"]
2389
+ return merged
2390
+
2391
+
2392
+ def _multipart_fields_from_source(src):
2393
+ text = str(src or "")
2394
+ fields = {}
2395
+
2396
+ def add(name, kind):
2397
+ # file kinds win over plain text; "files" (several files under one name) wins over a single "file"
2398
+ current = fields.get(name)
2399
+ if current == "files" or (current == "file" and kind != "files"):
2400
+ return
2401
+ fields[name] = kind
2402
+
2403
+ # request.files["x"] / .get("x") / .getlist("x") (Flask, Sanic, Bottle, Tornado) and request.FILES (Django)
2404
+ for m in re.finditer(r"request\.(?:files|FILES)\s*(\[\s*|\.get\(\s*|\.getlist\(\s*)" + _MP_KEY, text):
2405
+ add(m.group(2), "files" if "getlist" in m.group(1) else "file")
2406
+ # Bottle also allows attribute style: request.files.upload
2407
+ for m in re.finditer(r"request\.files\.(?!(?:get|getlist|getall|keys|values|items|dict|copy|pop)\b)([A-Za-z_]\w*)", text):
2408
+ add(m.group(1), "file")
2409
+ # text fields sent next to the files
2410
+ for m in re.finditer(r"(?:request|req)\.(?:form|forms|POST)\s*(?:\[\s*|\.(?:get|getlist|getunicode)\(\s*)" + _MP_KEY, text):
2411
+ add(m.group(1), "string")
2412
+ for m in re.finditer(r"get_(?:body_)?argument\(\s*" + _MP_KEY, text):
2413
+ add(m.group(1), "string")
2414
+
2415
+ # form = await request.form() / request.post(), then form["x"] (FastAPI, Starlette, aiohttp); request.POST (Pyramid)
2416
+ containers = [re.escape(v) for v in re.findall(r"(\w+)\s*=\s*(?:await\s+)?[\w.]+\.(?:form\s*\([^)]*\)|post\s*\(\s*\))", text)]
2417
+ containers += [re.escape(v) for v in re.findall(r"async\s+with\s+[\w.]+\.form\s*\([^)]*\)\s*as\s+(\w+)", text)]
2418
+ containers.append(r"request\.POST")
2419
+ containers.append(r"request\.data") # Django REST Framework: files and fields both arrive in request.data
2420
+ for c in containers:
2421
+ for m in re.finditer(r"(?:(\w+)\s*=\s*)?\b" + c + r"\s*(?:\[\s*|\.(?:get|getlist)\(\s*)" + _MP_KEY, text):
2422
+ var, name = m.group(1), m.group(2)
2423
+ tail = text[m.end(): m.end() + 60]
2424
+ filelike = bool(re.match(r"\s*[\])]?\s*\.(?:filename|file|read|content_type|headers|name|size|chunks)\b", tail))
2425
+ if not filelike and var:
2426
+ v = re.escape(var)
2427
+ filelike = bool(
2428
+ re.search(r"\b" + v + r"\s*\.(?:filename|file|read|content_type|name|size|chunks)\b", text)
2429
+ or re.search(r"isinstance\(\s*" + v + r"\s*,[^)]*File", text)
2430
+ )
2431
+ kind = "file" if filelike else "string"
2432
+ # form.getlist("files") returns several uploads: a loop over it that touches file features marks a list
2433
+ if not filelike and var and ".getlist" in m.group(0):
2434
+ loop = re.search(r"for\s+(\w+)\s+in\s+" + re.escape(var) + r"\b", text)
2435
+ if loop and re.search(r"\b" + re.escape(loop.group(1)) + r"\s*\.(?:filename|file|read|content_type|name|size|chunks)\b", text):
2436
+ kind = "files"
2437
+ add(name, kind)
2438
+
2439
+ # streamed multipart readers (aiohttp .multipart(), Falcon get_media()): part.name == "x"
2440
+ if re.search(r"\.multipart\s*\(|get_media\s*\(", text):
2441
+ for m in re.finditer(r"\.name\s*==?\s*" + _MP_KEY, text):
2442
+ # a part is a file only if the code that handles it (up to the next name check) uses file features
2443
+ window = text[m.end(): m.end() + 300]
2444
+ nxt = re.search(r"\.name\s*==?", window)
2445
+ if nxt:
2446
+ window = window[:nxt.start()]
2447
+ is_file = re.search(r"\.(?:filename|stream|file)\b|read_chunk", window)
2448
+ add(m.group(1), "file" if is_file else "string")
2449
+
2450
+ return fields
2451
+
2452
+
2453
+ def extract_multipart_fields_from_source(src):
2454
+ try:
2455
+ return build_multipart_schema(_multipart_fields_from_source(src))
2456
+ except Exception:
2457
+ return None
2458
+
2459
+
2460
+ def live_multipart(handler, method):
2461
+ # For live app scans: reads a handler's source for upload fields (body methods only)
2462
+ try:
2463
+ if method not in _MULTIPART_METHODS:
2464
+ return None
2465
+ if isinstance(handler, _ScopedHandler):
2466
+ handler = handler.fn
2467
+ if handler is None:
2468
+ return None
2469
+ handler = inspect.unwrap(handler)
2470
+ return extract_multipart_fields_from_source(textwrap.dedent(inspect.getsource(handler)))
2471
+ except Exception:
2472
+ return None
2473
+
2474
+
2475
+ def cherrypy_multipart(fn, method):
2476
+ # CherryPy hands uploads to the handler as parameters (an object with .file / .filename)
2477
+ try:
2478
+ if method not in _MULTIPART_METHODS or fn is None:
2479
+ return None
2480
+ fn = inspect.unwrap(fn)
2481
+ src = textwrap.dedent(inspect.getsource(fn))
2482
+ fields = {}
2483
+ for name, param in inspect.signature(fn).parameters.items():
2484
+ if name == "self" or param.kind in (param.VAR_POSITIONAL, param.VAR_KEYWORD):
2485
+ continue
2486
+ n = re.escape(name)
2487
+ features = r"\s*\.\s*(?:file|filename|content_type|fullvalue|read)\b"
2488
+ loop = re.search(r"for\s+(\w+)\s+in\s+" + n + r"\b", src)
2489
+ if loop and re.search(r"\b" + re.escape(loop.group(1)) + features, src):
2490
+ fields[name] = "files" # several uploads under one name
2491
+ elif re.search(r"\b" + n + features, src):
2492
+ fields[name] = "file"
2493
+ elif param.default is not param.empty:
2494
+ fields[name] = "string" # form fields usually have defaults; URL-path parts usually do not
2495
+ return build_multipart_schema(fields)
2496
+ except Exception:
2497
+ return None
2498
+
2499
+
2500
+ def extract_fastapi_multipart_schema(route, method):
2501
+ # FastAPI declares uploads in the function signature: UploadFile / File() / Form()
2502
+ if method not in _MULTIPART_METHODS:
2503
+ return None
2504
+ try:
2505
+ fn = getattr(route, "endpoint", None)
2506
+ if fn is None:
2507
+ return None
2508
+ try:
2509
+ hints = typing.get_type_hints(fn, include_extras=True)
2510
+ except Exception:
2511
+ hints = {}
2512
+ fields = {}
2513
+ for name, param in inspect.signature(fn).parameters.items():
2514
+ ann = hints.get(name, param.annotation)
2515
+ meta = [type(x).__name__ for x in getattr(ann, "__metadata__", ())]
2516
+ default_kind = type(param.default).__name__
2517
+ if "UploadFile" in str(ann) or "File" in meta or default_kind == "File":
2518
+ # List[UploadFile] / list[bytes] = File(...) accept several files under one field name
2519
+ is_list = re.search(r"\b(?:list|List|Sequence|set|Set|tuple|Tuple)\[", str(ann))
2520
+ fields[name] = "files" if is_list else "file"
2521
+ elif "Form" in meta or default_kind == "Form":
2522
+ fields[name] = "string"
2523
+ return build_multipart_schema(fields) or live_multipart(fn, method)
2524
+ except Exception:
2525
+ return None
2526
+
2527
+
2528
+ def _signature_multipart_fields(fn_node, content):
2529
+ # Same as the FastAPI check above, but read from source text (no running app needed)
2530
+ fields = {}
2531
+ try:
2532
+ args = fn_node.args
2533
+ positional = list(args.posonlyargs) + list(args.args)
2534
+ padded = [None] * (len(positional) - len(args.defaults)) + list(args.defaults)
2535
+ pairs = list(zip(positional, padded)) + list(zip(args.kwonlyargs, args.kw_defaults))
2536
+ for arg, default in pairs:
2537
+ text = " ".join(
2538
+ (ast.get_source_segment(content, n) or "") for n in (arg.annotation, default) if n is not None
2539
+ )
2540
+ if "UploadFile" in text or re.search(r"\bFile\s*\(", text):
2541
+ fields[arg.arg] = "file"
2542
+ elif re.search(r"\bForm\s*\(", text):
2543
+ fields[arg.arg] = "string"
2544
+ except Exception:
2545
+ pass
2546
+ return fields
2547
+
2548
+
2549
+ def extract_multipart_static_at(tree, content, char_index, method=None):
2550
+ # For file scans: reads upload fields from the one function that owns this route
2551
+ try:
2552
+ if tree is None or (method and method not in _MULTIPART_METHODS):
2553
+ return None
2554
+ line = content.count("\n", 0, char_index) + 1
2555
+ owner = None
2556
+ for node in ast.walk(tree):
2557
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
2558
+ start = min([d.lineno for d in node.decorator_list] or [node.lineno])
2559
+ end = getattr(node, "end_lineno", None)
2560
+ if end and start <= line <= end and (owner is None or start >= owner[0]):
2561
+ owner = (start, node)
2562
+ if owner is None:
2563
+ return None
2564
+ node = owner[1]
2565
+ fields = _multipart_fields_from_source(ast.get_source_segment(content, node) or "")
2566
+ for name, kind in _signature_multipart_fields(node, content).items():
2567
+ if fields.get(name) != "file":
2568
+ fields[name] = kind
2569
+ return build_multipart_schema(fields)
2316
2570
  except Exception:
2317
2571
  return None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: botversion-sdk
3
- Version: 2.2.2
3
+ Version: 2.2.3
4
4
  Summary: BotVersion SDK — automatically discover and register your API endpoints
5
5
  Home-page: https://github.com/botversion/botversion-sdk-python
6
6
  Author: BotVersion
@@ -0,0 +1,11 @@
1
+ botversion_sdk/__init__.py,sha256=sG7a8EgRU8uQXUkGZAtX8P1ZSMM42TW_lwMpKbUwX30,11437
2
+ botversion_sdk/client.py,sha256=jE-8EosiLZA0jQ3YidmnJmVEaABvOtIISHXX0Bbi9Oo,9351
3
+ botversion_sdk/interceptor.py,sha256=MpblkcaTyRWhiMg4M_phww1LoY05jRK0pjZJ7ACEC_M,64369
4
+ botversion_sdk/scanner.py,sha256=nvJ1fwxEg_So6aMVW6VDk3owVeHZE63A5w4AspGf5Nk,103388
5
+ botversion_sdk/bin/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ botversion_sdk/bin/scan_endpoints.py,sha256=pR2NVzlaybigElgyIaV_eXAalEnXvQzarJ_izJVPSik,1959
7
+ botversion_sdk-2.2.3.dist-info/METADATA,sha256=5AH6mx83PgFShR814X18K5lpgE4g_D_R5f9x8V-l1xA,1142
8
+ botversion_sdk-2.2.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ botversion_sdk-2.2.3.dist-info/entry_points.txt,sha256=ISTt6tr_e5NMa2oVDgahjE0vLrjFMdxVRhwnYJY_zdw,85
10
+ botversion_sdk-2.2.3.dist-info/top_level.txt,sha256=EbPd-R4CmXKOF-TSF1O6ctFozM7-R4CjGRpzZQgloic,15
11
+ botversion_sdk-2.2.3.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (84.0.0)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,11 +0,0 @@
1
- botversion_sdk/__init__.py,sha256=sG7a8EgRU8uQXUkGZAtX8P1ZSMM42TW_lwMpKbUwX30,11437
2
- botversion_sdk/client.py,sha256=jE-8EosiLZA0jQ3YidmnJmVEaABvOtIISHXX0Bbi9Oo,9351
3
- botversion_sdk/interceptor.py,sha256=ZHKgS6QVo9TKCUcP9eqiynLDSgBTIu6a6Ye_kt1tQt0,62328
4
- botversion_sdk/scanner.py,sha256=mpr9T9Dfi86e3lxLylGk2_PpUh8KnjZaM29dtgztDLI,89864
5
- botversion_sdk/bin/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
- botversion_sdk/bin/scan_endpoints.py,sha256=pR2NVzlaybigElgyIaV_eXAalEnXvQzarJ_izJVPSik,1959
7
- botversion_sdk-2.2.2.dist-info/METADATA,sha256=SNz3pxhGTUMuC2kdWPrkBhMCKIJ4oyBQAqZWPaOY79U,1142
8
- botversion_sdk-2.2.2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
9
- botversion_sdk-2.2.2.dist-info/entry_points.txt,sha256=ISTt6tr_e5NMa2oVDgahjE0vLrjFMdxVRhwnYJY_zdw,85
10
- botversion_sdk-2.2.2.dist-info/top_level.txt,sha256=EbPd-R4CmXKOF-TSF1O6ctFozM7-R4CjGRpzZQgloic,15
11
- botversion_sdk-2.2.2.dist-info/RECORD,,