-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebapp.py
More file actions
1626 lines (1422 loc) · 61.5 KB
/
Copy pathwebapp.py
File metadata and controls
1626 lines (1422 loc) · 61.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
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
from __future__ import annotations
import hmac
import json
import os
import time
from contextlib import asynccontextmanager
from datetime import UTC, datetime
from typing import Any, Literal
from uuid import uuid4
from fastapi import BackgroundTasks, FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, PlainTextResponse, RedirectResponse
from pydantic import BaseModel, ConfigDict
from sentinel.config import SentinelSettings
from sentinel.connectivity import run_live_connectivity_checks
from sentinel.credentials import (
OAuthTokenStoreError,
missing_live_credentials,
missing_live_credentials_without_oauth_store,
resolve_settings,
save_datadog_oauth_payload,
save_github_oauth_payload,
save_slack_oauth_payload,
token_source_status,
)
from sentinel.errors import ToolExecutionError, redact_sensitive_text
from sentinel.live_clients import LiveProviderClients
from sentinel.models import ApprovalCommand, AuditEvent, InvestigationState, InvestigationStatus
from sentinel.oauth import OAuthManager, verify_pagerduty_signature
from sentinel.orchestrator import SentinelOrchestrator
from sentinel.postgres_store import build_store
from sentinel.rate_limiters import RedisRateLimitBackend
from sentinel.real_tools import LiveToolFactory
from sentinel.slow_query import (
TARGET_USER_ID,
create_orders_user_id_index,
reset_slow_query_database,
run_slow_query,
slow_query_metrics,
slow_query_status,
)
from sentinel.tools import ToolExecutor
_MANAGED_STORE_ATTR = "_sentinel_managed_store"
_PROCESS_STARTED_AT = datetime.now(UTC)
_PROCESS_START_MONOTONIC = time.monotonic()
class WebhookRunResponse(BaseModel):
accepted: bool
investigation_id: str | None = None
message: str
class GenericWebhookRequest(BaseModel):
model_config = ConfigDict(extra="allow")
incident_id: Any | None = None
alert_id: Any | None = None
id: Any | None = None
fingerprint: Any | None = None
source: Any | None = None
affected_service: Any | None = None
affected_services: Any | None = None
service: Any | None = None
service_name: Any | None = None
services: Any | None = None
labels: Any | None = None
alert: Any | None = None
alerts: Any | None = None
commonLabels: Any | None = None
groupLabels: Any | None = None
groupKey: Any | None = None
def normalized_payload(self) -> dict[str, Any]:
payload = self.model_dump(exclude_none=True)
source = payload.get("source")
payload["source"] = source.strip() if isinstance(source, str) and source.strip() else "generic_webhook"
return payload
class ApprovalCommandRequest(BaseModel):
request_id: str
approver_id: str
decision: Literal["approve", "reject"]
idempotency_key: str | None = None
def to_command(self, investigation_id: str) -> ApprovalCommand:
return ApprovalCommand(
request_id=self.request_id,
approver_id=self.approver_id,
decision=self.decision,
idempotency_key=(
self.idempotency_key
or f"{investigation_id}:approval-command:{self.request_id}:{self.approver_id}:{self.decision}"
),
)
class _UnavailableInvestigationStore:
def __init__(self, error: Exception):
self.error = redact_sensitive_text(error, max_length=500)
setattr(self, _MANAGED_STORE_ATTR, True)
def ping(self) -> bool:
return False
def close(self) -> None:
return None
def load_oauth_token(self, provider: str) -> None:
raise RuntimeError(self._message())
def __getattr__(self, name: str):
raise RuntimeError(self._message())
def _message(self) -> str:
return f"Investigation Store unavailable: {self.error}"
def create_app(settings: SentinelSettings | None = None) -> FastAPI:
if settings is None:
try:
settings = SentinelSettings.from_env()
except Exception as exc:
return _invalid_configuration_app(exc)
app = FastAPI(title="SENTINEL live webhook receiver", lifespan=_app_lifespan)
app.state.store = _build_app_store(settings)
@app.get("/health")
def health() -> dict[str, Any]:
store = _get_app_store(app, settings)
credential_status = _credential_status(settings, store)
body = {
"status": "ok",
"missing_live_credentials": credential_status["missing_live_credentials"],
"oauth_store_reachable": credential_status["oauth_store_reachable"],
"webhook_signature_verification": bool(settings.pagerduty_webhook_secret),
"webhook_subscription_bound": bool(settings.pagerduty_webhook_subscription_id),
}
if credential_status["oauth_store_error"]:
body["oauth_store_error"] = credential_status["oauth_store_error"]
return body
@app.get("/metrics")
def prometheus_metrics() -> PlainTextResponse:
return PlainTextResponse(
_prometheus_metrics_body(settings),
media_type="text/plain; version=0.0.4; charset=utf-8",
)
@app.get("/slow-query")
def slow_query(user_id: int = TARGET_USER_ID) -> dict[str, Any]:
result = run_slow_query(user_id)
return {
"ok": True,
"service": settings.default_service,
"query": "SELECT * FROM orders WHERE user_id = ?",
"user_id": result.user_id,
"matched_rows": result.matched_rows,
"duration_ms": round(result.duration_seconds * 1000, 3),
"index_present": result.index_present,
"missing_index": not result.index_present,
"query_plan": result.query_plan,
"row_count": result.row_count,
"scan_repeats": result.scan_repeats,
}
@app.get("/slow-query/status")
def slow_query_status_endpoint() -> dict[str, Any]:
return slow_query_status()
@app.post("/slow-query/reset")
def slow_query_reset(row_count: int = 120_000) -> dict[str, Any]:
return reset_slow_query_database(row_count=row_count)
@app.post("/slow-query/add-index")
def slow_query_add_index(request: Request) -> dict[str, Any]:
_require_operator_auth(settings, request)
return create_orders_user_id_index()
@app.get("/ready")
def ready() -> JSONResponse:
body = _readiness_body(settings, _get_app_store(app, settings))
return JSONResponse(status_code=200 if body["ready"] else 503, content=body)
@app.get("/ready/live")
def live_ready(request: Request) -> JSONResponse:
_require_operator_auth(settings, request)
body = _live_readiness_body(settings, _get_app_store(app, settings))
return JSONResponse(status_code=200 if body["ready"] else 503, content=body)
@app.get("/live/connectivity")
def live_connectivity(request: Request) -> dict[str, Any]:
_require_operator_auth(settings, request)
store = _get_app_store(app, settings)
return run_live_connectivity_checks(settings, store=store).model_dump(mode="json")
@app.get("/oauth/slack/install")
def slack_install(request: Request):
_require_operator_auth(settings, request)
_require_oauth_install_config(settings, "slack")
manager = OAuthManager(settings)
state = manager.issue_state("slack")
store = _get_app_store(app, settings)
_remember_oauth_state(store, "slack", state)
return RedirectResponse(manager.slack_install_url(state=state))
@app.get("/oauth/slack/callback")
def slack_callback(code: str, state: str) -> dict[str, Any]:
manager = OAuthManager(settings)
store = _get_app_store(app, settings)
_consume_issued_oauth_state(manager, store, "slack", state)
try:
payload = manager.exchange_slack_code(code, state)
save_slack_oauth_payload(store, payload)
except ToolExecutionError as exc:
raise _oauth_callback_exception(exc) from exc
except Exception as exc:
raise _store_unavailable_exception(exc) from exc
return {
"ok": True,
"team": payload.get("team", {}).get("name"),
"bot_user_id": payload.get("bot_user_id"),
"token_received": bool(payload.get("access_token")),
}
@app.get("/oauth/github/install")
def github_install(request: Request):
_require_operator_auth(settings, request)
_require_oauth_install_config(settings, "github")
manager = OAuthManager(settings)
state = manager.issue_state("github")
store = _get_app_store(app, settings)
_remember_oauth_state(store, "github", state)
return RedirectResponse(manager.github_install_url(state=state))
@app.get("/oauth/github/callback")
def github_callback(code: str, state: str) -> dict[str, Any]:
manager = OAuthManager(settings)
store = _get_app_store(app, settings)
_consume_issued_oauth_state(manager, store, "github", state)
try:
payload = manager.exchange_github_code(code, state)
save_github_oauth_payload(store, payload)
except ToolExecutionError as exc:
raise _oauth_callback_exception(exc) from exc
except Exception as exc:
raise _store_unavailable_exception(exc) from exc
return {
"ok": True,
"scope": payload.get("scope"),
"token_type": payload.get("token_type"),
"token_received": bool(payload.get("access_token")),
}
@app.get("/oauth/datadog/install")
def datadog_install(request: Request):
_require_operator_auth(settings, request)
_require_oauth_install_config(settings, "datadog")
manager = OAuthManager(settings)
state = manager.issue_state("datadog")
code_verifier = manager.issue_pkce_verifier()
store = _get_app_store(app, settings)
_remember_oauth_state(store, "datadog", state)
_remember_oauth_value(store, "datadog", state, "pkce_verifier", code_verifier)
return RedirectResponse(manager.datadog_install_url(state=state, code_verifier=code_verifier))
@app.get("/oauth/datadog/callback")
def datadog_callback(code: str, state: str, domain: str | None = None) -> dict[str, Any]:
manager = OAuthManager(settings)
store = _get_app_store(app, settings)
_consume_issued_oauth_state(manager, store, "datadog", state)
try:
code_verifier = _lookup_oauth_value(store, "datadog", state, "pkce_verifier")
payload = manager.exchange_datadog_code(code, state, code_verifier=code_verifier, domain=domain)
save_datadog_oauth_payload(store, payload)
except ToolExecutionError as exc:
raise _oauth_callback_exception(exc) from exc
except Exception as exc:
raise _store_unavailable_exception(exc) from exc
return {
"ok": True,
"domain": payload.get("domain"),
"scope": payload.get("scope"),
"token_type": payload.get("token_type"),
"token_received": bool(payload.get("access_token")),
"refresh_token_received": bool(payload.get("refresh_token")),
}
@app.post("/webhooks/pagerduty", response_model=WebhookRunResponse)
async def pagerduty_webhook(request: Request, background_tasks: BackgroundTasks):
raw_body = await request.body()
_require_pagerduty_webhook_signature_config(settings)
if not verify_pagerduty_signature(
raw_body,
request.headers.get("x-pagerduty-signature"),
settings.pagerduty_webhook_secret,
settings.pagerduty_webhook_previous_secret,
):
raise HTTPException(status_code=401, detail="Invalid PagerDuty webhook signature")
_require_pagerduty_webhook_subscription(settings, request)
try:
payload = json.loads(raw_body.decode() or "{}")
except json.JSONDecodeError as exc:
raise HTTPException(status_code=400, detail="PagerDuty webhook body must be valid JSON") from exc
if not isinstance(payload, dict):
raise HTTPException(status_code=400, detail="PagerDuty webhook body must be a JSON object")
actionable_items = _actionable_pagerduty_payload_items(payload)
if not actionable_items:
if _is_pagerduty_test_event(payload):
return WebhookRunResponse(
accepted=True,
investigation_id=None,
message="Accepted PagerDuty webhook test event; no Investigation created",
)
return WebhookRunResponse(
accepted=True,
investigation_id=None,
message="Accepted non-triggering PagerDuty webhook event; no Investigation created",
)
incident_ids = _extract_incident_ids_from_items(actionable_items)
if not incident_ids:
raise HTTPException(status_code=400, detail="PagerDuty webhook did not include an incident id")
if len(incident_ids) > 1:
raise HTTPException(
status_code=400,
detail="PagerDuty webhook contained multiple actionable incidents; send one incident per webhook",
)
incident_id = incident_ids[0]
store = _get_app_store(app, settings)
_require_runtime_ready(
settings,
store,
operation="live investigation",
)
webhook_key = _webhook_idempotency_key("pagerduty", incident_id)
if hasattr(store, "lookup_idempotency_key"):
existing_id = store.lookup_idempotency_key(webhook_key)
if existing_id:
return WebhookRunResponse(
accepted=True,
investigation_id=existing_id,
message=f"Duplicate PagerDuty webhook for {incident_id}; returning existing investigation",
)
_require_runtime_ready(
settings,
store,
operation="live investigation",
provider_preflight=True,
)
services = _extract_webhook_services(actionable_items, settings)
state, created = _create_received_investigation(
store,
payload,
incident_id,
services,
source="pagerduty",
)
if not created:
return WebhookRunResponse(
accepted=True,
investigation_id=state.id,
message=f"Duplicate PagerDuty webhook for {incident_id}; returning existing investigation",
)
background_tasks.add_task(
_run_live_investigation_safely,
settings,
store,
payload,
incident_id,
services,
state.id,
)
return WebhookRunResponse(
accepted=True,
investigation_id=state.id,
message=f"Accepted PagerDuty webhook for {incident_id}",
)
@app.post("/webhooks/generic", response_model=WebhookRunResponse)
async def generic_alert_webhook(request: Request, background_tasks: BackgroundTasks):
try:
payload = await request.json()
except json.JSONDecodeError as exc:
raise HTTPException(status_code=400, detail="Generic webhook body must be valid JSON") from exc
if not isinstance(payload, dict):
raise HTTPException(status_code=400, detail="Generic webhook body must be a JSON object")
payload = GenericWebhookRequest.model_validate(payload).normalized_payload()
incident_id = _extract_generic_incident_id(payload)
if not incident_id:
raise HTTPException(status_code=400, detail="Generic webhook must include incident_id, alert_id, or id")
services = _extract_generic_services(payload, settings)
store = _get_app_store(app, settings)
_require_runtime_ready(
settings,
store,
operation="free-tier live investigation",
)
webhook_key = _webhook_idempotency_key("generic_webhook", incident_id)
if hasattr(store, "lookup_idempotency_key"):
existing_id = store.lookup_idempotency_key(webhook_key)
if existing_id:
return WebhookRunResponse(
accepted=True,
investigation_id=existing_id,
message=f"Duplicate generic webhook for {incident_id}; returning existing investigation",
)
state, created = _create_received_investigation(
store,
payload,
incident_id,
services,
source="generic_webhook",
)
if not created:
return WebhookRunResponse(
accepted=True,
investigation_id=state.id,
message=f"Duplicate generic webhook for {incident_id}; returning existing investigation",
)
background_tasks.add_task(
_run_live_investigation_safely,
settings,
store,
payload,
incident_id,
services,
state.id,
)
return WebhookRunResponse(
accepted=True,
investigation_id=state.id,
message=f"Accepted generic webhook for {incident_id}",
)
@app.get("/investigations/{investigation_id}")
def investigation_status(investigation_id: str, request: Request) -> dict[str, Any]:
_require_operator_auth(settings, request)
store = _get_app_store(app, settings)
try:
state = store.load_state(investigation_id)
except KeyError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
except Exception as exc:
raise _store_unavailable_exception(exc) from exc
return _investigation_response(state)
@app.post("/investigations/{investigation_id}/approval")
def submit_approval(investigation_id: str, command: ApprovalCommandRequest, request: Request) -> dict[str, Any]:
_require_operator_auth(settings, request)
store = _get_app_store(app, settings)
_require_runtime_ready(
settings,
store,
operation="live remediation",
provider_preflight=True,
)
try:
state = _resume_live_investigation_with_approval(
settings,
investigation_id,
command.to_command(investigation_id),
store=store,
)
except KeyError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
except RuntimeError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
except ToolExecutionError as exc:
raise _live_operation_exception(exc) from exc
except Exception as exc:
raise _store_unavailable_exception(exc) from exc
return _investigation_response(state)
@app.post("/live/run/{incident_id}")
def run_live_now(incident_id: str, request: Request, payload: dict[str, Any] | None = None) -> dict[str, Any]:
_require_operator_auth(settings, request)
body = payload or {}
store = _get_app_store(app, settings)
_require_runtime_ready(
settings,
store,
operation="live investigation",
provider_preflight=True,
)
try:
state = _run_live_investigation(
settings,
body,
incident_id,
services=_extract_live_run_services(body, settings),
store=store,
)
except HTTPException:
raise
except ToolExecutionError as exc:
raise _live_operation_exception(exc) from exc
except Exception as exc:
raise _store_unavailable_exception(exc) from exc
return _investigation_response(state)
return app
def _invalid_configuration_app(exc: Exception) -> FastAPI:
app = FastAPI(title="SENTINEL live webhook receiver")
safe_error = redact_sensitive_text(exc, max_length=500)
@app.get("/health")
def invalid_health() -> dict[str, Any]:
return {
"status": "configuration_error",
"ready": False,
"config_error": safe_error,
}
@app.get("/ready")
def invalid_ready() -> JSONResponse:
return JSONResponse(
status_code=503,
content={
"ready": False,
"status": "configuration_error",
"missing_live_credentials": [],
"config_error": safe_error,
},
)
@app.api_route(
"/{path:path}",
methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
)
def invalid_configuration_unavailable(path: str) -> None:
raise HTTPException(
status_code=503,
detail={
"message": "SENTINEL configuration is invalid",
"config_error": safe_error,
},
)
return app
def _readiness_body(settings: SentinelSettings, store: Any) -> dict[str, Any]:
credential_status = _credential_status(settings, store)
missing = credential_status["missing_live_credentials"]
database_reachable = _store_reachable(store)
redis_reachable = _redis_reachable(settings)
is_ready = (
not missing
and database_reachable
and redis_reachable
and credential_status["oauth_store_reachable"]
)
body = {
"ready": is_ready,
"receiver_process": _receiver_process_identity(),
"missing_live_credentials": missing,
"token_sources": credential_status["token_sources"],
"oauth_store_reachable": credential_status["oauth_store_reachable"],
"database_configured": bool(settings.database_url),
"database_reachable": database_reachable,
"redis_configured": bool(settings.redis_url),
"redis_reachable": redis_reachable,
"kubeconfig_configured": bool(settings.existing_kubeconfig),
"webhook_signature_verification": bool(settings.pagerduty_webhook_secret),
"webhook_subscription_bound": bool(settings.pagerduty_webhook_subscription_id),
"operator_authentication": bool(settings.api_token),
}
database_error = _store_error(store)
if database_error:
body["database_error"] = database_error
if credential_status["oauth_store_error"]:
body["oauth_store_error"] = credential_status["oauth_store_error"]
return body
def _live_readiness_body(settings: SentinelSettings, store: Any) -> dict[str, Any]:
base = _readiness_body(settings, store)
if not base["ready"]:
return {
**base,
"base_ready": False,
"provider_preflight_ready": False,
"provider_preflight_skipped": False,
}
if _live_provider_preflight_skipped(settings):
return {
**base,
"base_ready": True,
"provider_preflight_ready": True,
"provider_preflight_skipped": True,
}
report = run_live_connectivity_checks(settings, store=store)
provider_body = report.model_dump(mode="json")
return {
"ready": report.ready,
"base_ready": True,
"provider_preflight_ready": report.ready,
"provider_preflight_skipped": False,
"missing_live_credentials": provider_body["missing_live_credentials"],
"checks": provider_body["checks"],
"base": base,
}
def _credential_status(settings: SentinelSettings, store: Any) -> dict[str, Any]:
try:
missing = missing_live_credentials(settings, store)
oauth_store_error = None
except OAuthTokenStoreError as exc:
missing = missing_live_credentials_without_oauth_store(settings)
oauth_store_error = redact_sensitive_text(exc, max_length=500)
return {
"missing_live_credentials": missing,
"token_sources": token_source_status(settings, store),
"oauth_store_reachable": oauth_store_error is None,
"oauth_store_error": oauth_store_error,
}
def _build_app_store(settings: SentinelSettings):
try:
return _mark_managed_store(build_store(settings.database_url))
except Exception as exc:
return _UnavailableInvestigationStore(exc)
def _mark_managed_store(store: Any):
try:
setattr(store, _MANAGED_STORE_ATTR, True)
except Exception:
pass
return store
@asynccontextmanager
async def _app_lifespan(app: FastAPI):
try:
yield
finally:
_close_resource(getattr(app.state, "store", None))
def _get_app_store(app: FastAPI, settings: SentinelSettings):
store = app.state.store
if not _managed_store_needs_refresh(store):
return store
refreshed = _build_app_store(settings)
if refreshed is not store:
_close_resource(store)
app.state.store = refreshed
return refreshed
def _managed_store_needs_refresh(store: Any) -> bool:
if isinstance(store, _UnavailableInvestigationStore):
return True
if not bool(getattr(store, _MANAGED_STORE_ATTR, False)):
return False
if not _store_has_reachability_probe(store):
return False
return not _store_reachable(store)
def _store_has_reachability_probe(store: Any) -> bool:
try:
return callable(getattr(store, "ping", None)) or callable(getattr(store, "count_rows", None))
except Exception:
return False
def _require_operator_auth(settings: SentinelSettings, request: Request) -> None:
if not settings.api_token:
if settings.api_auth_required:
raise HTTPException(status_code=503, detail="SENTINEL_API_TOKEN is required for operator endpoints")
return
authorization = request.headers.get("authorization") or ""
scheme, _, token = authorization.partition(" ")
if scheme.lower() != "bearer" or not token or not hmac.compare_digest(token, settings.api_token):
raise HTTPException(status_code=401, detail="Invalid SENTINEL API token")
def _require_pagerduty_webhook_signature_config(settings: SentinelSettings) -> None:
if settings.webhook_signature_required and not settings.pagerduty_webhook_secret:
raise HTTPException(
status_code=503,
detail="PAGERDUTY_WEBHOOK_SECRET is required for PagerDuty webhooks",
)
def _require_pagerduty_webhook_subscription(settings: SentinelSettings, request: Request) -> None:
expected = settings.pagerduty_webhook_subscription_id
if not expected:
return
observed = (request.headers.get("x-webhook-subscription") or "").strip()
if not observed or not hmac.compare_digest(observed, expected.strip()):
raise HTTPException(status_code=401, detail="Invalid PagerDuty webhook subscription")
_OAUTH_INSTALL_REQUIREMENTS = {
"slack": (
("SLACK_CLIENT_ID", "slack_client_id"),
("SLACK_CLIENT_SECRET", "slack_client_secret"),
("SLACK_REDIRECT_URI", "slack_redirect_uri"),
),
"github": (
("GITHUB_CLIENT_ID", "github_client_id"),
("GITHUB_CLIENT_SECRET", "github_client_secret"),
("GITHUB_REDIRECT_URI", "github_redirect_uri"),
),
"datadog": (
("DD_CLIENT_ID", "datadog_client_id"),
("DD_CLIENT_SECRET", "datadog_client_secret"),
("DD_REDIRECT_URI", "datadog_redirect_uri"),
),
}
def _require_oauth_install_config(settings: SentinelSettings, provider: str) -> None:
requirements = _OAUTH_INSTALL_REQUIREMENTS[provider]
missing = [name for name, attr in requirements if not getattr(settings, attr)]
if missing:
raise HTTPException(
status_code=503,
detail=f"{provider} OAuth install is not configured; missing: {', '.join(missing)}",
)
def _remember_oauth_state(store: Any, provider: str, state: str) -> None:
try:
remember = getattr(store, "remember_idempotency_key", None)
if not callable(remember):
raise HTTPException(status_code=503, detail="Investigation Store does not support OAuth state tracking")
if not remember(_oauth_state_key(provider, state, "issued"), "oauth_state_issued", provider):
raise HTTPException(status_code=409, detail="OAuth state was already issued")
except HTTPException:
raise
except Exception as exc:
raise _store_unavailable_exception(exc) from exc
def _remember_oauth_value(store: Any, provider: str, state: str, name: str, value: str) -> None:
try:
remember = getattr(store, "remember_idempotency_key", None)
if not callable(remember):
raise HTTPException(status_code=503, detail="Investigation Store does not support OAuth state tracking")
if not remember(_oauth_state_key(provider, state, name), f"oauth_{name}", value):
raise HTTPException(status_code=409, detail=f"OAuth {name} was already stored")
except HTTPException:
raise
except Exception as exc:
raise _store_unavailable_exception(exc) from exc
def _consume_issued_oauth_state(manager: OAuthManager, store: Any, provider: str, state: str) -> None:
try:
manager.verify_state(state, provider)
except ToolExecutionError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
try:
lookup = getattr(store, "lookup_idempotency_key", None)
remember = getattr(store, "remember_idempotency_key", None)
if not callable(lookup) or not callable(remember):
raise HTTPException(status_code=503, detail="Investigation Store does not support OAuth state tracking")
if lookup(_oauth_state_key(provider, state, "issued")) != provider:
raise HTTPException(status_code=400, detail="OAuth state was not issued by this SENTINEL receiver")
if not remember(_oauth_state_key(provider, state, "used"), "oauth_state_used", provider):
raise HTTPException(status_code=409, detail="OAuth state has already been used")
except HTTPException:
raise
except Exception as exc:
raise _store_unavailable_exception(exc) from exc
def _lookup_oauth_value(store: Any, provider: str, state: str, name: str) -> str:
try:
lookup = getattr(store, "lookup_idempotency_key", None)
if not callable(lookup):
raise HTTPException(status_code=503, detail="Investigation Store does not support OAuth state tracking")
value = lookup(_oauth_state_key(provider, state, name))
if not value:
raise HTTPException(status_code=400, detail=f"OAuth {name} was not issued by this SENTINEL receiver")
return value
except HTTPException:
raise
except Exception as exc:
raise _store_unavailable_exception(exc) from exc
def _oauth_state_key(provider: str, state: str, status: str) -> str:
return f"oauth:{provider}:{state}:{status}"
def _oauth_callback_exception(exc: ToolExecutionError) -> HTTPException:
status_code = 503 if exc.retryable else 502
return HTTPException(status_code=status_code, detail=redact_sensitive_text(exc, max_length=500))
def _live_operation_exception(exc: ToolExecutionError) -> HTTPException:
status_code = 503 if exc.retryable else 502
return HTTPException(status_code=status_code, detail=redact_sensitive_text(exc, max_length=500))
def _store_unavailable_exception(exc: Exception) -> HTTPException:
return HTTPException(status_code=503, detail=redact_sensitive_text(exc, max_length=500))
def _require_runtime_ready(
settings: SentinelSettings,
store: Any,
*,
operation: str,
provider_preflight: bool = False,
) -> None:
body = _readiness_body(settings, store)
if body["ready"] and (not provider_preflight or _live_provider_preflight_skipped(settings)):
return
if body["ready"] and provider_preflight:
report = run_live_connectivity_checks(settings, store=store)
if report.ready or _provider_preflight_has_only_data_dependent_trace_gap(report):
return
raise HTTPException(
status_code=503,
detail={
"message": f"SENTINEL live provider preflight failed for {operation}",
"ready": False,
"provider_preflight_ready": False,
**report.model_dump(mode="json"),
},
)
raise HTTPException(
status_code=503,
detail={
"message": f"SENTINEL is not ready for {operation}",
**body,
},
)
def _provider_preflight_has_only_data_dependent_trace_gap(report: Any) -> bool:
if getattr(report, "missing_live_credentials", []):
return False
checks = getattr(report, "checks", [])
failed = [check for check in checks if not getattr(check, "passed", False)]
if not failed:
return True
for check in failed:
if getattr(check, "name", None) != "loki.apm_traces":
return False
detail = str(getattr(check, "detail", "") or "")
if "at least one provider record" not in detail:
return False
return True
def _live_provider_preflight_skipped(settings: SentinelSettings) -> bool:
return settings.runtime_environment != "production"
def _store_reachable(store: Any) -> bool:
try:
ping = getattr(store, "ping", None)
if callable(ping):
return bool(ping())
count_rows = getattr(store, "count_rows", None)
if callable(count_rows):
count_rows("schema_migrations")
return True
except Exception:
return False
return False
def _store_error(store: Any) -> str | None:
error = getattr(store, "error", None)
return error if isinstance(error, str) and error else None
def _close_resource(resource: Any) -> None:
close = getattr(resource, "close", None)
if callable(close):
close()
def _redis_reachable(settings: SentinelSettings) -> bool:
if not settings.redis_url:
return True
backend = None
try:
backend = RedisRateLimitBackend(settings.redis_url)
return backend.ping()
except Exception:
return False
finally:
if backend is not None:
_close_resource(backend)
def _prometheus_metrics_body(settings: SentinelSettings) -> str:
service = _prometheus_label(settings.default_service)
pod = _prometheus_label(f"{settings.default_service}-demo")
elapsed = max(1, int(time.monotonic() - _PROCESS_START_MONOTONIC) + 1)
ok_requests = 10000 + elapsed * 90
error_requests = 150 + elapsed * 4
duration_bucket_100ms = 7000 + elapsed * 45
duration_bucket_500ms = 9400 + elapsed * 82
duration_bucket_1s = 9900 + elapsed * 89
duration_bucket_inf = ok_requests + error_requests
cpu_seconds = 500 + elapsed * 2
memory_bytes = 185_000_000 + (elapsed % 20) * 1_000_000
demo_metrics = "\n".join(
[
"# HELP sentinel_demo_info SENTINEL free-tier demo metric.",
"# TYPE sentinel_demo_info gauge",
f"sentinel_demo_info{{service={service}}} 1",
"# HELP up Demo scrape health with service identity.",
"# TYPE up gauge",
f"up{{service={service}}} 1",
"# HELP http_requests_total Demo HTTP requests by status.",
"# TYPE http_requests_total counter",
f"http_requests_total{{service={service},status=\"200\"}} {ok_requests}",
f"http_requests_total{{service={service},status=\"500\"}} {error_requests}",
"# HELP http_request_duration_seconds Demo HTTP request latency histogram.",
"# TYPE http_request_duration_seconds histogram",
f"http_request_duration_seconds_bucket{{service={service},le=\"0.1\"}} {duration_bucket_100ms}",
f"http_request_duration_seconds_bucket{{service={service},le=\"0.5\"}} {duration_bucket_500ms}",
f"http_request_duration_seconds_bucket{{service={service},le=\"1\"}} {duration_bucket_1s}",
f"http_request_duration_seconds_bucket{{service={service},le=\"+Inf\"}} {duration_bucket_inf}",
f"http_request_duration_seconds_sum{{service={service}}} {duration_bucket_inf * 0.23:.3f}",
f"http_request_duration_seconds_count{{service={service}}} {duration_bucket_inf}",
"# HELP queue_depth Demo queue depth.",
"# TYPE queue_depth gauge",
f"queue_depth{{service={service}}} {42 + elapsed % 7}",
"# HELP network_tcp_rtt_seconds Demo inter-service RTT.",
"# TYPE network_tcp_rtt_seconds gauge",
f"network_tcp_rtt_seconds{{service={service}}} {0.028 + (elapsed % 5) * 0.001:.3f}",
"# HELP synthetics_browser_uptime Demo uptime percentage.",
"# TYPE synthetics_browser_uptime gauge",
f"synthetics_browser_uptime{{service={service}}} 0.998",
"# HELP container_cpu_usage_seconds_total Demo container CPU counter.",
"# TYPE container_cpu_usage_seconds_total counter",
f"container_cpu_usage_seconds_total{{pod={pod},container=\"app\"}} {cpu_seconds}",
"# HELP container_memory_working_set_bytes Demo container memory working set.",
"# TYPE container_memory_working_set_bytes gauge",
f"container_memory_working_set_bytes{{pod={pod},container=\"app\"}} {memory_bytes}",
"",
]
)
return demo_metrics + slow_query_metrics(settings.default_service)
def _prometheus_label(value: str) -> str:
return json.dumps(str(value))
def _investigation_response(state: InvestigationState) -> dict[str, Any]:
provider_proofs = _live_provider_success_counts(state)
tool_proofs = _live_tool_success_counts(state)
slack_notified = _has_live_tool_evidence(state, "comms.post_to_slack")
discord_notified = slack_notified and state.artifacts.get("comms_provider") == "discord"
approval_request_id = state.approval_request.id if state.approval_request else None
approval_command = state.approval_command
approval_notification_request_id = state.artifacts.get("approval_slack_notification_request_id")
approval_slack_notified = (
state.artifacts.get("approval_slack_notified") is True
and approval_request_id is not None
and approval_notification_request_id == approval_request_id
)
rollback_executed = _rollback_executed(state)
rollback_attempted = any(
call.tool_name == "infra.rollback_deployment"
for call in state.tool_calls
)
return {
"receiver_process": _receiver_process_identity(),
"investigation_id": state.id,
"incident_id": state.incident_id,
"status": state.status.value,
"current_state": state.current_state.value,
"tool_calls": len(state.tool_calls),
"tool_call_names": [call.tool_name for call in state.tool_calls],
"tool_call_records": [call.model_dump(mode="json") for call in state.tool_calls],
"state_transitions": [
event.model_dump(mode="json")
for event in state.audit_events
if event.event_type == "state_transition"
],
"plan_steps": [step.model_dump(mode="json") for step in state.plan_steps],
"model_tool_plans": state.artifacts.get("model_tool_plans", []),
"evidence_records": [
{
**evidence.model_dump(mode="json"),
"claim": redact_sensitive_text(evidence.claim, max_length=1000),
}