- event-ingress server, observability store, campaign recovery: ID whitelist + resolve containment - task_worktree.sh: tighten TASK_ID regex, reject ../ and ..\ traversal - init_gitops_baseline.sh: validate zip entries before extract (zip-slip) - sync_gitea_owner_password.sh: remove env-sourced shell injection - chatgpt_actions + model_api_staging: authenticated command read w/ strict id + containment + size cap
58 lines
2.4 KiB
Python
58 lines
2.4 KiB
Python
"""Persistent store for agent observability records.
|
|
|
|
Stores sanitized execution metrics for OpenClaw/Hermes/sub-agents. No prompts,
|
|
secrets, or private message contents are persisted here; only metrics and routing
|
|
metadata are stored for Web UI statistics and audit.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from .agent_observability import AgentExecutionRecord, AgentObservability
|
|
|
|
# Constrain execution IDs (used as filename) to a single safe path segment.
|
|
_SAFE_EXECUTION_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$")
|
|
|
|
|
|
class AgentObservabilityStore:
|
|
def __init__(self, root: str = "runtime/agent-observability"):
|
|
self.root = Path(root)
|
|
self.records_dir = self.root / "records"
|
|
self.records_dir.mkdir(parents=True, exist_ok=True)
|
|
|
|
def append(self, record: AgentExecutionRecord) -> dict[str, Any]:
|
|
execution_id = str(record.execution_id or "")
|
|
if not _SAFE_EXECUTION_ID.fullmatch(execution_id) or ".." in execution_id:
|
|
raise ValueError(f"invalid execution_id: {execution_id!r}")
|
|
base = self.records_dir.resolve()
|
|
target = (self.records_dir / f"{execution_id}.json").resolve()
|
|
# The whitelist forbids separators/traversal, so the resolved target
|
|
# must sit directly inside the records dir; verify defensively.
|
|
if target.parent != base:
|
|
raise ValueError(f"invalid execution_id: {execution_id!r}")
|
|
data = record.to_dict()
|
|
target.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
return data
|
|
|
|
def load(self) -> AgentObservability:
|
|
observability = AgentObservability()
|
|
for path in sorted(self.records_dir.glob("*.json")):
|
|
raw = json.loads(path.read_text(encoding="utf-8"))
|
|
observability.records.append(AgentExecutionRecord(**raw))
|
|
return observability
|
|
|
|
def query(self, user_id: str | None = None, group_id: str | None = None, role: str = "user") -> list[dict[str, Any]]:
|
|
records = [record.to_dict() for record in self.load().records]
|
|
if role == "owner":
|
|
return records
|
|
if role == "group_admin" and group_id:
|
|
return [r for r in records if r.get("visible_scope") == group_id or r.get("user_id") == user_id]
|
|
return [r for r in records if r.get("user_id") == user_id]
|
|
|
|
|
|
__all__ = ["AgentObservabilityStore"]
|