-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgql_hound.py
More file actions
1454 lines (1242 loc) · 47 KB
/
Copy pathgql_hound.py
File metadata and controls
1454 lines (1242 loc) · 47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
GQL Hound - BurpSuite Extension
Passively discovers, catalogs, and enables fuzzing of GraphQL
operations observed in proxy traffic. Tracks variable shapes,
stores original requests, and integrates with Intruder and Repeater.
Batched mutations are highlighted in orange.
"""
from burp import IBurpExtender, IHttpListener, ITab
from burp import IHttpRequestResponse, IHttpService
from javax.swing import (
JPanel, JScrollPane, JTable, JLabel, JButton,
JSplitPane, BorderFactory, Box, ListSelectionModel,
JPopupMenu, JMenuItem, JMenu, SwingUtilities,
JFileChooser, JComboBox, DefaultCellEditor
)
from javax.swing.filechooser import FileNameExtensionFilter
from javax.swing.event import ListSelectionListener
from javax.swing.table import AbstractTableModel, TableRowSorter
from java.awt import BorderLayout, FlowLayout, Font
from java.awt.event import MouseAdapter
from java.lang import Integer, String
from java.util import ArrayList
from java.io import File as JavaFile
from jarray import array as jarray
from collections import OrderedDict
import json
import re
import base64
from threading import Lock
# ==================================================================
# Lightweight wrappers for imported/stored request data
# ==================================================================
class StoredHttpService(IHttpService):
"""Minimal IHttpService for deserialized requests."""
def __init__(self, host, port, protocol):
self._host = host
self._port = port
self._protocol = protocol
def getHost(self):
return self._host
def getPort(self):
return self._port
def getProtocol(self):
return self._protocol
class StoredRequestResponse(IHttpRequestResponse):
"""Minimal IHttpRequestResponse for deserialized requests."""
def __init__(self, request_bytes, service):
self._request = request_bytes
self._service = service
def getRequest(self):
return self._request
def getResponse(self):
return None
def getComment(self):
return None
def getHighlight(self):
return None
def getHttpService(self):
return self._service
def setRequest(self, message):
self._request = message
def setResponse(self, message):
pass
def setComment(self, comment):
pass
def setHighlight(self, color):
pass
def setHttpService(self, service):
self._service = service
# ==================================================================
# Position-tracking JSON serializer
# ==================================================================
class JsonWriter(object):
"""
Serializes a Python object to JSON while recording byte offsets
of variable values so they can be marked as Intruder positions.
"""
def __init__(self, mark_paths=None):
"""
Args:
mark_paths: set of variable paths to track (e.g. {"input.name"}).
None means track ALL leaf values under "variables".
"""
self._mark = mark_paths
self._parts = []
self._pos = 0
self.positions = {} # var_path -> (start, end)
def result(self):
return "".join(self._parts)
def _write(self, s):
self._parts.append(s)
self._pos += len(s)
def serialize(self, obj, path=""):
if isinstance(obj, dict):
self._write("{")
first = True
for key in obj:
if not first:
self._write(", ")
first = False
self._write(json.dumps(key))
self._write(": ")
child = "%s.%s" % (path, key) if path else key
self.serialize(obj[key], child)
self._write("}")
elif isinstance(obj, list):
self._write("[")
for i, item in enumerate(obj):
if i > 0:
self._write(", ")
child = "%s[%d]" % (path, i)
self.serialize(item, child)
self._write("]")
else:
# Leaf value -- check if we should mark it
var_path = None
if path.startswith("variables."):
var_path = path[len("variables."):]
should_mark = False
if var_path is not None:
if self._mark is None:
should_mark = True
elif var_path in self._mark:
should_mark = True
val_str = json.dumps(obj)
# Detect string values by their JSON representation
is_str = val_str.startswith('"') and val_str.endswith('"')
if should_mark and is_str and len(val_str) > 2:
# Mark inside quotes so Intruder replaces the value,
# not the surrounding quotes (keeps JSON valid)
self._write('"')
start = self._pos
self._write(val_str[1:-1]) # escaped content
end = self._pos
self._write('"')
self.positions[var_path] = (start, end)
elif should_mark:
start = self._pos
self._write(val_str)
end = self._pos
self.positions[var_path] = (start, end)
else:
self._write(val_str)
# ==================================================================
# Upper table model: unique operations
# ==================================================================
class OperationTableModel(AbstractTableModel):
COLUMNS = [
"#", "Operation Name", "Type", "Status",
"Count", "Var Shapes", "Last Host",
]
STATUSES = ["New", "In Progress", "Postponed", "Done", "Ignored"]
def __init__(self):
self._lock = Lock()
# (name, op_type, status, count, shape_count, host)
self._rows = []
self._op_index = {}
def getRowCount(self):
return len(self._rows)
def getColumnCount(self):
return len(self.COLUMNS)
def getColumnName(self, col):
return self.COLUMNS[col]
def getColumnClass(self, col):
if col in (0, 4, 5):
return Integer
return String
def isCellEditable(self, row, col):
return col == 3 # Status column
def setValueAt(self, value, row, col):
if col != 3:
return
if row >= len(self._rows):
return
with self._lock:
name, op_type, _, count, shapes, host = self._rows[row]
self._rows[row] = (name, op_type, value, count, shapes, host)
self.fireTableCellUpdated(row, col)
def getValueAt(self, row, col):
if row >= len(self._rows):
return ""
name, op_type, status, count, shapes, host = self._rows[row]
return [row + 1, name, op_type, status, count, shapes, host][col]
def get_op_name(self, row):
if 0 <= row < len(self._rows):
return self._rows[row][0]
return None
def get_status(self, row):
if 0 <= row < len(self._rows):
return self._rows[row][2]
return "New"
def track(self, op_name, op_type, host, shape_count):
with self._lock:
if op_name in self._op_index:
idx = self._op_index[op_name]
n, t, status, count, _, _ = self._rows[idx]
self._rows[idx] = (
n, t, status, count + 1, shape_count, host
)
self.fireTableRowsUpdated(idx, idx)
return False
else:
idx = len(self._rows)
self._op_index[op_name] = idx
self._rows.append(
(op_name, op_type, "New", 1, shape_count, host)
)
self.fireTableRowsInserted(idx, idx)
return True
def update_shape_count(self, op_name, shape_count):
with self._lock:
if op_name in self._op_index:
idx = self._op_index[op_name]
n, t, status, count, _, host = self._rows[idx]
self._rows[idx] = (n, t, status, count, shape_count, host)
self.fireTableRowsUpdated(idx, idx)
def clear(self):
with self._lock:
count = len(self._rows)
self._rows = []
self._op_index = {}
if count > 0:
self.fireTableRowsDeleted(0, count - 1)
# ==================================================================
# Lower table model: variable paths for selected operation
# ==================================================================
class VariableTableModel(AbstractTableModel):
COLUMNS = ["Variable Path", "Sample Values", "Times Seen"]
def __init__(self):
self._rows = []
def getRowCount(self):
return len(self._rows)
def getColumnCount(self):
return len(self.COLUMNS)
def getColumnName(self, col):
return self.COLUMNS[col]
def getColumnClass(self, col):
if col == 2:
return Integer
return String
def getValueAt(self, row, col):
if row >= len(self._rows):
return ""
return self._rows[row][col]
def get_path(self, row):
if 0 <= row < len(self._rows):
return self._rows[row][0]
return None
def load(self, rows):
self._rows = rows
self.fireTableDataChanged()
# ==================================================================
# Variable store: sample values per operation per path
# ==================================================================
MAX_SAMPLES = 5
class VariableStore(object):
def __init__(self):
self._lock = Lock()
self._data = {}
def record(self, op_name, variables):
if not variables or not isinstance(variables, dict):
return
flat = self._flatten(variables)
with self._lock:
op_store = self._data.setdefault(op_name, {})
for path, value in flat:
entry = op_store.setdefault(
path, {"count": 0, "samples": set()}
)
entry["count"] += 1
if len(entry["samples"]) < MAX_SAMPLES:
entry["samples"].add(self._truncate(value))
def get_rows(self, op_name):
with self._lock:
op_store = self._data.get(op_name, {})
rows = []
for path in sorted(op_store):
e = op_store[path]
samples = " | ".join(sorted(e["samples"]))
rows.append((path, samples, e["count"]))
return rows
def get_all_paths(self, op_name):
with self._lock:
return set(self._data.get(op_name, {}).keys())
def clear(self):
with self._lock:
self._data.clear()
def to_dict(self):
"""Serialize to a JSON-safe dict."""
with self._lock:
out = {}
for op_name, op_store in self._data.items():
out[op_name] = {}
for path, entry in op_store.items():
out[op_name][path] = {
"count": entry["count"],
"samples": sorted(entry["samples"]),
}
return out
def from_dict(self, data):
"""Restore from a deserialized dict."""
with self._lock:
self._data.clear()
for op_name, paths in data.items():
op_store = {}
for path, entry in paths.items():
op_store[path] = {
"count": entry["count"],
"samples": set(entry["samples"]),
}
self._data[op_name] = op_store
@staticmethod
def _flatten(obj, prefix=""):
items = []
if isinstance(obj, dict):
for key, val in obj.items():
p = "%s.%s" % (prefix, key) if prefix else key
if isinstance(val, (dict, list)):
items.extend(VariableStore._flatten(val, p))
else:
items.append((p, val))
elif isinstance(obj, list):
for i, val in enumerate(obj):
p = "%s[%d]" % (prefix, i) if prefix else "[%d]" % i
if isinstance(val, (dict, list)):
items.extend(VariableStore._flatten(val, p))
else:
items.append((p, val))
return items
@staticmethod
def _truncate(value, max_len=60):
s = str(value) if value is not None else "null"
return s[:max_len - 3] + "..." if len(s) > max_len else s
# ==================================================================
# Request store: keeps original messageInfo per (op, var_signature)
# ==================================================================
class RequestStore(object):
"""
Stores the most recent messageInfo for each unique combination of
operation name and variable key signature (frozenset of var paths).
"""
def __init__(self):
self._lock = Lock()
# op_name -> { sig: {"info": messageInfo, "keys": sorted_keys,
# "count": N} }
self._data = {}
def store(self, op_name, variables, messageInfo):
if not variables or not isinstance(variables, dict):
sig = frozenset()
keys = []
else:
flat_keys = [
p for p, _ in VariableStore._flatten(variables)
]
sig = frozenset(flat_keys)
keys = sorted(flat_keys)
with self._lock:
op_store = self._data.setdefault(op_name, OrderedDict())
if sig in op_store:
op_store[sig]["info"] = messageInfo
op_store[sig]["count"] += 1
else:
op_store[sig] = {
"info": messageInfo,
"keys": keys,
"count": 1,
}
def get_shapes(self, op_name):
"""
Return list of dicts describing each variable shape:
[{"sig": frozenset, "keys": [...], "count": N, "info": msgInfo}]
Sorted by number of keys descending (richest shapes first).
"""
with self._lock:
op_store = self._data.get(op_name, {})
shapes = []
for sig, entry in op_store.items():
shapes.append({
"sig": sig,
"keys": entry["keys"],
"count": entry["count"],
"info": entry["info"],
})
shapes.sort(key=lambda s: len(s["keys"]), reverse=True)
return shapes
def shape_count(self, op_name):
with self._lock:
return len(self._data.get(op_name, {}))
def get_best_request_for_paths(self, op_name, paths):
"""
Find the stored request whose variable keys best cover the
requested paths. Returns (messageInfo, covered_paths) or None.
"""
target = set(paths)
with self._lock:
op_store = self._data.get(op_name, {})
best = None
best_overlap = -1
for sig, entry in op_store.items():
overlap = len(target & sig)
if overlap > best_overlap:
best_overlap = overlap
best = entry
if best:
covered = target & frozenset(best["keys"])
return best["info"], covered
return None
def build_merged_request(self, op_name, helpers):
"""
Take the richest stored request and merge in any variable keys
from other shapes, using placeholder values. Returns
(messageInfo_base, merged_variables_dict) or None.
"""
with self._lock:
op_store = self._data.get(op_name, {})
if not op_store:
return None
# Start with the shape that has the most keys
shapes = sorted(
op_store.values(),
key=lambda e: len(e["keys"]),
reverse=True,
)
base = shapes[0]
base_info = base["info"]
# Parse the base request body to get its variables
req = base_info.getRequest()
analyzed = helpers.analyzeRequest(req)
body = helpers.bytesToString(req[analyzed.getBodyOffset():])
try:
data = json.loads(body)
except (ValueError, TypeError):
return None
# If batched array, extract the matching operation
if isinstance(data, list):
target = None
for item in data:
if not isinstance(item, dict):
continue
item_name = item.get("operationName")
if not item_name:
q = item.get("query", "")
m = re.search(
r'(?:query|mutation|subscription)\s+(\w+)', q
)
if m:
item_name = m.group(1)
if item_name == op_name:
target = item
break
if target is None:
return None
data = target
variables = data.get("variables")
if not variables or not isinstance(variables, dict):
variables = OrderedDict()
# Collect all keys from all shapes and add missing ones
all_keys = set()
for entry in shapes:
all_keys.update(entry["keys"])
existing_keys = set(
p for p, _ in VariableStore._flatten(variables)
)
missing = all_keys - existing_keys
for path in sorted(missing):
self._inject_path(variables, path, "FUZZ")
data["variables"] = variables
return base_info, data
@staticmethod
def _inject_path(obj, path, value):
"""Inject a dotted path into a nested dict, creating parents."""
parts = []
remainder = path
while remainder:
m = re.match(r'^([^.\[]+)', remainder)
if m:
parts.append(m.group(1))
remainder = remainder[m.end():]
m2 = re.match(r'^\[(\d+)\]', remainder)
if m2:
parts.append(int(m2.group(1)))
remainder = remainder[m2.end():]
if remainder.startswith("."):
remainder = remainder[1:]
if not m and not m2:
break
current = obj
for i, part in enumerate(parts[:-1]):
next_part = parts[i + 1]
if isinstance(part, int):
while len(current) <= part:
current.append(
OrderedDict() if isinstance(next_part, str)
else []
)
current = current[part]
else:
if part not in current:
current[part] = (
OrderedDict() if isinstance(next_part, str)
else []
)
current = current[part]
last = parts[-1]
if isinstance(last, int):
while len(current) <= last:
current.append(None)
current[last] = value
else:
current[last] = value
def clear(self):
with self._lock:
self._data.clear()
def to_dict(self, helpers):
"""
Serialize to a JSON-safe dict. Request bytes are base64-encoded.
"""
with self._lock:
out = {}
for op_name, op_store in self._data.items():
shapes_list = []
for sig, entry in op_store.items():
info = entry["info"]
service = info.getHttpService()
req_bytes = info.getRequest()
req_b64 = base64.b64encode(
helpers.bytesToString(req_bytes)
)
shapes_list.append({
"keys": entry["keys"],
"count": entry["count"],
"host": service.getHost(),
"port": service.getPort(),
"protocol": service.getProtocol(),
"request_b64": req_b64,
})
out[op_name] = shapes_list
return out
def from_dict(self, data, helpers):
"""
Restore from a deserialized dict. Recreates lightweight
IHttpRequestResponse wrappers for each stored shape.
"""
with self._lock:
self._data.clear()
for op_name, shapes_list in data.items():
op_store = OrderedDict()
for shape in shapes_list:
keys = shape["keys"]
sig = frozenset(keys)
req_str = base64.b64decode(shape["request_b64"])
req_bytes = helpers.stringToBytes(req_str)
service = StoredHttpService(
shape["host"],
shape["port"],
shape["protocol"],
)
info = StoredRequestResponse(req_bytes, service)
op_store[sig] = {
"info": info,
"keys": keys,
"count": shape["count"],
}
self._data[op_name] = op_store
# ==================================================================
# Swing helpers
# ==================================================================
def _shape_label(keys, count):
"""Build a readable submenu label for a variable shape."""
n = len(keys)
if n == 0:
return "no variables (%dx)" % count
preview = keys[:4]
label = ", ".join(preview)
if n > 4:
label += ", ... +%d more" % (n - 4)
return "%d vars: %s (%dx)" % (n, label, count)
# ==================================================================
# Extension entry point
# ==================================================================
class BurpExtender(IBurpExtender, IHttpListener, ITab):
EXTENSION_NAME = "GQL Hound"
def registerExtenderCallbacks(self, callbacks):
self._callbacks = callbacks
self._helpers = callbacks.getHelpers()
callbacks.setExtensionName(self.EXTENSION_NAME)
callbacks.registerHttpListener(self)
self._op_model = OperationTableModel()
self._var_model = VariableTableModel()
self._var_store = VariableStore()
self._req_store = RequestStore()
self._selected_op = None # currently selected operation name
self._build_ui()
callbacks.addSuiteTab(self)
callbacks.printOutput("[+] %s loaded." % self.EXTENSION_NAME)
# -- ITab --------------------------------------------------
def getTabCaption(self):
return self.EXTENSION_NAME
def getUiComponent(self):
return self._panel
# -- UI ----------------------------------------------------
def _build_ui(self):
self._panel = JPanel(BorderLayout(0, 6))
self._panel.setBorder(
BorderFactory.createEmptyBorder(10, 10, 10, 10)
)
# -- Header
header = JPanel(FlowLayout(FlowLayout.LEFT))
title = JLabel("Unique GraphQL Operations")
title.setFont(Font("Dialog", Font.BOLD, 14))
header.add(title)
clear_btn = JButton("Clear", actionPerformed=self._on_clear)
header.add(Box.createHorizontalStrut(12))
header.add(clear_btn)
export_btn = JButton("Export", actionPerformed=self._on_export)
header.add(Box.createHorizontalStrut(8))
header.add(export_btn)
import_btn = JButton("Import", actionPerformed=self._on_import)
header.add(Box.createHorizontalStrut(8))
header.add(import_btn)
self._panel.add(header, BorderLayout.NORTH)
# -- Upper table: operations (sortable)
self._op_table = JTable(self._op_model)
self._op_table.setSelectionMode(
ListSelectionModel.SINGLE_SELECTION
)
self._op_table.setAutoCreateRowSorter(True)
cm = self._op_table.getColumnModel()
cm.getColumn(0).setMaxWidth(50) # #
cm.getColumn(2).setMaxWidth(100) # Type
cm.getColumn(4).setMaxWidth(80) # Count
cm.getColumn(5).setMaxWidth(90) # Var Shapes
# Status dropdown editor
status_combo = JComboBox(OperationTableModel.STATUSES)
cm.getColumn(3).setCellEditor(DefaultCellEditor(status_combo))
cm.getColumn(3).setMaxWidth(110)
op_scroll = JScrollPane(self._op_table)
# Selection listener
self._op_table.getSelectionModel().addListSelectionListener(
_OpSelectionListener(self)
)
# Right-click on operations
self._op_table.addMouseListener(_OpMouseListener(self))
# -- Lower table: variables (sortable)
var_panel = JPanel(BorderLayout(0, 4))
var_label = JLabel("Variables for selected operation:")
var_label.setFont(Font("Dialog", Font.BOLD, 12))
var_panel.add(var_label, BorderLayout.NORTH)
self._var_table = JTable(self._var_model)
self._var_table.setAutoCreateRowSorter(True)
self._var_table.getColumnModel().getColumn(2).setMaxWidth(100)
var_scroll = JScrollPane(self._var_table)
var_panel.add(var_scroll, BorderLayout.CENTER)
# Right-click on variables
self._var_table.addMouseListener(_VarMouseListener(self))
# -- Split pane
split = JSplitPane(
JSplitPane.VERTICAL_SPLIT, op_scroll, var_panel
)
split.setResizeWeight(0.5)
split.setDividerLocation(250)
self._panel.add(split, BorderLayout.CENTER)
def _on_clear(self, event):
self._op_model.clear()
self._var_store.clear()
self._var_model.load([])
self._req_store.clear()
self._selected_op = None
def _on_export(self, event):
"""Export all state to a JSON file."""
chooser = JFileChooser()
chooser.setDialogTitle("Export GQL Hound Data")
chooser.setFileFilter(
FileNameExtensionFilter("JSON files", ["json"])
)
chooser.setSelectedFile(
JavaFile("gql_hound_export.json")
)
result = chooser.showSaveDialog(self._panel)
if result != JFileChooser.APPROVE_OPTION:
return
path = chooser.getSelectedFile().getAbsolutePath()
if not path.endswith(".json"):
path += ".json"
try:
# Serialize operation table rows
ops = []
for row in self._op_model._rows:
name, op_type, status, count, shapes, host = row
ops.append({
"name": name,
"type": op_type,
"status": status,
"count": count,
"host": host,
})
state = {
"version": 1,
"operations": ops,
"variables": self._var_store.to_dict(),
"requests": self._req_store.to_dict(self._helpers),
}
f = open(path, "w")
try:
json.dump(state, f, indent=2)
finally:
f.close()
n_ops = len(ops)
n_shapes = sum(
len(v) for v in state["requests"].values()
)
self._callbacks.printOutput(
"[+] Exported %d operations, %d request shapes to %s"
% (n_ops, n_shapes, path)
)
except Exception as ex:
self._callbacks.printError(
"[!] Export failed: %s" % str(ex)
)
def _on_import(self, event):
"""Import state from a JSON file, merging with existing data."""
chooser = JFileChooser()
chooser.setDialogTitle("Import GQL Hound Data")
chooser.setFileFilter(
FileNameExtensionFilter("JSON files", ["json"])
)
result = chooser.showOpenDialog(self._panel)
if result != JFileChooser.APPROVE_OPTION:
return
path = chooser.getSelectedFile().getAbsolutePath()
try:
f = open(path, "r")
try:
state = json.load(f)
finally:
f.close()
version = state.get("version", 0)
if version != 1:
self._callbacks.printError(
"[!] Unsupported file version: %s" % version
)
return
# Clear current state
self._op_model.clear()
self._var_store.clear()
self._var_model.load([])
self._req_store.clear()
self._selected_op = None
# Restore variable store
self._var_store.from_dict(state.get("variables", {}))
# Restore request store
self._req_store.from_dict(
state.get("requests", {}), self._helpers
)
# Restore operation table
for op in state.get("operations", []):
name = op["name"]
op_type = op["type"]
status = op.get("status", "New")
count = op["count"]
host = op["host"]
sc = self._req_store.shape_count(name)
# Add to model and override count + status
self._op_model.track(name, op_type, host, sc)
idx = self._op_model._op_index.get(name)
if idx is not None:
self._op_model._rows[idx] = (
name, op_type, status, count, sc, host
)
self._op_model.fireTableRowsUpdated(idx, idx)
n_ops = len(state.get("operations", []))
n_shapes = sum(
len(v) for v in state.get("requests", {}).values()
)
self._callbacks.printOutput(
"[+] Imported %d operations, %d request shapes from %s"
% (n_ops, n_shapes, path)
)
except Exception as ex:
self._callbacks.printError(
"[!] Import failed: %s" % str(ex)
)
# -- IHttpListener ------------------------------------------
def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo):
if toolFlag != self._callbacks.TOOL_PROXY:
return
if not messageIsRequest:
return
request = messageInfo.getRequest()
analyzed = self._helpers.analyzeRequest(messageInfo)
body_offset = analyzed.getBodyOffset()
body = self._helpers.bytesToString(
request[body_offset:]
).strip()
if not body:
return
operations = self._extract_operations(body)
if not operations:
return
host = (
analyzed.getUrl().getHost()
if analyzed.getUrl() else "unknown"
)
is_batched = len(operations) > 1
mut_count = sum(1 for _, t, _ in operations if t == "mutation")
has_batched_muts = is_batched and mut_count > 1
existing = messageInfo.getComment() or ""
tags = []
any_new = False
for op_name, op_type, variables in operations:
tag = "GQL:%s" % op_name
if tag not in existing:
tags.append(tag)
# Record variable samples
self._var_store.record(op_name, variables)
# Store original request by variable shape
self._req_store.store(op_name, variables, messageInfo)
sc = self._req_store.shape_count(op_name)
is_new = self._op_model.track(
op_name, op_type, host, sc
)
if not is_new:
self._op_model.update_shape_count(op_name, sc)
if is_new:
any_new = True
self._callbacks.printOutput(
"[*] New %s: %s (%s)" % (op_type, op_name, host)
)
if tags:
new_part = " | ".join(tags)
comment = (
"%s | %s" % (existing, new_part) if existing
else new_part
)
messageInfo.setComment(comment)
if has_batched_muts:
messageInfo.setHighlight("orange")
self._callbacks.printOutput(
"[!] Batched mutations (%d): %s (%s)"
% (
mut_count,
", ".join(
n for n, t, _ in operations
if t == "mutation"
),
host,
)
)
elif any_new:
messageInfo.setHighlight("cyan")