-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_live_guardian_extended.py
More file actions
829 lines (707 loc) · 35.5 KB
/
Copy pathtest_live_guardian_extended.py
File metadata and controls
829 lines (707 loc) · 35.5 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
"""[FACT] Extended tests for live_guardian.py to reach 80% coverage.
[HYPOTHESIS] Testing additional endpoints improves coverage.
[ASSUMPTION] FastAPI TestClient allows synchronous testing of async endpoints.
"""
from pathlib import Path
import live_demo_server as standalone_live_demo_server
from fastapi.testclient import TestClient
import helix_code.live_demo_server as live_demo_server
import helix_code.live_guardian as live_guardian
from helix_code.request_limits import SlidingWindowRateLimiter
app = live_guardian.app
class TestLiveGuardianExtended:
"""[FACT] Extended test suite for live_guardian endpoints."""
def test_root_endpoint(self) -> None:
"""[FACT] Root endpoint returns demo HTML."""
with TestClient(app) as client:
response = client.get("/")
assert response.status_code == 200
assert "text/html" in response.headers["content-type"]
def test_favicon_endpoint(self) -> None:
"""[FACT] Favicon endpoint returns 204."""
with TestClient(app) as client:
response = client.get("/favicon.ico")
# Returns 204 No Content
assert response.status_code in [204, 404]
def test_api_receipts_endpoint(self) -> None:
"""[FACT] /api/receipts returns receipts list."""
with TestClient(app) as client:
response = client.get("/api/receipts")
assert response.status_code == 200
data = response.json()
assert "receipts" in data
assert "stats" in data
def test_api_receipts_with_limit(self) -> None:
"""[FACT] /api/receipts respects limit parameter."""
with TestClient(app) as client:
response = client.get("/api/receipts?limit=5")
assert response.status_code == 200
data = response.json()
assert len(data["receipts"]) <= 5
def test_validate_endpoint_empty_text(self) -> None:
"""[FACT] POST /validate handles empty text."""
with TestClient(app) as client:
response = client.post("/validate", params={"text": ""})
assert response.status_code == 200
# Empty text should be compliant (no violations)
data = response.json()
assert "compliant" in data
def test_validate_endpoint_compliant(self) -> None:
"""[FACT] POST /validate with compliant text."""
with TestClient(app) as client:
response = client.post("/validate", params={"text": "[FACT] The sky is blue."})
assert response.status_code == 200
data = response.json()
assert data["compliant"] is True
assert data["epistemic_markers"]["fact"] is True
def test_validate_endpoint_agency_violation(self) -> None:
"""[FACT] POST /validate detects agency violations."""
with TestClient(app) as client:
response = client.post("/validate", params={"text": "I will take control."})
assert response.status_code == 200
data = response.json()
assert len(data["agency_violations"]) > 0
def test_validate_endpoint_long_text(self) -> None:
"""[FACT] POST /validate handles long text."""
long_text = "[FACT] " + "This is a test sentence with proper labeling. " * 5
with TestClient(app) as client:
response = client.post("/validate", params={"text": long_text})
assert response.status_code == 200
data = response.json()
assert "compliant" in data
assert "epistemic_markers" in data
class TestGeminiStatusEndpoint:
"""[FACT] Tests for Gemini API status endpoint."""
def test_gemini_status_endpoint(self) -> None:
"""[FACT] /api/gemini-status returns API configuration."""
with TestClient(app) as client:
response = client.get("/api/gemini-status")
assert response.status_code == 200
data = response.json()
assert "available" in data
assert "mode" in data
# Model info only present when available
if data["available"]:
assert "model" in data
class TestHealthEndpointVariations:
"""[FACT] Test health endpoint variations."""
def test_health_endpoint_post(self) -> None:
"""[FACT] POST to health returns method not allowed."""
with TestClient(app) as client:
response = client.post("/health")
assert response.status_code == 405 # Method Not Allowed
def test_health_endpoint_head(self) -> None:
"""[FACT] HEAD to health returns 200 or 405."""
with TestClient(app) as client:
response = client.head("/health")
assert response.status_code in [200, 405] # Method may not be allowed
class TestApiInfoEndpoint:
"""[FACT] Test API info endpoint."""
def test_api_info_structure(self) -> None:
"""[FACT] /api returns correct structure."""
with TestClient(app) as client:
response = client.get("/api")
assert response.status_code == 200
data = response.json()
assert data["service"] == "Constitutional Guardian"
assert data["node"] == "GCS-GUARDIAN"
assert data["status"] == "RATIFIED"
assert "endpoints" in data
assert data["endpoints"]["metrics"] == "/metrics"
assert data["endpoints"]["incident_board"] == "/incidents"
assert data["endpoints"]["incident_api"] == "/api/incidents"
class TestRuntimeConfigEndpoint:
"""[FACT] Test runtime config verification endpoint."""
def test_runtime_config_defaults(self) -> None:
"""[FACT] Runtime config returns expected default model values."""
with TestClient(app) as client:
response = client.get("/api/runtime-config")
assert response.status_code == 200
data = response.json()
assert (
data["models"]["gemini_live_model"]
== "gemini-2.5-flash-native-audio-preview-12-2025"
)
assert data["models"]["gemini_text_model"] == "gemini-3.1-pro-preview"
assert "auth" in data
assert "limits" in data
assert "federation" in data
assert "secrets" in data
assert "backend" in data["secrets"]
assert "vault_configured" in data["secrets"]
assert "receipts" in data
assert "persistence_mode" in data["receipts"]
assert "model_armor" in data
assert data["model_armor"]["enabled"] is False
def test_runtime_config_reflects_env(self, monkeypatch) -> None:
"""[FACT] Runtime config reflects safe env overrides."""
monkeypatch.setenv("GEMINI_LIVE_MODEL", "gemini-3.1-pro-preview")
monkeypatch.setenv("GEMINI_TEXT_MODEL", "gemini-3.1-pro-preview")
monkeypatch.setenv("AUDIO_AUDIT_TOKEN", "set")
monkeypatch.setenv(
"AUDIO_AUDIT_ALLOWED_ORIGINS",
"https://helixprojectai.com,https://app.helixprojectai.com",
)
monkeypatch.setenv("HELIX_MAX_AUDIO_CHUNK_BYTES", "262144")
monkeypatch.setenv("HELIX_ALLOWED_ORIGINS", "https://console.helixprojectai.com")
monkeypatch.setenv("HELIX_MODEL_ARMOR_ENABLED", "true")
monkeypatch.setenv("HELIX_MODEL_ARMOR_ENFORCEMENT", "soft_block")
monkeypatch.setenv("HELIX_MODEL_ARMOR_FAILURE_MODE", "closed")
monkeypatch.setenv("HELIX_MODEL_ARMOR_TIMEOUT_MS", "4321")
monkeypatch.setenv("HELIX_MODEL_ARMOR_ENDPOINT", "https://modelarmor.example")
monkeypatch.setenv("HELIX_MODEL_ARMOR_TEMPLATE_INPUT", "projects/test/input")
monkeypatch.setenv("HELIX_MODEL_ARMOR_TEMPLATE_OUTPUT", "projects/test/output")
with TestClient(app) as client:
response = client.get("/api/runtime-config")
assert response.status_code == 200
data = response.json()
assert data["auth"]["audio_audit_token_required"] is True
assert len(data["auth"]["audio_audit_allowed_origins"]) == 2
assert data["auth"]["guardian_allowed_origins"] == [
"https://console.helixprojectai.com"
]
assert data["auth"]["guardian_origin_enforced"] is True
assert data["limits"]["max_audio_chunk_bytes"] == 262144
assert data["model_armor"]["enabled"] is True
assert data["model_armor"]["enforcement"] == "soft_block"
assert data["model_armor"]["failure_mode"] == "closed"
assert data["model_armor"]["timeout_ms"] == 4321
assert data["model_armor"]["endpoint_configured"] is True
assert data["model_armor"]["input_template_configured"] is True
assert data["model_armor"]["output_template_configured"] is True
class TestSecurityTransparencyEndpoint:
"""[FACT] Test security transparency env wiring."""
def test_security_transparency_reflects_env(self, monkeypatch) -> None:
"""[FACT] API reflects scan metadata when provided by deployment pipeline."""
monkeypatch.setenv("SECURITY_SCAN_TIMESTAMP", "2026-03-07T18:15:00Z")
monkeypatch.setenv("SECURITY_TEST_STATUS", "186/186 passing")
monkeypatch.setenv("SECURITY_CHECK_BANDIT", "passing")
monkeypatch.setenv("SECURITY_ARTIFACT_ANALYSIS_STATUS", "clean")
monkeypatch.setenv("SECURITY_ARTIFACT_ANALYSIS_TIMESTAMP", "2026-03-08T11:29:23Z")
monkeypatch.setenv(
"SECURITY_ARTIFACT_IMAGE_URI",
"us-central1-docker.pkg.dev/helix-ai-deploy/helix-repo/constitutional-guardian@sha256:a68ebdc0075e40d0b734b3c2e220cb277e6d84e19843031a5ded68e7013a5c77",
)
with TestClient(app) as client:
response = client.get("/api/security-transparency")
assert response.status_code == 200
data = response.json()
assert data["latest_scan_timestamp"] == "2026-03-07T18:15:00Z"
assert data["test_status"] == "186/186 passing"
assert data["checks"]["bandit"] == "passing"
assert data["artifact_analysis"]["status"] == "clean"
assert data["artifact_analysis"]["scan_timestamp"] == "2026-03-08T11:29:23Z"
assert "sha256:a68ebdc0" in data["artifact_analysis"]["image_uri"]
class TestAuditDashboardEndpoint:
"""[FACT] Test audit dashboard API and HTML surface."""
def test_audit_dashboard_api_structure(self) -> None:
"""[FACT] /api/audit-dashboard returns summary payload."""
with TestClient(app) as client:
response = client.get("/api/audit-dashboard")
assert response.status_code == 200
data = response.json()
assert "snapshot_at" in data
assert "receipts" in data
assert "drift_counts" in data
assert "metrics" in data
assert "model_armor" in data
assert "storage" in data
assert "recent_receipts" in data
assert "incidents" in data
def test_audit_dashboard_page(self) -> None:
"""[FACT] /audit-dashboard serves an HTML compliance view."""
with TestClient(app) as client:
response = client.get("/audit-dashboard")
assert response.status_code == 200
assert "text/html" in response.headers["content-type"]
assert "Audit Trail Dashboard" in response.text
def test_audit_dashboard_exposes_model_armor_summary(self, monkeypatch) -> None:
"""[FACT] Audit dashboard reports Model Armor metrics and blocked receipts."""
patched_metrics = live_demo_server.LiveMetrics()
patched_metrics.record_model_armor_payload(
{
"input": {
"blocked": False,
"action": "inspect",
"findings": [{"category": "prompt_injection"}],
},
"output": {
"blocked": True,
"action": "error_block",
"findings": [{"category": "prompt_injection"}],
},
}
)
patched_store = live_demo_server.ReceiptStore(max_receipts=10)
patched_store.add(
live_demo_server.Receipt(
"ma-1",
"2026-03-13T00:00:00",
"blocked",
False,
"DRIFT-A",
"session-1",
{
"output": {
"blocked": True,
"action": "error_block",
"findings": [{"category": "prompt_injection"}],
}
},
)
)
monkeypatch.setattr(live_demo_server, "metrics", patched_metrics)
monkeypatch.setattr(standalone_live_demo_server, "metrics", patched_metrics)
monkeypatch.setattr(live_demo_server, "receipt_store", patched_store)
monkeypatch.setattr(standalone_live_demo_server, "receipt_store", patched_store)
with TestClient(app) as client:
response = client.get("/api/audit-dashboard")
assert response.status_code == 200
data = response.json()
assert data["model_armor"]["block_count"] == 1
assert data["model_armor"]["blocked_receipt_count"] == 1
assert data["model_armor"]["findings"]["prompt_injection"] == 2
assert data["recent_receipts"][-1]["model_armor"]["output"]["blocked"] is True
class TestIncidentDashboardEndpoint:
"""[FACT] Test operator incident API and HTML surface."""
def test_incident_api_structure(self) -> None:
live_guardian._reset_incident_triage_state()
with TestClient(app) as client:
response = client.get("/api/incidents")
assert response.status_code == 200
data = response.json()
assert "snapshot_at" in data
assert "summary" in data
assert "incidents" in data
assert "active_total" in data["summary"]
assert "open_total" in data["summary"]
assert "acknowledged_total" in data["summary"]
assert "all_clear" in data["summary"]
assert "category_totals" in data["summary"]
def test_incident_api_surfaces_active_signals(self, monkeypatch) -> None:
monkeypatch.setenv("HELIX_ENV", "production")
monkeypatch.setenv("SECURITY_ARTIFACT_ANALYSIS_STATUS", "unverified")
monkeypatch.setenv(
"SECURITY_ARTIFACT_IMAGE_URI",
"us-central1-docker.pkg.dev/helix-ai-deploy/helix-repo/constitutional-guardian@sha256:test",
)
patched_metrics = live_demo_server.LiveMetrics()
patched_metrics.record_auth_failure("operator")
monkeypatch.setattr(live_demo_server, "metrics", patched_metrics)
monkeypatch.setattr(standalone_live_demo_server, "metrics", patched_metrics)
with TestClient(app) as client:
response = client.get("/api/incidents")
assert response.status_code == 200
data = response.json()
incident_keys = {incident["incident_key"] for incident in data["incidents"]}
assert "artifact-verification" in incident_keys
assert "operator-auth-failure" in incident_keys
artifact = next(
incident
for incident in data["incidents"]
if incident["incident_key"] == "artifact-verification"
)
assert artifact["id"].startswith("artifact-verification:")
assert artifact["category"] == "security"
assert artifact["investigate_url"] == "/security-transparency"
assert data["summary"]["active_total"] >= 2
def test_incident_dashboard_page(self) -> None:
with TestClient(app) as client:
response = client.get("/incidents")
assert response.status_code == 200
assert "Operator Incident Board" in response.text
assert "/api/incidents" in response.text
assert "Selected Incident" in response.text
assert "Acknowledge Incident" in response.text
assert "data-filter='warn'" in response.text
def test_incident_api_surfaces_model_armor_signals(self, monkeypatch) -> None:
patched_metrics = live_demo_server.LiveMetrics()
patched_metrics.record_model_armor_payload(
{
"input": {
"blocked": True,
"action": "error_block",
"findings": [{"category": "prompt_injection"}],
}
}
)
monkeypatch.setattr(live_demo_server, "metrics", patched_metrics)
monkeypatch.setattr(standalone_live_demo_server, "metrics", patched_metrics)
snapshot = live_guardian._incident_snapshot(limit=20)
incident_keys = {incident["incident_key"] for incident in snapshot["incidents"]}
assert "model-armor-blocks" in incident_keys
assert "model-armor-prompt-injection" in incident_keys
def test_incident_acknowledge_and_reopen_flow(self, monkeypatch) -> None:
monkeypatch.setenv("HELIX_ENV", "production")
monkeypatch.setenv("SECURITY_ARTIFACT_ANALYSIS_STATUS", "unverified")
monkeypatch.setenv(
"SECURITY_ARTIFACT_IMAGE_URI",
"us-central1-docker.pkg.dev/helix-ai-deploy/helix-repo/constitutional-guardian@sha256:test",
)
live_guardian._reset_incident_triage_state()
with TestClient(app) as client:
incidents = client.get("/api/incidents")
assert incidents.status_code == 200
artifact = next(
incident
for incident in incidents.json()["incidents"]
if incident["incident_key"] == "artifact-verification"
)
artifact_id = artifact["id"]
acknowledge = client.post(f"/api/incidents/{artifact_id}/acknowledge")
assert acknowledge.status_code == 200
acknowledged = acknowledge.json()
assert acknowledged["incident"]["triage_status"] == "acknowledged"
assert acknowledged["summary"]["acknowledged_total"] == 1
assert acknowledged["summary"]["open_total"] >= 0
incidents = client.get("/api/incidents")
assert incidents.status_code == 200
artifact = next(
incident
for incident in incidents.json()["incidents"]
if incident["incident_key"] == "artifact-verification"
)
assert artifact["triage_status"] == "acknowledged"
assert artifact["triaged_at"] is not None
reopen = client.post(f"/api/incidents/{artifact_id}/reopen")
assert reopen.status_code == 200
reopened = reopen.json()
assert reopened["incident"]["triage_status"] == "open"
assert reopened["summary"]["acknowledged_total"] == 0
def test_incident_triage_status_validation(self) -> None:
live_guardian._reset_incident_triage_state()
try:
live_guardian._set_incident_triage_status("artifact-verification", "closed")
except ValueError as exc:
assert "Unsupported incident triage status" in str(exc)
else:
raise AssertionError("Expected ValueError for unsupported triage status")
def test_incident_triage_entry_limit(self, tmp_path: Path) -> None:
persistence = live_guardian.IncidentTriagePersistenceManager(
local_path=tmp_path / "triage.json", gcs_bucket=""
)
store = live_guardian.IncidentTriageStore(max_entries=3, persistence=persistence)
store.reset()
for index in range(4):
store.set_status(f"incident-{index}", "acknowledged")
snapshot = store.snapshot()
assert len(snapshot) == 3
assert "incident-0" not in snapshot
assert "incident-3" in snapshot
def test_incident_id_changes_when_state_changes(self, monkeypatch) -> None:
monkeypatch.setenv("HELIX_ENV", "production")
monkeypatch.setenv("SECURITY_ARTIFACT_ANALYSIS_STATUS", "clean")
patched_metrics = live_demo_server.LiveMetrics()
patched_metrics.record_auth_failure("operator")
monkeypatch.setattr(live_demo_server, "metrics", patched_metrics)
monkeypatch.setattr(standalone_live_demo_server, "metrics", patched_metrics)
first = live_guardian._incident_snapshot(limit=20)
first_auth = next(
incident
for incident in first["incidents"]
if incident["incident_key"] == "operator-auth-failure"
)
patched_metrics.record_auth_failure("operator")
second = live_guardian._incident_snapshot(limit=20)
second_auth = next(
incident
for incident in second["incidents"]
if incident["incident_key"] == "operator-auth-failure"
)
assert first_auth["id"] != second_auth["id"]
def test_incident_triage_persists_across_store_instances(self, tmp_path: Path) -> None:
local_path = tmp_path / "triage.json"
first_store = live_guardian.IncidentTriageStore(
persistence=live_guardian.IncidentTriagePersistenceManager(
local_path=local_path, gcs_bucket=""
)
)
first_store.reset()
fields = first_store.set_status("incident-persisted", "acknowledged")
assert fields["triage_status"] == "acknowledged"
second_store = live_guardian.IncidentTriageStore(
persistence=live_guardian.IncidentTriagePersistenceManager(
local_path=local_path, gcs_bucket=""
)
)
restored = second_store.snapshot()
assert restored["incident-persisted"]["status"] == "acknowledged"
class TestGuardianOriginPolicy:
"""[FACT] Test Guardian CORS and WebSocket origin policy helpers."""
def test_guardian_origin_is_not_enforced_in_non_production_without_allowlist(
self, monkeypatch
) -> None:
monkeypatch.delenv("HELIX_ALLOWED_ORIGINS", raising=False)
monkeypatch.setenv("HELIX_ENV", "development")
assert live_guardian._guardian_origin_enforced() is False
assert (
live_guardian._is_guardian_websocket_origin_allowed({"origin": "https://evil.example"})
is True
)
def test_guardian_origin_requires_same_origin_in_production(self, monkeypatch) -> None:
monkeypatch.delenv("HELIX_ALLOWED_ORIGINS", raising=False)
monkeypatch.setenv("HELIX_ENV", "production")
assert live_guardian._guardian_origin_enforced() is True
assert (
live_guardian._is_guardian_websocket_origin_allowed(
{
"origin": "https://constitutional-guardian.example",
"host": "constitutional-guardian.example",
"x-forwarded-proto": "https",
}
)
is True
)
assert (
live_guardian._is_guardian_websocket_origin_allowed(
{
"origin": "https://evil.example",
"host": "constitutional-guardian.example",
"x-forwarded-proto": "https",
}
)
is False
)
assert (
live_guardian._is_guardian_websocket_origin_allowed(
{"host": "constitutional-guardian.example"}
)
is False
)
def test_guardian_origin_honors_explicit_allowlist(self, monkeypatch) -> None:
monkeypatch.setenv(
"HELIX_ALLOWED_ORIGINS",
"https://console.helixprojectai.com,https://app.helixprojectai.com",
)
monkeypatch.setenv("HELIX_ENV", "production")
assert live_guardian._guardian_origin_enforced() is True
assert (
live_guardian._is_guardian_websocket_origin_allowed(
{"origin": "https://console.helixprojectai.com"}
)
is True
)
assert (
live_guardian._is_guardian_websocket_origin_allowed({"origin": "https://evil.example"})
is False
)
class TestProtectedOperationalEndpoints:
"""[FACT] Test admin token protection for operational surfaces."""
def test_runtime_config_requires_admin_token(self, monkeypatch) -> None:
"""[FACT] Runtime config rejects unauthenticated requests when token is set."""
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
patched_metrics = live_demo_server.LiveMetrics()
monkeypatch.setattr(live_demo_server, "metrics", patched_metrics)
monkeypatch.setattr(standalone_live_demo_server, "metrics", patched_metrics)
with TestClient(app) as client:
response = client.get("/api/runtime-config")
assert response.status_code == 401
assert live_demo_server.metrics.operator_auth_failure_count == 0
def test_runtime_config_counts_invalid_admin_token_attempts(self, monkeypatch) -> None:
"""[FACT] Operator auth metrics count wrong tokens but ignore missing credentials."""
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
patched_metrics = live_demo_server.LiveMetrics()
monkeypatch.setattr(live_demo_server, "metrics", patched_metrics)
monkeypatch.setattr(standalone_live_demo_server, "metrics", patched_metrics)
with TestClient(app) as client:
response = client.get(
"/api/runtime-config",
headers={"X-Helix-Admin-Token": "wrong-token"},
)
assert response.status_code == 401
assert live_demo_server.metrics.operator_auth_failure_count == 1
def test_runtime_config_accepts_bearer_admin_token(self, monkeypatch) -> None:
"""[FACT] Runtime config accepts bearer authorization."""
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
with TestClient(app) as client:
response = client.get(
"/api/runtime-config",
headers={"Authorization": "Bearer secret-token"},
)
assert response.status_code == 200
def test_audit_dashboard_page_returns_login_form_when_token_missing(self, monkeypatch) -> None:
"""[FACT] Protected dashboard HTML returns a login form when no admin session exists."""
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
with TestClient(app) as client:
response = client.get("/audit-dashboard")
assert response.status_code == 401
assert "Admin Access Required" in response.text
def test_root_demo_page_can_be_public_when_enabled(self, monkeypatch) -> None:
"""[FACT] Public demo mode opens only the root demo surface."""
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
monkeypatch.setenv("HELIX_PUBLIC_DEMO", "true")
with TestClient(app) as client:
response = client.get("/")
assert response.status_code == 200
assert "CONSTITUTIONAL GUARDIAN" in response.text
assert "LIVE v1.5.0" in response.text
def test_runtime_config_reports_public_demo_flag(self, monkeypatch) -> None:
"""[FACT] Runtime config reports whether public demo mode is enabled."""
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
monkeypatch.setenv("HELIX_PUBLIC_DEMO", "true")
with TestClient(app) as client:
response = client.get(
"/api/runtime-config",
headers={"X-Helix-Admin-Token": "secret-token"},
)
assert response.status_code == 200
assert response.json()["auth"]["public_demo_enabled"] is True
def test_public_demo_disables_demo_websocket_admin_gate(self, monkeypatch) -> None:
"""[FACT] Public demo mode removes admin auth from the demo websocket only."""
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
monkeypatch.setenv("HELIX_PUBLIC_DEMO", "true")
assert live_guardian._demo_requires_admin_auth() is False
def test_receipts_api_accepts_custom_admin_header(self, monkeypatch) -> None:
"""[FACT] Receipts API accepts custom admin header."""
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
with TestClient(app) as client:
response = client.get(
"/api/receipts",
headers={"X-Helix-Admin-Token": "secret-token"},
)
assert response.status_code == 200
def test_metrics_requires_admin_token(self, monkeypatch) -> None:
"""[FACT] Metrics export rejects unauthenticated requests when admin auth is enabled."""
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
with TestClient(app) as client:
response = client.get("/metrics")
assert response.status_code == 401
def test_metrics_returns_prometheus_payload(self, monkeypatch) -> None:
"""[FACT] Metrics export returns authenticated Prometheus text."""
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
monkeypatch.setenv("SECURITY_ARTIFACT_ANALYSIS_STATUS", "clean")
monkeypatch.setenv(
"SECURITY_ARTIFACT_IMAGE_URI",
"us-central1-docker.pkg.dev/helix-ai-deploy/helix-repo/constitutional-guardian@sha256:test",
)
patched_metrics = live_demo_server.LiveMetrics()
patched_metrics.record_rate_limit("operator")
patched_metrics.record_auth_failure("operator")
patched_metrics.record_model_armor_payload(
{
"input": {
"blocked": False,
"action": "inspect",
"findings": [{"category": "prompt_injection"}],
},
"output": {
"blocked": True,
"action": "error_block",
"findings": [{"category": "sensitive_data"}],
},
}
)
monkeypatch.setattr(live_demo_server, "metrics", patched_metrics)
monkeypatch.setattr(standalone_live_demo_server, "metrics", patched_metrics)
with TestClient(app) as client:
response = client.get(
"/metrics",
headers={"X-Helix-Admin-Token": "secret-token"},
)
assert response.status_code == 200
assert "text/plain" in response.headers["content-type"]
assert "helix_requests_total" in response.text
assert "helix_receipt_storage_backend" in response.text
assert 'helix_security_events_total{event="operator_auth_failure"}' in response.text
assert 'helix_security_events_total{event="operator_rate_limit"}' in response.text
assert "helix_model_armor_requests_total 2" in response.text
assert "helix_model_armor_blocks_total 1" in response.text
assert 'helix_model_armor_findings_total{category="prompt_injection"} 1' in response.text
assert 'helix_model_armor_findings_total{category="sensitive_data"} 1' in response.text
assert (
'helix_artifact_analysis_state{image_uri="us-central1-docker.pkg.dev/helix-ai-deploy/helix-repo/constitutional-guardian@sha256:test",status="clean"} 1'
in response.text
)
def test_runtime_config_returns_503_when_admin_enforced_without_token(
self, monkeypatch
) -> None:
"""[FACT] Enforced admin mode fails closed when the token is missing."""
monkeypatch.delenv("HELIX_ADMIN_TOKEN", raising=False)
monkeypatch.setenv("HELIX_ENFORCE_ADMIN_TOKEN", "true")
with TestClient(app) as client:
response = client.get("/api/runtime-config")
assert response.status_code == 503
def test_protected_html_returns_503_when_admin_enforced_without_token(
self, monkeypatch
) -> None:
"""[FACT] Protected HTML surfaces fail closed when admin auth is enforced but unset."""
monkeypatch.delenv("HELIX_ADMIN_TOKEN", raising=False)
monkeypatch.setenv("HELIX_ENFORCE_ADMIN_TOKEN", "true")
with TestClient(app) as client:
response = client.get("/audit-dashboard")
assert response.status_code == 503
def test_guardian_websocket_auth_counts_only_wrong_tokens(self, monkeypatch) -> None:
"""[FACT] Guardian WebSocket auth metrics ignore missing credentials but count wrong tokens."""
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
patched_metrics = live_demo_server.LiveMetrics()
monkeypatch.setattr(live_demo_server, "metrics", patched_metrics)
monkeypatch.setattr(standalone_live_demo_server, "metrics", patched_metrics)
assert live_guardian._require_admin_websocket({}) is False
assert live_demo_server.metrics.websocket_auth_failure_count == 0
assert (
live_guardian._require_admin_websocket({"x-helix-admin-token": "wrong-token"}) is False
)
assert live_demo_server.metrics.websocket_auth_failure_count == 1
class TestOperatorRateLimiting:
"""[FACT] Test operator and auth throttling behavior."""
def test_runtime_config_rate_limits_operator_requests(self, monkeypatch) -> None:
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
monkeypatch.setenv("HELIX_OPERATOR_RATE_LIMIT_MAX_REQUESTS", "1")
monkeypatch.setenv("HELIX_OPERATOR_RATE_LIMIT_WINDOW_SECONDS", "60")
monkeypatch.setattr(
live_guardian,
"operator_rate_limiter",
SlidingWindowRateLimiter(now_fn=lambda: 100.0),
)
with TestClient(app) as client:
first = client.get(
"/api/runtime-config",
headers={"X-Helix-Admin-Token": "secret-token"},
)
second = client.get(
"/api/runtime-config",
headers={"X-Helix-Admin-Token": "secret-token"},
)
assert first.status_code == 200
assert second.status_code == 429
assert second.json()["detail"] == "Rate limit exceeded for operator"
def test_admin_login_rate_limits_repeated_attempts(self, monkeypatch) -> None:
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
monkeypatch.setenv("HELIX_AUTH_RATE_LIMIT_MAX_ATTEMPTS", "1")
monkeypatch.setenv("HELIX_AUTH_RATE_LIMIT_WINDOW_SECONDS", "300")
monkeypatch.setattr(
live_guardian,
"auth_rate_limiter",
SlidingWindowRateLimiter(now_fn=lambda: 200.0),
)
with TestClient(app) as client:
first = client.post(
"/auth/admin",
data={"token": "wrong-token", "next": "/audit-dashboard"},
)
second = client.post(
"/auth/admin",
data={"token": "wrong-token", "next": "/audit-dashboard"},
)
assert first.status_code == 401
assert second.status_code == 429
assert second.json()["detail"] == "Rate limit exceeded for auth"
class TestAdminLoginFlow:
"""[FACT] Test browser-oriented admin session flow for protected HTML pages."""
def test_admin_login_sets_cookie_for_dashboard(self, monkeypatch) -> None:
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
with TestClient(app) as client:
login = client.post(
"/auth/admin",
data={"token": "secret-token", "next": "/audit-dashboard"},
follow_redirects=False,
)
assert login.status_code == 303
response = client.get("/audit-dashboard")
assert response.status_code == 200
assert "Audit Trail Dashboard" in response.text
def test_query_param_token_is_rejected_for_api(self, monkeypatch) -> None:
monkeypatch.setenv("HELIX_ADMIN_TOKEN", "secret-token")
with TestClient(app) as client:
response = client.get("/api/runtime-config?token=secret-token")
assert response.status_code == 401