-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph_security_webhook_tester.py
More file actions
1790 lines (1442 loc) · 81.3 KB
/
graph_security_webhook_tester.py
File metadata and controls
1790 lines (1442 loc) · 81.3 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
#!/usr/bin/env python3
"""
Microsoft Graph Security Webhook Tester
A GUI application to test Microsoft Graph change notifications for security-related user actions.
"""
import tkinter as tk
from tkinter import ttk, scrolledtext, messagebox, filedialog
import requests
import json
import logging
import os
from datetime import datetime, timedelta, timezone
import threading
import time
import webbrowser
from typing import Dict, Any, Optional
import urllib.parse
import pygame
from pathlib import Path
# Import delta tracker for detailed change analysis
try:
from enhanced_change_tracker import EnhancedChangeTracker
except ImportError:
print("Warning: enhanced_change_tracker.py not found. Enhanced analysis will be limited.")
EnhancedChangeTracker = None
# Import MSAL for authentication
try:
import msal
except ImportError:
print("MSAL not installed. Please install it with: pip install msal")
exit(1)
class HTTPLogger:
"""Custom logger for HTTP requests and responses"""
def __init__(self, log_file: str = "logs/graph_api_requests.log"):
# Make log file path relative to script directory
if not os.path.isabs(log_file):
script_dir = os.path.dirname(os.path.abspath(__file__))
self.log_file = os.path.join(script_dir, log_file)
else:
self.log_file = log_file
# Create logs directory if it doesn't exist
log_dir = os.path.dirname(self.log_file)
if log_dir and not os.path.exists(log_dir):
os.makedirs(log_dir)
self.logger = logging.getLogger("GraphAPILogger")
self.logger.setLevel(logging.INFO)
# Create file handler
handler = logging.FileHandler(self.log_file, encoding='utf-8')
handler.setLevel(logging.INFO)
# Create formatter
formatter = logging.Formatter(
'%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
handler.setFormatter(formatter)
# Add handler to logger
if not self.logger.handlers:
self.logger.addHandler(handler)
def log_request(self, method: str, url: str, headers: Dict, body: str = None):
"""Log HTTP request"""
self.logger.info(f"=== REQUEST ===")
self.logger.info(f"Method: {method}")
self.logger.info(f"URL: {url}")
self.logger.info(f"Headers: {json.dumps(dict(headers), indent=2)}")
if body:
self.logger.info(f"Body: {body}")
self.logger.info(f"==================")
def log_response(self, status_code: int, headers: Dict, body: str):
"""Log HTTP response"""
self.logger.info(f"=== RESPONSE ===")
self.logger.info(f"Status Code: {status_code}")
self.logger.info(f"Headers: {json.dumps(dict(headers), indent=2)}")
self.logger.info(f"Body: {body}")
self.logger.info(f"===================")
class GraphAuthenticator:
"""Handles Microsoft Graph authentication using MSAL"""
def __init__(self, client_id: str, client_secret: str = None, tenant_id: str = "common"):
self.client_id = client_id
self.client_secret = client_secret
self.tenant_id = tenant_id
self.authority = f"https://login.microsoftonline.com/{tenant_id}"
self.scopes = [
"https://graph.microsoft.com/Mail.Read",
"https://graph.microsoft.com/Calendars.Read",
"https://graph.microsoft.com/Contacts.Read",
"https://graph.microsoft.com/Files.Read.All",
"https://graph.microsoft.com/Sites.Read.All",
"https://graph.microsoft.com/User.Read"
]
self.access_token = None
# Initialize MSAL app
if client_secret:
# Confidential client app
self.app = msal.ConfidentialClientApplication(
client_id=client_id,
client_credential=client_secret,
authority=self.authority
)
else:
# Public client app
self.app = msal.PublicClientApplication(
client_id=client_id,
authority=self.authority
)
def authenticate_interactive(self) -> bool:
"""Authenticate using interactive flow"""
try:
# Interactive authentication only works with PublicClientApplication
if self.client_secret:
raise Exception("Interactive authentication is not supported when using client secret. Please use client credentials flow instead.")
# Ensure we have a PublicClientApplication
if not isinstance(self.app, msal.PublicClientApplication):
self.app = msal.PublicClientApplication(
client_id=self.client_id,
authority=self.authority
)
# Note: Make sure your Azure App Registration has a redirect URI configured:
# - Go to Azure Portal → App registrations → Your app → Authentication
# - Add platform → Mobile and desktop applications
# - Add redirect URI: http://localhost
# - Or use: https://login.microsoftonline.com/common/oauth2/nativeclient
# Try to get token from cache first
accounts = self.app.get_accounts()
if accounts:
result = self.app.acquire_token_silent(self.scopes, account=accounts[0])
if result and "access_token" in result:
self.access_token = result["access_token"]
return True
# Interactive authentication
result = self.app.acquire_token_interactive(
scopes=self.scopes,
prompt="select_account",
parent_window_handle=None # Use default browser
)
if result and "access_token" in result:
self.access_token = result["access_token"]
return True
else:
error = result.get("error", "Unknown error")
error_desc = result.get("error_description", "No description")
raise Exception(f"Authentication failed: {error} - {error_desc}")
except Exception as e:
raise Exception(f"Authentication error: {str(e)}")
def authenticate_client_credentials(self) -> bool:
"""Authenticate using client credentials flow (app-only)"""
if not self.client_secret:
raise Exception("Client secret required for client credentials flow")
try:
result = self.app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
if result and "access_token" in result:
self.access_token = result["access_token"]
return True
else:
error = result.get("error", "Unknown error")
error_desc = result.get("error_description", "No description")
raise Exception(f"Authentication failed: {error} - {error_desc}")
except Exception as e:
raise Exception(f"Authentication error: {str(e)}")
class GraphSubscriptionManager:
"""Manages Microsoft Graph subscriptions"""
def __init__(self, authenticator: GraphAuthenticator, http_logger: HTTPLogger):
self.authenticator = authenticator
self.http_logger = http_logger
self.graph_endpoint = "https://graph.microsoft.com/v1.0"
def create_subscription(self,
resource: str,
change_type: str,
notification_url: str,
expiration_hours: int = 24,
include_security_webhooks: bool = True) -> Dict[str, Any]:
"""Create a Microsoft Graph subscription"""
if not self.authenticator.access_token:
raise Exception("Not authenticated. Please authenticate first.")
# Calculate expiration time (using proper UTC timezone)
expiration = datetime.now(timezone.utc) + timedelta(hours=expiration_hours)
expiration_str = expiration.strftime("%Y-%m-%dT%H:%M:%S.0000000Z")
# Prepare subscription payload
subscription_data = {
"changeType": change_type,
"notificationUrl": notification_url,
"resource": resource,
"expirationDateTime": expiration_str,
"clientState": "webhook-test-" + str(int(time.time()))
}
headers = {
"Authorization": f"Bearer {self.authenticator.access_token}",
"Content-Type": "application/json"
}
# Add security webhooks header if requested
if include_security_webhooks:
headers["Prefer"] = "includesecuritywebhooks"
url = f"{self.graph_endpoint}/subscriptions"
body = json.dumps(subscription_data, indent=2)
# Log the request
self.http_logger.log_request("POST", url, headers, body)
try:
response = requests.post(url, headers=headers, data=body)
# Log the response
response_body = response.text
self.http_logger.log_response(response.status_code, response.headers, response_body)
if response.status_code == 201:
return {
"success": True,
"data": response.json(),
"status_code": response.status_code,
"message": "Subscription created successfully!"
}
else:
error_data = response.json() if response.text else {}
return {
"success": False,
"error": error_data,
"status_code": response.status_code,
"message": f"Failed to create subscription. Status: {response.status_code}"
}
except requests.exceptions.RequestException as e:
return {
"success": False,
"error": str(e),
"status_code": None,
"message": f"Request failed: {str(e)}"
}
except json.JSONDecodeError as e:
return {
"success": False,
"error": str(e),
"status_code": response.status_code,
"message": f"Invalid JSON response: {str(e)}"
}
def list_subscriptions(self) -> Dict[str, Any]:
"""List all current subscriptions"""
if not self.authenticator.access_token:
raise Exception("Not authenticated. Please authenticate first.")
headers = {
"Authorization": f"Bearer {self.authenticator.access_token}",
"Content-Type": "application/json"
}
url = f"{self.graph_endpoint}/subscriptions"
# Log the request
self.http_logger.log_request("GET", url, headers)
try:
response = requests.get(url, headers=headers)
# Log the response
response_body = response.text
self.http_logger.log_response(response.status_code, response.headers, response_body)
if response.status_code == 200:
return {
"success": True,
"data": response.json(),
"status_code": response.status_code,
"message": "Subscriptions retrieved successfully!"
}
else:
error_data = response.json() if response.text else {}
return {
"success": False,
"error": error_data,
"status_code": response.status_code,
"message": f"Failed to retrieve subscriptions. Status: {response.status_code}"
}
except requests.exceptions.RequestException as e:
return {
"success": False,
"error": str(e),
"status_code": None,
"message": f"Request failed: {str(e)}"
}
except json.JSONDecodeError as e:
return {
"success": False,
"error": str(e),
"status_code": response.status_code,
"message": f"Invalid JSON response: {str(e)}"
}
def delete_subscription(self, subscription_id: str) -> Dict[str, Any]:
"""Delete a Microsoft Graph subscription"""
if not self.authenticator.access_token:
raise Exception("Not authenticated. Please authenticate first.")
headers = {
"Authorization": f"Bearer {self.authenticator.access_token}",
"Content-Type": "application/json"
}
url = f"{self.graph_endpoint}/subscriptions/{subscription_id}"
# Log the request
self.http_logger.log_request("DELETE", url, headers)
try:
response = requests.delete(url, headers=headers)
# Log the response
response_body = response.text if response.text else ""
self.http_logger.log_response(response.status_code, response.headers, response_body)
if response.status_code == 204:
return {
"success": True,
"data": None,
"status_code": response.status_code,
"message": "Subscription deleted successfully!"
}
else:
error_data = response.json() if response.text else {}
return {
"success": False,
"error": error_data,
"status_code": response.status_code,
"message": f"Failed to delete subscription. Status: {response.status_code}"
}
except requests.exceptions.RequestException as e:
return {
"success": False,
"error": str(e),
"status_code": None,
"message": f"Request failed: {str(e)}"
}
except json.JSONDecodeError as e:
return {
"success": False,
"error": str(e),
"status_code": response.status_code,
"message": f"Invalid JSON response: {str(e)}"
}
class SoundManager:
"""Manages sound notifications"""
def __init__(self):
pygame.mixer.init()
self.sounds = {}
self._load_default_sounds()
def _load_default_sounds(self):
"""Load default system sounds"""
try:
# Create simple tone sounds using pygame
pass
except Exception as e:
print(f"Could not load sounds: {e}")
def play_success_sound(self):
"""Play success notification sound"""
try:
# Create a simple success tone
import pygame.sndarray
import numpy as np
sample_rate = 22050
duration = 0.5
frequency = 800
frames = int(duration * sample_rate)
arr = np.zeros((frames, 2))
for i in range(frames):
time_val = float(i) / sample_rate
wave = np.sin(frequency * 2 * np.pi * time_val)
arr[i] = [wave, wave]
arr = (arr * 32767).astype(np.int16)
sound = pygame.sndarray.make_sound(arr)
sound.play()
except Exception as e:
# Fallback to system beep
print('\a') # System beep
def play_error_sound(self):
"""Play error notification sound"""
try:
# Create a simple error tone
import pygame.sndarray
import numpy as np
sample_rate = 22050
duration = 0.3
frequency = 400
frames = int(duration * sample_rate)
arr = np.zeros((frames, 2))
for i in range(frames):
time_val = float(i) / sample_rate
wave = np.sin(frequency * 2 * np.pi * time_val)
arr[i] = [wave, wave]
arr = (arr * 32767).astype(np.int16)
sound = pygame.sndarray.make_sound(arr)
sound.play()
except Exception as e:
# Fallback to system beep
print('\a\a') # Double system beep
class GraphWebhookTesterGUI:
"""Main GUI application for testing Microsoft Graph webhooks"""
def __init__(self):
self.root = tk.Tk()
self.root.title("Microsoft Graph Security Webhook Tester")
self.root.geometry("900x700")
# Initialize components
self.http_logger = HTTPLogger()
self.sound_manager = SoundManager()
self.authenticator = None
self.subscription_manager = None
# Create GUI
self._create_gui()
# Load configuration if exists
self._load_config()
def _create_gui(self):
"""Create the GUI interface"""
# Create notebook for tabs
notebook = ttk.Notebook(self.root)
notebook.pack(fill="both", expand=True, padx=10, pady=10)
# Authentication tab
auth_frame = ttk.Frame(notebook)
notebook.add(auth_frame, text="Authentication")
self._create_auth_tab(auth_frame)
# Subscription tab
sub_frame = ttk.Frame(notebook)
notebook.add(sub_frame, text="Create Subscription")
self._create_subscription_tab(sub_frame)
# Monitor tab
monitor_frame = ttk.Frame(notebook)
notebook.add(monitor_frame, text="Monitor Subscriptions")
self._create_monitor_tab(monitor_frame)
# Logs tab
logs_frame = ttk.Frame(notebook)
notebook.add(logs_frame, text="API Logs")
self._create_logs_tab(logs_frame)
# Delta query tab for change details
delta_frame = ttk.Frame(notebook)
notebook.add(delta_frame, text="Change Details")
self._create_delta_tab(delta_frame)
def _create_auth_tab(self, parent):
"""Create authentication tab"""
# Title
title_label = ttk.Label(parent, text="Microsoft Graph Authentication", font=("Arial", 14, "bold"))
title_label.pack(pady=10)
# Configuration frame
config_frame = ttk.LabelFrame(parent, text="App Registration Configuration")
config_frame.pack(fill="x", padx=10, pady=5)
# Client ID
ttk.Label(config_frame, text="Client ID:").grid(row=0, column=0, sticky="w", padx=5, pady=5)
self.client_id_var = tk.StringVar()
client_id_entry = ttk.Entry(config_frame, textvariable=self.client_id_var, width=50)
client_id_entry.grid(row=0, column=1, padx=5, pady=5)
# Client Secret (optional)
ttk.Label(config_frame, text="Client Secret (Optional):").grid(row=1, column=0, sticky="w", padx=5, pady=5)
self.client_secret_var = tk.StringVar()
client_secret_entry = ttk.Entry(config_frame, textvariable=self.client_secret_var, width=50, show="*")
client_secret_entry.grid(row=1, column=1, padx=5, pady=5)
# Tenant ID
ttk.Label(config_frame, text="Tenant ID:").grid(row=2, column=0, sticky="w", padx=5, pady=5)
self.tenant_id_var = tk.StringVar(value="common")
tenant_id_entry = ttk.Entry(config_frame, textvariable=self.tenant_id_var, width=50)
tenant_id_entry.grid(row=2, column=1, padx=5, pady=5)
# Authentication type
auth_type_frame = ttk.LabelFrame(parent, text="Authentication Type")
auth_type_frame.pack(fill="x", padx=10, pady=5)
self.auth_type_var = tk.StringVar(value="interactive")
ttk.Radiobutton(auth_type_frame, text="Interactive (User)", variable=self.auth_type_var, value="interactive").pack(anchor="w", padx=5, pady=2)
ttk.Radiobutton(auth_type_frame, text="App-only (Client Credentials)", variable=self.auth_type_var, value="client_credentials").pack(anchor="w", padx=5, pady=2)
# Buttons frame
buttons_frame = ttk.Frame(parent)
buttons_frame.pack(fill="x", padx=10, pady=10)
ttk.Button(buttons_frame, text="Save Configuration", command=self._save_config).pack(side="left", padx=5)
ttk.Button(buttons_frame, text="Load Configuration", command=self._load_config_dialog).pack(side="left", padx=5)
ttk.Button(buttons_frame, text="Authenticate", command=self._authenticate).pack(side="left", padx=5)
# Status frame
status_frame = ttk.LabelFrame(parent, text="Authentication Status")
status_frame.pack(fill="both", expand=True, padx=10, pady=5)
self.auth_status_text = scrolledtext.ScrolledText(status_frame, height=10, state="disabled")
self.auth_status_text.pack(fill="both", expand=True, padx=5, pady=5)
def _create_subscription_tab(self, parent):
"""Create subscription creation tab"""
# Title
title_label = ttk.Label(parent, text="Create Microsoft Graph Subscription", font=("Arial", 14, "bold"))
title_label.pack(pady=10)
# Subscription configuration
config_frame = ttk.LabelFrame(parent, text="Subscription Configuration")
config_frame.pack(fill="x", padx=10, pady=5)
# Resource
ttk.Label(config_frame, text="Resource:").grid(row=0, column=0, sticky="w", padx=5, pady=5)
resource_frame = ttk.Frame(config_frame)
resource_frame.grid(row=0, column=1, padx=5, pady=5, sticky="w")
self.resource_var = tk.StringVar(value="/me/drive/root")
resource_combo = ttk.Combobox(resource_frame, textvariable=self.resource_var, width=57,
values=[
"/me/drive/root",
"/me/drive/items/{item-id}",
"/sites/{site-id}/drive/root",
"/groups/{group-id}/drive/root",
"/users/{user-id}/drive/root"
])
resource_combo.pack(side="left")
ttk.Button(resource_frame, text="Help", width=6,
command=self._show_resource_help).pack(side="left", padx=(5, 0))
# Change Type
ttk.Label(config_frame, text="Change Type:").grid(row=1, column=0, sticky="w", padx=5, pady=5)
self.change_type_var = tk.StringVar(value="updated")
change_type_combo = ttk.Combobox(config_frame, textvariable=self.change_type_var,
values=["updated", "deleted", "updated,deleted"])
change_type_combo.grid(row=1, column=1, padx=5, pady=5, sticky="w")
# Notification URL
ttk.Label(config_frame, text="Notification URL:").grid(row=2, column=0, sticky="w", padx=5, pady=5)
notification_frame = ttk.Frame(config_frame)
notification_frame.grid(row=2, column=1, padx=5, pady=5, sticky="w")
self.notification_url_var = tk.StringVar(value="https://webhook.site/unique-id")
notification_url_combo = ttk.Combobox(notification_frame, textvariable=self.notification_url_var, width=57,
values=[
"http://localhost:8000",
"https://webhook.site/unique-id",
"https://your-app.azurewebsites.net/webhook",
"https://your-domain.com/webhook"
])
notification_url_combo.pack(side="left")
ttk.Button(notification_frame, text="Help", width=6,
command=self._show_webhook_help).pack(side="left", padx=(5, 0))
# Expiration hours
ttk.Label(config_frame, text="Expiration (hours):").grid(row=3, column=0, sticky="w", padx=5, pady=5)
self.expiration_var = tk.StringVar(value="24")
expiration_entry = ttk.Entry(config_frame, textvariable=self.expiration_var, width=10)
expiration_entry.grid(row=3, column=1, padx=5, pady=5, sticky="w")
# Security webhooks option
security_frame = ttk.LabelFrame(parent, text="Security Options")
security_frame.pack(fill="x", padx=10, pady=5)
self.include_security_var = tk.BooleanVar(value=True)
ttk.Checkbutton(security_frame, text="Include Security Webhooks (Prefer: includesecuritywebhooks)",
variable=self.include_security_var).pack(anchor="w", padx=5, pady=5)
# Configuration management buttons
config_buttons_frame = ttk.Frame(parent)
config_buttons_frame.pack(fill="x", padx=10, pady=5)
ttk.Button(config_buttons_frame, text="Load Defaults", command=self._load_defaults).pack(side="left", padx=5)
ttk.Button(config_buttons_frame, text="Save as Defaults", command=self._save_as_defaults).pack(side="left", padx=5)
ttk.Button(config_buttons_frame, text="Reset Fields", command=self._reset_subscription_fields).pack(side="left", padx=5)
# Create button
create_button = ttk.Button(parent, text="Create Subscription", command=self._create_subscription)
create_button.pack(pady=10)
# Response frame
response_frame = ttk.LabelFrame(parent, text="Response")
response_frame.pack(fill="both", expand=True, padx=10, pady=5)
self.response_text = scrolledtext.ScrolledText(response_frame, height=15, state="disabled")
self.response_text.pack(fill="both", expand=True, padx=5, pady=5)
def _create_monitor_tab(self, parent):
"""Create subscription monitoring tab"""
# Title
title_label = ttk.Label(parent, text="Monitor Active Subscriptions", font=("Arial", 14, "bold"))
title_label.pack(pady=10)
# Buttons
buttons_frame = ttk.Frame(parent)
buttons_frame.pack(fill="x", padx=10, pady=5)
ttk.Button(buttons_frame, text="Refresh Subscriptions", command=self._refresh_subscriptions).pack(side="left", padx=5)
ttk.Button(buttons_frame, text="Delete Selected", command=self._delete_selected_subscription).pack(side="left", padx=5)
ttk.Button(buttons_frame, text="Delete All", command=self._delete_all_subscriptions).pack(side="left", padx=5)
ttk.Button(buttons_frame, text="Open Log File", command=self._open_log_file).pack(side="left", padx=5)
# Subscription selection frame
selection_frame = ttk.LabelFrame(parent, text="Subscription Selection")
selection_frame.pack(fill="x", padx=10, pady=5)
# Subscription dropdown
subscription_select_frame = ttk.Frame(selection_frame)
subscription_select_frame.pack(fill="x", padx=5, pady=5)
ttk.Label(subscription_select_frame, text="Select Subscription:").pack(side="left", padx=(0, 5))
self.subscription_id_var = tk.StringVar()
self.subscription_combo = ttk.Combobox(subscription_select_frame, textvariable=self.subscription_id_var, width=50, state="readonly")
self.subscription_combo.pack(side="left", padx=5)
ttk.Button(subscription_select_frame, text="Refresh List", command=self._refresh_subscription_dropdown).pack(side="left", padx=5)
# Subscriptions list
list_frame = ttk.LabelFrame(parent, text="Active Subscriptions")
list_frame.pack(fill="both", expand=True, padx=10, pady=5)
self.subscriptions_text = scrolledtext.ScrolledText(list_frame, height=15, state="disabled")
self.subscriptions_text.pack(fill="both", expand=True, padx=5, pady=5)
def _create_logs_tab(self, parent):
"""Create API logs tab"""
# Title
title_label = ttk.Label(parent, text="Microsoft Graph API Request/Response Logs", font=("Arial", 14, "bold"))
title_label.pack(pady=10)
# Buttons
buttons_frame = ttk.Frame(parent)
buttons_frame.pack(fill="x", padx=10, pady=5)
ttk.Button(buttons_frame, text="Refresh Logs", command=self._refresh_logs).pack(side="left", padx=5)
ttk.Button(buttons_frame, text="Clear Logs", command=self._clear_logs).pack(side="left", padx=5)
ttk.Button(buttons_frame, text="Export Logs", command=self._export_logs).pack(side="left", padx=5)
# Logs display
logs_frame = ttk.LabelFrame(parent, text="API Logs")
logs_frame.pack(fill="both", expand=True, padx=10, pady=5)
self.logs_text = scrolledtext.ScrolledText(logs_frame, height=25, state="disabled")
self.logs_text.pack(fill="both", expand=True, padx=5, pady=5)
# Auto-refresh logs
self._refresh_logs()
def _create_delta_tab(self, parent):
"""Create delta query/change details tab"""
# Title
title_label = ttk.Label(parent, text="Detailed Change Analysis", font=("Arial", 14, "bold"))
title_label.pack(pady=10)
# Instructions
instructions = ttk.Label(parent,
text="This tab shows detailed analysis of what specifically changed, obtained via Microsoft Graph Delta Query API.\n"
"When webhook notifications are received, the system automatically queries for detailed changes.",
wraplength=700, justify="left")
instructions.pack(padx=10, pady=5)
# Control buttons
buttons_frame = ttk.Frame(parent)
buttons_frame.pack(fill="x", padx=10, pady=5)
ttk.Button(buttons_frame, text="Analyze Latest Webhook", command=self._analyze_latest_webhook).pack(side="left", padx=5)
ttk.Button(buttons_frame, text="Refresh Changes", command=self._refresh_changes).pack(side="left", padx=5)
ttk.Button(buttons_frame, text="Clear Analysis", command=self._clear_change_analysis).pack(side="left", padx=5)
# File selection frame
file_frame = ttk.LabelFrame(parent, text="Analyze Specific Webhook File")
file_frame.pack(fill="x", padx=10, pady=5)
file_select_frame = ttk.Frame(file_frame)
file_select_frame.pack(fill="x", padx=5, pady=5)
self.webhook_file_var = tk.StringVar()
webhook_file_combo = ttk.Combobox(file_select_frame, textvariable=self.webhook_file_var, width=50)
webhook_file_combo.pack(side="left", padx=(0, 5))
ttk.Button(file_select_frame, text="Browse", command=self._browse_webhook_file).pack(side="left", padx=5)
ttk.Button(file_select_frame, text="Analyze Selected", command=self._analyze_selected_webhook).pack(side="left", padx=5)
# Update webhook file list
self._update_webhook_file_list(webhook_file_combo)
# Change details display
details_frame = ttk.LabelFrame(parent, text="Change Details")
details_frame.pack(fill="both", expand=True, padx=10, pady=5)
self.change_details_text = scrolledtext.ScrolledText(details_frame, height=20, state="disabled")
self.change_details_text.pack(fill="both", expand=True, padx=5, pady=5)
# Auto-refresh changes
self._refresh_changes()
def _authenticate(self):
"""Authenticate with Microsoft Graph"""
def auth_worker():
try:
self._update_auth_status("Starting authentication...")
client_id = self.client_id_var.get().strip()
client_secret = self.client_secret_var.get().strip() or None
tenant_id = self.tenant_id_var.get().strip() or "common"
auth_type = self.auth_type_var.get()
if not client_id:
raise Exception("Client ID is required")
# Initialize authenticator
self.authenticator = GraphAuthenticator(client_id, client_secret, tenant_id)
# Authenticate based on type
if auth_type == "interactive":
if client_secret:
raise Exception("Interactive authentication cannot be used with client secret. Please remove the client secret or switch to app-only authentication.")
self._update_auth_status("Opening browser for interactive authentication...")
success = self.authenticator.authenticate_interactive()
else:
if not client_secret:
raise Exception("Client secret is required for app-only authentication")
self._update_auth_status("Authenticating with client credentials...")
success = self.authenticator.authenticate_client_credentials()
if success:
# Initialize subscription manager
self.subscription_manager = GraphSubscriptionManager(self.authenticator, self.http_logger)
self._update_auth_status("Authentication successful!")
self.sound_manager.play_success_sound()
else:
self._update_auth_status("Authentication failed!")
self.sound_manager.play_error_sound()
except Exception as e:
self._update_auth_status(f"Authentication error: {str(e)}")
self.sound_manager.play_error_sound()
# Run authentication in background thread
threading.Thread(target=auth_worker, daemon=True).start()
def _create_subscription(self):
"""Create a Microsoft Graph subscription"""
def create_worker():
try:
if not self.subscription_manager:
raise Exception("Please authenticate first")
self._update_response("Creating subscription...")
resource = self.resource_var.get().strip()
change_type = self.change_type_var.get().strip()
notification_url = self.notification_url_var.get().strip()
expiration_hours = int(self.expiration_var.get().strip())
include_security = self.include_security_var.get()
if not all([resource, change_type, notification_url]):
raise Exception("Resource, change type, and notification URL are required")
# Create subscription
result = self.subscription_manager.create_subscription(
resource=resource,
change_type=change_type,
notification_url=notification_url,
expiration_hours=expiration_hours,
include_security_webhooks=include_security
)
# Format response
response_text = f"Status: {result['message']}\n"
response_text += f"Success: {result['success']}\n"
response_text += f"Status Code: {result['status_code']}\n\n"
if result['success']:
response_text += "Subscription Details:\n"
response_text += json.dumps(result['data'], indent=2)
self.sound_manager.play_success_sound()
else:
response_text += "Error Details:\n"
response_text += json.dumps(result.get('error', {}), indent=2)
self.sound_manager.play_error_sound()
self._update_response(response_text)
except Exception as e:
error_text = f"Error creating subscription: {str(e)}"
self._update_response(error_text)
self.sound_manager.play_error_sound()
# Run in background thread
threading.Thread(target=create_worker, daemon=True).start()
def _refresh_subscriptions(self):
"""Refresh the list of active subscriptions"""
def refresh_worker():
try:
if not self.subscription_manager:
raise Exception("Please authenticate first")
self._update_subscriptions("Refreshing subscriptions...")
result = self.subscription_manager.list_subscriptions()
if result['success']:
subscriptions = result['data'].get('value', [])
if not subscriptions:
text = "No active subscriptions found."
else:
text = f"Found {len(subscriptions)} active subscription(s):\n\n"
for i, sub in enumerate(subscriptions, 1):
text += f"Subscription {i}:\n"
text += f" ID: {sub.get('id', 'N/A')}\n"
text += f" Resource: {sub.get('resource', 'N/A')}\n"
text += f" Change Type: {sub.get('changeType', 'N/A')}\n"
text += f" Notification URL: {sub.get('notificationUrl', 'N/A')}\n"
text += f" Expiration: {sub.get('expirationDateTime', 'N/A')}\n"
text += f" Client State: {sub.get('clientState', 'N/A')}\n"
text += "-" * 60 + "\n"
self._update_subscriptions(text)
else:
error_text = f"Error retrieving subscriptions: {result['message']}\n"
error_text += json.dumps(result.get('error', {}), indent=2)
self._update_subscriptions(error_text)
except Exception as e:
error_text = f"Error refreshing subscriptions: {str(e)}"
self._update_subscriptions(error_text)
# Run in background thread
threading.Thread(target=refresh_worker, daemon=True).start()
def _refresh_logs(self):
"""Refresh the API logs display"""
try:
if os.path.exists(self.http_logger.log_file):
with open(self.http_logger.log_file, 'r', encoding='utf-8') as f:
log_content = f.read()
self.logs_text.config(state="normal")
self.logs_text.delete(1.0, tk.END)
self.logs_text.insert(tk.END, log_content)
self.logs_text.config(state="disabled")
# Scroll to bottom
self.logs_text.see(tk.END)
else:
self.logs_text.config(state="normal")
self.logs_text.delete(1.0, tk.END)
self.logs_text.insert(tk.END, "No log file found. Make API requests to see logs here.")
self.logs_text.config(state="disabled")
except Exception as e:
self.logs_text.config(state="normal")
self.logs_text.delete(1.0, tk.END)
self.logs_text.insert(tk.END, f"Error reading log file: {str(e)}")
self.logs_text.config(state="disabled")
def _clear_logs(self):
"""Clear the API logs"""
try:
if os.path.exists(self.http_logger.log_file):
open(self.http_logger.log_file, 'w').close()
self._refresh_logs()
messagebox.showinfo("Success", "Logs cleared successfully!")
except Exception as e:
messagebox.showerror("Error", f"Failed to clear logs: {str(e)}")
def _export_logs(self):
"""Export logs to a file"""
try:
filename = filedialog.asksaveasfilename(
defaultextension=".log",
filetypes=[("Log files", "*.log"), ("Text files", "*.txt"), ("All files", "*.*")]
)
if filename:
if os.path.exists(self.http_logger.log_file):
with open(self.http_logger.log_file, 'r', encoding='utf-8') as src:
with open(filename, 'w', encoding='utf-8') as dst:
dst.write(src.read())
messagebox.showinfo("Success", f"Logs exported to: {filename}")
else:
messagebox.showwarning("Warning", "No log file found to export.")
except Exception as e:
messagebox.showerror("Error", f"Failed to export logs: {str(e)}")
def _open_log_file(self):
"""Open the log file in the default text editor"""
try:
log_file_path = self.http_logger.log_file
# Create the log file if it doesn't exist
if not os.path.exists(log_file_path):
# Ensure the directory exists
log_dir = os.path.dirname(log_file_path)
if not os.path.exists(log_dir):
os.makedirs(log_dir)
# Create an empty log file
with open(log_file_path, 'w', encoding='utf-8') as f:
f.write("# Graph API Requests Log\n")
f.write(f"# Created: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n\n")
# Open the file with the default application
os.startfile(log_file_path)
except Exception as e:
messagebox.showerror("Error", f"Failed to open log file: {str(e)}")
print(f"Debug - Log file path: {getattr(self.http_logger, 'log_file', 'Not set')}")
print(f"Debug - Error: {str(e)}")
def _save_config(self):
"""Save configuration to file"""
try:
config = {
"client_id": self.client_id_var.get(),
"client_secret": self.client_secret_var.get(),
"tenant_id": self.tenant_id_var.get(),
"auth_type": self.auth_type_var.get(),
"subscription_defaults": {
"resource": self.resource_var.get(),
"change_type": self.change_type_var.get(),
"notification_url": self.notification_url_var.get(),
"expiration_hours": self.expiration_var.get(),
"include_security_webhooks": self.include_security_var.get()
}
}
filename = filedialog.asksaveasfilename(
defaultextension=".json",
filetypes=[("JSON files", "*.json"), ("All files", "*.*")],
title="Save Configuration"
)
if filename:
with open(filename, 'w') as f:
json.dump(config, f, indent=2)