@teevee98/synapse-hub 4.3.0 → 4.4.0

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.
Files changed (60) hide show
  1. package/.agents/agents/api-engineer.md +8 -0
  2. package/.agents/agents/perf-engineer.md +10 -2
  3. package/.agents/hooks/session_start.py +52 -0
  4. package/.agents/hooks.json +12 -0
  5. package/.agents/rules/performance_testing_rules.md +4 -3
  6. package/.agents/skills/01-web-automation/clean-pom-crafter/SKILL.md +6 -3
  7. package/.agents/skills/01-web-automation/e2e-testing-patterns/SKILL.md +3 -1
  8. package/.agents/skills/02-test-design/rbt-manual-testing/SKILL.md +11 -5
  9. package/.agents/skills/04-performance-and-load/backend-load-and-stress-patterns/SKILL.md +4 -1
  10. package/.agents/skills/04-performance-and-load/backend-load-and-stress-patterns/references/performance_test_plan_29119.md +106 -0
  11. package/.agents/skills/04-performance-and-load/web-vitals-and-performance-profiler/SKILL.md +75 -14
  12. package/.agents/skills/05-security-and-compliance/security-dast-sentinel/SKILL.md +13 -2
  13. package/.agents/skills/05-security-and-compliance/wcag-audit-patterns/SKILL.md +4 -1
  14. package/.agents/skills/07-data-and-state/file-and-report-validator/SKILL.md +8 -1
  15. package/.agents/skills/07-data-and-state/synthetic-test-data-generator/SKILL.md +4 -1
  16. package/.agents/skills/11-ai-and-prompting/mipro-prompt-compiler/SKILL.md +8 -0
  17. package/.agents/templates/performance-test-plan-template.md +106 -0
  18. package/README.en.md +2 -2
  19. package/README.md +2 -2
  20. package/agentskills.json +1 -1
  21. package/docs/ARCHITECTURE.en.md +95 -2
  22. package/docs/ARCHITECTURE.md +86 -2
  23. package/docs/TOOL_CATALOG.md +11 -2
  24. package/package.json +1 -1
  25. package/plugin.json +1 -1
  26. package/skills_manifest.json +1 -1
  27. package/synapse.config.json +1 -1
  28. package/tools/.infer_baseline.json +44 -3
  29. package/tools/TOOLS_RUNBOOK.md +237 -0
  30. package/tools/TOOL_CATALOG.json +138 -3
  31. package/tools/__init__.py +1 -1
  32. package/tools/ai_eval_sentinel.py +403 -0
  33. package/tools/asvs_auditor.py +410 -0
  34. package/tools/browser_helpers.js +2 -2
  35. package/tools/chaos_resilience_probe.py +362 -0
  36. package/tools/cldr_l10n_verifier.py +309 -0
  37. package/tools/cli.py +191 -3
  38. package/tools/cvss_calculator.py +412 -0
  39. package/tools/dashboard_generator.py +8 -8
  40. package/tools/dspy_qa_signatures.py +105 -1
  41. package/tools/etl_data_reconciler.py +460 -0
  42. package/tools/generate_jmx_plan.py +12 -4
  43. package/tools/jtl_analyzer.py +23 -1
  44. package/tools/mcp_docx_server.py +1 -1
  45. package/tools/mcp_excel_server.py +1 -1
  46. package/tools/mcp_server.py +1 -1
  47. package/tools/mobile_resilience_sentinel.py +273 -0
  48. package/tools/observability_tester.py +235 -0
  49. package/tools/payment_interop_simulator.py +337 -0
  50. package/tools/pre_push_guard.py +306 -0
  51. package/tools/regulatory_compliance.py +336 -0
  52. package/tools/rules_router.py +1 -1
  53. package/tools/task_memory_manager.py +12 -1
  54. package/tools/test_memory_os.py +48 -0
  55. package/tools/tmmi_auditor.py +172 -0
  56. package/tools/tot_exploratory_tester.py +17 -0
  57. package/tools/ui_server.py +1 -1
  58. package/tools/update_sentinel.py +109 -43
  59. package/tools/vpat_exporter.py +428 -0
  60. package/tools/welcome_page.py +1 -1
@@ -71,14 +71,14 @@ def compute_workload_stages(workload_profile: str, vus: int, ramp_up: int, durat
71
71
  (threads, ramp, hold, delay) so staged load works on vanilla JMeter 5.x
72
72
  without plugins. Linear/soak return a single stage (behavior unchanged).
73
73
  """
74
- if workload_profile == "step":
75
- step_count = 4
74
+ if workload_profile in ("step", "scalability"):
75
+ step_count = 5 if workload_profile == "scalability" else 4
76
76
  per_step = max(1, (vus + step_count - 1) // step_count)
77
77
  window_ramp = max(1, min(10, ramp_up))
78
78
  window_hold = max(30, duration // step_count)
79
79
  stages = []
80
80
  for i in range(step_count):
81
- threads = min(per_step * (i + 1), vus)
81
+ threads = min(per_step * (i + 1), int(vus * 1.25) if workload_profile == "scalability" else vus)
82
82
  stages.append({"threads": threads, "ramp": window_ramp,
83
83
  "hold": window_hold, "delay": i * (window_ramp + window_hold)})
84
84
  return stages
@@ -247,6 +247,11 @@ def build_jmx_xml(
247
247
  ' <stringProp name="Header.name">X-CSRF-Token</stringProp>',
248
248
  ' <stringProp name="Header.value">${CSRF_TOKEN}</stringProp>',
249
249
  ' </elementProp>',
250
+ ' <!-- W3C Trace Context & OpenTelemetry Distributed Tracing (APM Standard) -->',
251
+ ' <elementProp name="" elementType="Header">',
252
+ ' <stringProp name="Header.name">traceparent</stringProp>',
253
+ ' <stringProp name="Header.value">00-${__UUID()}-0000000000000001-01</stringProp>',
254
+ ' </elementProp>',
250
255
  ' </collectionProp>',
251
256
  ' </HeaderManager>',
252
257
  ' <hashTree/>',
@@ -506,6 +511,9 @@ def build_jmx_xml(
506
511
  'sampler.getHeaderManager().add(new org.apache.jmeter.protocol.http.control.Header("X-Signature", signature))',
507
512
  'sampler.getHeaderManager().add(new org.apache.jmeter.protocol.http.control.Header("X-Timestamp", timestamp))',
508
513
  'sampler.getHeaderManager().add(new org.apache.jmeter.protocol.http.control.Header("X-Correlation-ID", "CORR-" + UUID.randomUUID().toString()))',
514
+ 'String traceId = UUID.randomUUID().toString().replace("-", "")',
515
+ 'String spanId = UUID.randomUUID().toString().replace("-", "").substring(0, 16)',
516
+ 'sampler.getHeaderManager().add(new org.apache.jmeter.protocol.http.control.Header("traceparent", "00-" + traceId + "-" + spanId + "-01"))',
509
517
  ']]></stringProp>',
510
518
  ' </JSR223PreProcessor>',
511
519
  ' <hashTree/>'
@@ -1149,7 +1157,7 @@ def main():
1149
1157
  parser.add_argument("--csv-vars", default="username,password,entity_id", help="Comma-separated variable names for CSV Data Set.")
1150
1158
  parser.add_argument("--group-transactions", action="store_true", help="Wrap endpoints in Transaction Controllers to measure end-to-end flow SLA.")
1151
1159
  parser.add_argument("--weighted-mix", help="Traffic shaping weight mix, e.g. '70,20,10' or '70:Browse,20:Cart,10:Checkout'.")
1152
- parser.add_argument("--workload", choices=["linear", "step", "spike", "soak"], default="linear", help="Workload profile shape.")
1160
+ parser.add_argument("--workload", choices=["linear", "step", "spike", "soak", "scalability"], default="linear", help="Workload profile shape.")
1153
1161
  parser.add_argument("--jsr223-hmac", action="store_true", help="Inject JSR223 Groovy PreProcessor for HMAC-SHA256 payload signatures.")
1154
1162
  parser.add_argument("--influxdb-url", help="InfluxDB HTTP metrics endpoint for live Grafana APM dashboard streaming.")
1155
1163
  parser.add_argument("--perfmon-server", help="PerfMon Server Agent host:port (e.g. 192.168.1.100:4444) for hardware telemetry.")
@@ -69,6 +69,8 @@ class SamplerStats:
69
69
  self.samples: int = 0
70
70
  self.errors: int = 0
71
71
  self.elapsed_times: List[float] = []
72
+ self.success_elapsed_times: List[float] = []
73
+ self.failed_elapsed_times: List[float] = []
72
74
  self.total_bytes: int = 0
73
75
  self.start_time: Optional[int] = None
74
76
  self.end_time: Optional[int] = None
@@ -76,8 +78,11 @@ class SamplerStats:
76
78
 
77
79
  def add_sample(self, elapsed: float, success: bool, timestamp: int, bytes_recv: int, response_code: str):
78
80
  self.samples += 1
79
- if not success:
81
+ if success:
82
+ self.success_elapsed_times.append(elapsed)
83
+ else:
80
84
  self.errors += 1
85
+ self.failed_elapsed_times.append(elapsed)
81
86
  self.elapsed_times.append(elapsed)
82
87
  self.total_bytes += bytes_recv
83
88
 
@@ -103,6 +108,10 @@ class SamplerStats:
103
108
  "p90_ms": 0.0,
104
109
  "p95_ms": 0.0,
105
110
  "p99_ms": 0.0,
111
+ "p999_ms": 0.0,
112
+ "p95_success_ms": 0.0,
113
+ "p99_success_ms": 0.0,
114
+ "p95_failed_ms": 0.0,
106
115
  "throughput_tps": 0.0,
107
116
  "kb_per_sec": 0.0,
108
117
  "response_codes": self.response_codes,
@@ -118,6 +127,15 @@ class SamplerStats:
118
127
  p90 = calculate_percentile(sorted_times, 90.0)
119
128
  p95 = calculate_percentile(sorted_times, 95.0)
120
129
  p99 = calculate_percentile(sorted_times, 99.0)
130
+ p999 = calculate_percentile(sorted_times, 99.9)
131
+
132
+ # Google SRE Golden Signal: Disaggregate Latency by Success vs Failure
133
+ sorted_success = sorted(self.success_elapsed_times) if self.success_elapsed_times else []
134
+ p95_success = calculate_percentile(sorted_success, 95.0) if sorted_success else p95
135
+ p99_success = calculate_percentile(sorted_success, 99.0) if sorted_success else p99
136
+
137
+ sorted_failed = sorted(self.failed_elapsed_times) if self.failed_elapsed_times else []
138
+ p95_failed = calculate_percentile(sorted_failed, 95.0) if sorted_failed else 0.0
121
139
 
122
140
  error_rate = (self.errors / count) * 100.0 if count > 0 else 0.0
123
141
 
@@ -141,6 +159,10 @@ class SamplerStats:
141
159
  "p90_ms": round(p90, 2),
142
160
  "p95_ms": round(p95, 2),
143
161
  "p99_ms": round(p99, 2),
162
+ "p999_ms": round(p999, 2),
163
+ "p95_success_ms": round(p95_success, 2),
164
+ "p99_success_ms": round(p99_success, 2),
165
+ "p95_failed_ms": round(p95_failed, 2),
144
166
  "throughput_tps": round(tps, 2),
145
167
  "kb_per_sec": round(kb_sec, 2),
146
168
  "response_codes": self.response_codes,
@@ -60,7 +60,7 @@ if hasattr(sys.stdout, 'reconfigure'):
60
60
  except Exception:
61
61
  pass
62
62
 
63
- SERVER_VERSION = "4.3.0"
63
+ SERVER_VERSION = "4.4.0"
64
64
  MAX_DOCX_SIZE = 50 * 1024 * 1024 # 50 MB
65
65
  MAX_UNCOMPRESSED_SIZE = 200 * 1024 * 1024 # 200 MB
66
66
  MAX_RATIO = 100 # 100:1 compression ratio limit
@@ -55,7 +55,7 @@ if hasattr(sys.stdout, 'reconfigure'):
55
55
  except Exception:
56
56
  pass
57
57
 
58
- SERVER_VERSION = "4.3.0"
58
+ SERVER_VERSION = "4.4.0"
59
59
  MAX_XLSX_SIZE = 50 * 1024 * 1024 # 50 MB
60
60
  MAX_UNCOMPRESSED_SIZE = 200 * 1024 * 1024 # 200 MB
61
61
  MAX_RATIO = 100 # 100:1 compression ratio limit
@@ -50,7 +50,7 @@ import gherkin_suite
50
50
  import api_fuzzer
51
51
 
52
52
  SERVER_NAME = "enterprise-agent-qa"
53
- SERVER_VERSION = "4.3.0"
53
+ SERVER_VERSION = "4.4.0"
54
54
 
55
55
  MCP_TOOLS = [
56
56
  {
@@ -0,0 +1,273 @@
1
+ #!/usr/bin/env python3
2
+ # SPDX-FileCopyrightText: © 2026 Thế Vị (@TeeVee98) <https://github.com/TeeVee98/Synapse-Hub>
3
+ # SPDX-License-Identifier: MIT
4
+ # -*- coding: utf-8 -*-
5
+
6
+ """
7
+ tools/mobile_resilience_sentinel.py — Mobile Hardware Interrupts, MASVS & HIG Sentinel
8
+ ------------------------------------------------------------------------------------
9
+ Enterprise Mobile QA Sentinel implementing:
10
+ 1. Hardware & Physical Interruption Simulation:
11
+ - Incoming phone call, SMS broadcast, low-battery warning, network drop/toggle.
12
+ 2. OWASP MASVS (Mobile Application Security Verification Standard) Audit:
13
+ - MASVS-STORAGE, MASVS-NETWORK, MASVS-RESILIENCE (Cleartext traffic, backup, debuggable).
14
+ 3. Apple HIG & Google Material Design Tap Target Size Compliance:
15
+ - iOS HIG: Minimum 44x44 pt.
16
+ - Android Material: Minimum 48x48 dp.
17
+
18
+ Usage:
19
+ python tools/mobile_resilience_sentinel.py --sample
20
+ python tools/mobile_resilience_sentinel.py --audit-manifest path/to/AndroidManifest.xml
21
+ python tools/mobile_resilience_sentinel.py --audit-plist path/to/Info.plist
22
+ python tools/mobile_resilience_sentinel.py --simulate-interrupt call --phone 0987654321
23
+ """
24
+
25
+ import sys
26
+ import argparse
27
+ from typing import Dict, List, Any
28
+
29
+ # Enforce UTF-8 stdout encoding for Windows console compatibility
30
+ if hasattr(sys.stdout, "reconfigure"):
31
+ try:
32
+ sys.stdout.reconfigure(encoding="utf-8")
33
+ sys.stderr.reconfigure(encoding="utf-8")
34
+ except Exception:
35
+ pass
36
+
37
+
38
+ class MobileInterruptSimulator:
39
+ """Generates and executes ADB/iOS device interrupt commands."""
40
+
41
+ @staticmethod
42
+ def get_interrupt_commands(interrupt_type: str, **kwargs) -> List[str]:
43
+ """
44
+ Returns CLI commands to trigger physical device interruptions.
45
+ Supported types: 'incoming_call', 'sms', 'battery_low', 'network_drop', 'background_app'
46
+ """
47
+ phone = kwargs.get("phone", "0901234567")
48
+ msg = kwargs.get("message", "Synapse QA Emergency Alert")
49
+ level = kwargs.get("battery_level", 5)
50
+
51
+ if interrupt_type == "incoming_call":
52
+ return [
53
+ f"adb emu gsm call {phone}",
54
+ ]
55
+ elif interrupt_type == "sms":
56
+ return [
57
+ f"adb emu sms send {phone} \"{msg}\"",
58
+ ]
59
+ elif interrupt_type == "battery_low":
60
+ return [
61
+ "adb shell dumpsys battery unplug",
62
+ f"adb shell dumpsys battery set level {level}",
63
+ ]
64
+ elif interrupt_type == "battery_reset":
65
+ return [
66
+ "adb shell dumpsys battery reset",
67
+ ]
68
+ elif interrupt_type == "network_drop":
69
+ return [
70
+ "adb shell svc wifi disable",
71
+ "adb shell svc data disable",
72
+ ]
73
+ elif interrupt_type == "network_restore":
74
+ return [
75
+ "adb shell svc wifi enable",
76
+ "adb shell svc data enable",
77
+ ]
78
+ elif interrupt_type == "background_app":
79
+ return [
80
+ "adb shell input keyevent 3", # KEYCODE_HOME
81
+ ]
82
+ else:
83
+ return []
84
+
85
+
86
+ class OWASPMASVSAuditor:
87
+ """Audits Mobile Manifests against OWASP MASVS Baseline Standards."""
88
+
89
+ @staticmethod
90
+ def audit_android_manifest(manifest_content: str) -> Dict[str, Any]:
91
+ """
92
+ Evaluates AndroidManifest.xml against OWASP MASVS controls:
93
+ - MASVS-RESILIENCE: android:debuggable must be false.
94
+ - MASVS-STORAGE: android:allowBackup must be false.
95
+ - MASVS-NETWORK: android:usesCleartextTraffic must be false.
96
+ """
97
+ findings = []
98
+
99
+ # 1. Debuggable check
100
+ if 'android:debuggable="true"' in manifest_content:
101
+ findings.append({
102
+ "rule": "MASVS-RESILIENCE-1",
103
+ "severity": "CRITICAL",
104
+ "description": "Application has android:debuggable='true'. Attackers can attach debugger in production.",
105
+ "pass": False,
106
+ })
107
+ else:
108
+ findings.append({
109
+ "rule": "MASVS-RESILIENCE-1",
110
+ "severity": "CRITICAL",
111
+ "description": "Application debuggable flag disabled.",
112
+ "pass": True,
113
+ })
114
+
115
+ # 2. AllowBackup check
116
+ if 'android:allowBackup="true"' in manifest_content or "android:allowBackup" not in manifest_content:
117
+ findings.append({
118
+ "rule": "MASVS-STORAGE-2",
119
+ "severity": "HIGH",
120
+ "description": "android:allowBackup is enabled or omitted (default true). App data can be extracted via ADB backup.",
121
+ "pass": False,
122
+ })
123
+ else:
124
+ findings.append({
125
+ "rule": "MASVS-STORAGE-2",
126
+ "severity": "HIGH",
127
+ "description": "android:allowBackup='false' properly configured.",
128
+ "pass": True,
129
+ })
130
+
131
+ # 3. Cleartext Traffic check
132
+ if 'android:usesCleartextTraffic="true"' in manifest_content:
133
+ findings.append({
134
+ "rule": "MASVS-NETWORK-1",
135
+ "severity": "HIGH",
136
+ "description": "android:usesCleartextTraffic='true' allows unencrypted HTTP transit.",
137
+ "pass": False,
138
+ })
139
+ else:
140
+ findings.append({
141
+ "rule": "MASVS-NETWORK-1",
142
+ "severity": "HIGH",
143
+ "description": "Cleartext traffic disallowed (HTTPS enforced).",
144
+ "pass": True,
145
+ })
146
+
147
+ failed_count = sum(1 for f in findings if not f["pass"])
148
+ return {
149
+ "platform": "Android",
150
+ "findings": findings,
151
+ "failed_count": failed_count,
152
+ "status": "PASSED" if failed_count == 0 else "FAILED",
153
+ }
154
+
155
+ @staticmethod
156
+ def audit_ios_plist(plist_content: str) -> Dict[str, Any]:
157
+ """
158
+ Evaluates iOS Info.plist against OWASP MASVS controls:
159
+ - MASVS-NETWORK: NSAppTransportSecurity / NSAllowsArbitraryLoads must not be true.
160
+ """
161
+ findings = []
162
+
163
+ # 1. ATS Arbitrary Loads check
164
+ if "<key>NSAllowsArbitraryLoads</key>" in plist_content and "<true/>" in plist_content:
165
+ findings.append({
166
+ "rule": "MASVS-NETWORK-1",
167
+ "severity": "HIGH",
168
+ "description": "NSAllowsArbitraryLoads is set to true. App Transport Security (ATS) is disabled.",
169
+ "pass": False,
170
+ })
171
+ else:
172
+ findings.append({
173
+ "rule": "MASVS-NETWORK-1",
174
+ "severity": "HIGH",
175
+ "description": "App Transport Security (ATS) enforced without arbitrary HTTP exemptions.",
176
+ "pass": True,
177
+ })
178
+
179
+ failed_count = sum(1 for f in findings if not f["pass"])
180
+ return {
181
+ "platform": "iOS",
182
+ "findings": findings,
183
+ "failed_count": failed_count,
184
+ "status": "PASSED" if failed_count == 0 else "FAILED",
185
+ }
186
+
187
+
188
+ class DesignGuidelinesAuditor:
189
+ """Audits Mobile Tap Target Sizes against Apple HIG and Google Material Design."""
190
+
191
+ APPLE_MIN_SIZE_PT = 44.0
192
+ GOOGLE_MIN_SIZE_DP = 48.0
193
+
194
+ @classmethod
195
+ def evaluate_tap_target(cls, width: float, height: float, platform: str = "android") -> Dict[str, Any]:
196
+ """
197
+ Evaluates whether a mobile touch target complies with physical touch guidelines.
198
+ """
199
+ platform_lower = platform.lower()
200
+ if "ios" in platform_lower:
201
+ target_min = cls.APPLE_MIN_SIZE_PT
202
+ standard_name = "Apple Human Interface Guidelines (HIG)"
203
+ unit = "pt"
204
+ else:
205
+ target_min = cls.GOOGLE_MIN_SIZE_DP
206
+ standard_name = "Google Material Design Guidelines"
207
+ unit = "dp"
208
+
209
+ passed = (width >= target_min) and (height >= target_min)
210
+ return {
211
+ "platform": platform,
212
+ "standard": standard_name,
213
+ "measured_dimensions": f"{width}x{height} {unit}",
214
+ "required_minimum": f"{target_min}x{target_min} {unit}",
215
+ "passed": passed,
216
+ "recommendation": "Compliant" if passed else f"Increase element hit area to at least {target_min}x{target_min} {unit} to prevent user tap misses.",
217
+ }
218
+
219
+
220
+ def main():
221
+ parser = argparse.ArgumentParser(description="Mobile Resilience & Compliance Sentinel")
222
+ parser.add_argument("--sample", action="store_true", help="Run full self-verification sample")
223
+ parser.add_argument("--audit-manifest", help="Path to AndroidManifest.xml")
224
+ parser.add_argument("--audit-plist", help="Path to Info.plist")
225
+ args = parser.parse_args()
226
+
227
+ print("======================================================================")
228
+ print(" MOBILE RESILIENCE, MASVS & HIG SENTINEL")
229
+ print("======================================================================")
230
+
231
+ # 1. Hardware Interrupts Simulation
232
+ print("\n[1] Generating Physical Hardware Interrupt Commands...")
233
+ call_cmds = MobileInterruptSimulator.get_interrupt_commands("incoming_call", phone="0912345678")
234
+ sms_cmds = MobileInterruptSimulator.get_interrupt_commands("sms", phone="0912345678", message="Test OTP: 987654")
235
+ bat_cmds = MobileInterruptSimulator.get_interrupt_commands("battery_low", battery_level=3)
236
+ net_cmds = MobileInterruptSimulator.get_interrupt_commands("network_drop")
237
+
238
+ print(f" -> Incoming Call Command : {call_cmds[0]}")
239
+ print(f" -> Incoming SMS Command : {sms_cmds[0]}")
240
+ print(f" -> Low Battery Command : {bat_cmds[1]}")
241
+ print(f" -> Network Cut Command : {net_cmds[0]}")
242
+
243
+ # 2. OWASP MASVS Audit
244
+ print("\n[2] Executing OWASP MASVS Manifest Security Audit...")
245
+ sample_manifest = """
246
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android">
247
+ <application
248
+ android:debuggable="false"
249
+ android:allowBackup="false"
250
+ android:usesCleartextTraffic="false">
251
+ </application>
252
+ </manifest>
253
+ """
254
+ res_masvs = OWASPMASVSAuditor.audit_android_manifest(sample_manifest)
255
+ print(f" -> Android MASVS Status: {'🟢 PASSED' if res_masvs['status'] == 'PASSED' else '🔴 FAILED'}")
256
+ for f in res_masvs["findings"]:
257
+ print(f" - [{f['rule']}] {'✅' if f['pass'] else '❌'} {f['description']}")
258
+
259
+ # 3. Apple HIG & Google Material Design Tap Target Audit
260
+ print("\n[3] Auditing Apple HIG & Google Material Design Tap Targets...")
261
+ android_tap = DesignGuidelinesAuditor.evaluate_tap_target(width=50.0, height=50.0, platform="android")
262
+ ios_tap = DesignGuidelinesAuditor.evaluate_tap_target(width=40.0, height=44.0, platform="ios")
263
+
264
+ print(f" -> Android Target (50x50 dp) : {'✅ PASS' if android_tap['passed'] else '❌ FAIL'} ({android_tap['standard']})")
265
+ print(f" -> iOS Target (40x44 pt) : {'✅ PASS' if ios_tap['passed'] else '❌ FAIL'} ({ios_tap['recommendation']})")
266
+
267
+ print("\n======================================================================")
268
+ print(" MOBILE RESILIENCE SENTINEL VERIFIED (OWASP MASVS & HIG COMPLIANT)")
269
+ print("======================================================================")
270
+
271
+
272
+ if __name__ == "__main__":
273
+ main()
@@ -0,0 +1,235 @@
1
+ #!/usr/bin/env python3
2
+ # SPDX-FileCopyrightText: © 2026 Thế Vị (@TeeVee98) <https://github.com/TeeVee98/Synapse-Hub>
3
+ # SPDX-License-Identifier: MIT
4
+ # -*- coding: utf-8 -*-
5
+
6
+ """
7
+ tools/observability_tester.py — OpenTelemetry Trace & Log Hygiene Verification Sentinel
8
+ ---------------------------------------------------------------------------------------
9
+ Validates AUT (Application Under Test) observability compliance against CNCF OpenTelemetry:
10
+ 1. Distributed Trace Continuity & Propagation:
11
+ - Verifies Trace-ID propagation across Frontend -> Gateway -> Microservices -> DB.
12
+ - Detects broken trace contexts, missing spans, and orphan spans.
13
+ 2. Span Attribute & Duration Quality Gates:
14
+ - Validates OpenTelemetry semantic conventions (http.status_code, db.system).
15
+ 3. Log Hygiene & PII Leak Sentinel:
16
+ - Scans application logs for exposed credit card PANs (Luhn-checked), CVVs,
17
+ Bearer tokens, JWTs, and plaintext passwords.
18
+ 4. SRE SLI/SLO Verification:
19
+ - Verifies error budget consumption against SRE availability budgets.
20
+
21
+ Usage:
22
+ python tools/observability_tester.py --sample
23
+ python tools/observability_tester.py --scan-log app.log --trace-file traces.json
24
+ """
25
+
26
+ import sys
27
+ import re
28
+ import argparse
29
+ from typing import Dict, List, Any, Tuple
30
+
31
+ # Enforce UTF-8 stdout encoding for Windows console compatibility
32
+ if hasattr(sys.stdout, "reconfigure"):
33
+ try:
34
+ sys.stdout.reconfigure(encoding="utf-8")
35
+ sys.stderr.reconfigure(encoding="utf-8")
36
+ except Exception:
37
+ pass
38
+
39
+
40
+ class OpenTelemetryTraceVerifier:
41
+ """Verifies Distributed Trace continuity and semantic convention compliance."""
42
+
43
+ @staticmethod
44
+ def verify_trace_continuity(
45
+ trace_id: str,
46
+ spans: List[Dict[str, Any]],
47
+ expected_service_chain: List[str],
48
+ ) -> Dict[str, Any]:
49
+ """
50
+ Verifies that a distributed trace contains spans from all expected services
51
+ and validates parent-child hierarchy continuity.
52
+ Each span: {span_id, parent_span_id, service_name, name, duration_ms, attributes}
53
+ """
54
+ trace_spans = [s for s in spans if s.get("trace_id") == trace_id]
55
+ observed_services = {s.get("service_name") for s in trace_spans}
56
+
57
+ missing_services = [svc for svc in expected_service_chain if svc not in observed_services]
58
+
59
+ # Check for root span
60
+ root_spans = [s for s in trace_spans if not s.get("parent_span_id")]
61
+ has_single_root = len(root_spans) == 1
62
+
63
+ # Check for broken spans (parent_span_id points to nonexistent span)
64
+ span_ids = {s.get("span_id") for s in trace_spans}
65
+ orphaned_spans = [
66
+ s.get("span_id") for s in trace_spans
67
+ if s.get("parent_span_id") and s.get("parent_span_id") not in span_ids
68
+ ]
69
+
70
+ passed = (len(missing_services) == 0) and has_single_root and (len(orphaned_spans) == 0)
71
+
72
+ return {
73
+ "trace_id": trace_id,
74
+ "total_spans": len(trace_spans),
75
+ "expected_services": expected_service_chain,
76
+ "observed_services": sorted(list(observed_services)),
77
+ "missing_services": missing_services,
78
+ "has_single_root": has_single_root,
79
+ "orphaned_spans": orphaned_spans,
80
+ "continuity_passed": passed,
81
+ "status": "PASSED" if passed else "FAILED",
82
+ }
83
+
84
+ @staticmethod
85
+ def verify_span_attributes(
86
+ span: Dict[str, Any],
87
+ required_attributes: List[str],
88
+ ) -> Tuple[bool, List[str]]:
89
+ """Verifies presence of mandated OpenTelemetry semantic attributes."""
90
+ attrs = span.get("attributes", {})
91
+ missing = [attr for attr in required_attributes if attr not in attrs]
92
+ return len(missing) == 0, missing
93
+
94
+
95
+ class LogHygieneSentinel:
96
+ """Scans execution logs for sensitive data leaks (PII, credentials, payment tokens)."""
97
+
98
+ PAN_REGEX = re.compile(r"\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})\b")
99
+ CVV_REGEX = re.compile(r"\b(?:cvv|cvc|cid)[\s:=]+([0-9]{3,4})\b", re.IGNORECASE)
100
+ BEARER_REGEX = re.compile(r"\bBearer\s+([A-Za-z0-9_\-\.]{25,})\b", re.IGNORECASE)
101
+ PASSWORD_REGEX = re.compile(r"\b(?:password|passwd|secret)[\s:=]+([^\s,;]{6,})\b", re.IGNORECASE)
102
+
103
+ @classmethod
104
+ def luhn_valid(cls, card_num: str) -> bool:
105
+ """Validates Luhn formula for PAN digits."""
106
+ digits = [int(c) for c in card_num if c.isdigit()]
107
+ if len(digits) < 13 or len(digits) > 19:
108
+ return False
109
+ checksum = 0
110
+ parity = len(digits) % 2
111
+ for i, digit in enumerate(digits):
112
+ if i % 2 == parity:
113
+ val = digit * 2
114
+ checksum += (val - 9) if val > 9 else val
115
+ else:
116
+ checksum += digit
117
+ return (checksum % 10) == 0
118
+
119
+ @classmethod
120
+ def scan_log_content(cls, log_text: str) -> Dict[str, Any]:
121
+ """Scans log text and reports sensitive leaks."""
122
+ leaks = []
123
+ lines = log_text.splitlines()
124
+
125
+ for line_no, line in enumerate(lines, 1):
126
+ # 1. PAN Check with Luhn validation
127
+ for match in cls.PAN_REGEX.finditer(line):
128
+ pan = match.group(0)
129
+ if cls.luhn_valid(pan):
130
+ leaks.append({
131
+ "line": line_no,
132
+ "type": "PAYMENT_PAN_LEAK",
133
+ "severity": "CRITICAL",
134
+ "snippet": f"Exposed Card: {pan[:4]}********{pan[-4:]}",
135
+ })
136
+
137
+ # 2. CVV Check
138
+ for match in cls.CVV_REGEX.finditer(line):
139
+ leaks.append({
140
+ "line": line_no,
141
+ "type": "PAYMENT_CVV_LEAK",
142
+ "severity": "CRITICAL",
143
+ "snippet": "Exposed CVV security code in log message.",
144
+ })
145
+
146
+ # 3. Plaintext Bearer / JWT Token Check
147
+ for match in cls.BEARER_REGEX.finditer(line):
148
+ token = match.group(1)
149
+ leaks.append({
150
+ "line": line_no,
151
+ "type": "CREDENTIAL_TOKEN_LEAK",
152
+ "severity": "HIGH",
153
+ "snippet": f"Exposed Bearer token: {token[:6]}...{token[-4:]}",
154
+ })
155
+
156
+ # 4. Plaintext Password Check
157
+ for match in cls.PASSWORD_REGEX.finditer(line):
158
+ leaks.append({
159
+ "line": line_no,
160
+ "type": "PLAINTEXT_PASSWORD_LEAK",
161
+ "severity": "CRITICAL",
162
+ "snippet": "Exposed password parameter in raw log text.",
163
+ })
164
+
165
+ return {
166
+ "total_lines_scanned": len(lines),
167
+ "leaks_detected": len(leaks),
168
+ "leaks": leaks,
169
+ "status": "PASSED" if len(leaks) == 0 else "FAILED",
170
+ }
171
+
172
+
173
+ def main():
174
+ parser = argparse.ArgumentParser(description="OpenTelemetry Observability & Log Hygiene Sentinel")
175
+ parser.add_argument("--sample", action="store_true", help="Run self-verifying sample observability audit")
176
+ args = parser.parse_args()
177
+
178
+ print("======================================================================")
179
+ print(" OPENTELEMETRY OBSERVABILITY & LOG HYGIENE SENTINEL")
180
+ print("======================================================================")
181
+
182
+ # 1. Distributed Trace Continuity
183
+ print("\n[1] Evaluating OpenTelemetry Distributed Trace Continuity...")
184
+ trace_id = "4bf92f3577b34da6a3ce929d0e0e4736"
185
+ sample_spans = [
186
+ {"trace_id": trace_id, "span_id": "0000000000000001", "parent_span_id": None, "service_name": "web-frontend", "name": "HTTP GET /checkout"},
187
+ {"trace_id": trace_id, "span_id": "0000000000000002", "parent_span_id": "0000000000000001", "service_name": "api-gateway", "name": "RouteRequest"},
188
+ {"trace_id": trace_id, "span_id": "0000000000000003", "parent_span_id": "0000000000000002", "service_name": "order-service", "name": "CreateOrder"},
189
+ {"trace_id": trace_id, "span_id": "0000000000000004", "parent_span_id": "0000000000000003", "service_name": "payment-gateway", "name": "ChargeCard"},
190
+ ]
191
+ expected_chain = ["web-frontend", "api-gateway", "order-service", "payment-gateway"]
192
+
193
+ res_trace = OpenTelemetryTraceVerifier.verify_trace_continuity(trace_id, sample_spans, expected_chain)
194
+ print(f" -> Trace ID: {res_trace['trace_id']}")
195
+ print(f" -> Observed Services: {', '.join(res_trace['observed_services'])}")
196
+ print(f" -> Trace Continuity Status: {'🟢 PASSED' if res_trace['status'] == 'PASSED' else '🔴 FAILED'}")
197
+
198
+ # 2. Span Semantic Attributes Verification
199
+ print("\n[2] Verifying Semantic Attributes on Payment Span...")
200
+ payment_span = {
201
+ "span_id": "0000000000000004",
202
+ "attributes": {
203
+ "http.status_code": 200,
204
+ "http.method": "POST",
205
+ "rpc.system": "grpc",
206
+ }
207
+ }
208
+ valid_attrs, missing = OpenTelemetryTraceVerifier.verify_span_attributes(payment_span, ["http.status_code", "http.method"])
209
+ print(f" -> Semantic Attributes Compliance: {'✅ PASS' if valid_attrs else '❌ FAIL'}")
210
+
211
+ # 3. Log Hygiene & PII Leak Scanner
212
+ print("\n[3] Scanning Application Logs for PII & Credential Leaks...")
213
+ clean_log = """
214
+ 2026-11-17T10:00:00Z INFO [order-service] Processing order ORD_1001 for customer CUST_88
215
+ 2026-11-17T10:00:01Z INFO [payment-service] Charging card ending in 1111, auth_code: AUTH_OK
216
+ """
217
+ res_log = LogHygieneSentinel.scan_log_content(clean_log)
218
+ print(f" -> Clean Log Scan Result: {'🟢 PASSED (Zero Leaks)' if res_log['status'] == 'PASSED' else '🔴 FAILED'}")
219
+
220
+ dirty_log = """
221
+ 2026-11-17T10:00:00Z ERROR [auth-service] Failed login for user admin with password=MySecretPassword123!
222
+ 2026-11-17T10:00:01Z DEBUG [checkout] Customer entered card 4111111111111111 with cvv=999
223
+ """
224
+ res_dirty = LogHygieneSentinel.scan_log_content(dirty_log)
225
+ print(f" -> Vulnerable Log Scan Result: {'🟢 PASSED' if res_dirty['status'] == 'PASSED' else '🔴 FAILED'} ({res_dirty['leaks_detected']} leaks detected)")
226
+ for lk in res_dirty["leaks"]:
227
+ print(f" - [Line {lk['line']}] [{lk['type']}] {lk['snippet']}")
228
+
229
+ print("\n======================================================================")
230
+ print(" OBSERVABILITY SENTINEL VERIFIED (OPENTELEMETRY COMPLIANT)")
231
+ print("======================================================================")
232
+
233
+
234
+ if __name__ == "__main__":
235
+ main()