superuser 0.1.0__py3-none-any.whl
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.
- superuser/__init__.py +5 -0
- superuser/__main__.py +62 -0
- superuser/audit.py +70 -0
- superuser/authz.py +155 -0
- superuser/billing.py +91 -0
- superuser/config.py +314 -0
- superuser/guard.py +152 -0
- superuser/security.py +170 -0
- superuser/server.py +138 -0
- superuser/tools/__init__.py +1 -0
- superuser/tools/github.py +90 -0
- superuser/tools/shell.py +61 -0
- superuser/tools/system.py +69 -0
- superuser-0.1.0.dist-info/METADATA +215 -0
- superuser-0.1.0.dist-info/RECORD +18 -0
- superuser-0.1.0.dist-info/WHEEL +5 -0
- superuser-0.1.0.dist-info/entry_points.txt +2 -0
- superuser-0.1.0.dist-info/top_level.txt +1 -0
superuser/config.py
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
"""Configuration for the superuser agent.
|
|
2
|
+
|
|
3
|
+
Settings are resolved with the following precedence (highest first):
|
|
4
|
+
1. Explicit values in a YAML config file (path from ``SUPERUSER_CONFIG``).
|
|
5
|
+
2. Environment variables.
|
|
6
|
+
3. Built-in safe defaults.
|
|
7
|
+
|
|
8
|
+
The defaults are deliberately conservative: manual approval is required for
|
|
9
|
+
anything above low risk, and GitHub / shell writes are locked down until the
|
|
10
|
+
operator opts in.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import os
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from enum import IntEnum
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
import yaml
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class Risk(IntEnum):
|
|
25
|
+
"""Relative risk of a tool invocation. Higher means more dangerous."""
|
|
26
|
+
|
|
27
|
+
LOW = 0
|
|
28
|
+
MEDIUM = 1
|
|
29
|
+
HIGH = 2
|
|
30
|
+
CRITICAL = 3
|
|
31
|
+
|
|
32
|
+
@classmethod
|
|
33
|
+
def parse(cls, value: Any) -> "Risk":
|
|
34
|
+
if isinstance(value, Risk):
|
|
35
|
+
return value
|
|
36
|
+
if isinstance(value, int):
|
|
37
|
+
return cls(value)
|
|
38
|
+
return cls[str(value).strip().upper()]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# Commands that are never allowed to run, regardless of approval. These are
|
|
42
|
+
# blunt substring/word checks — a defense-in-depth backstop, not the primary
|
|
43
|
+
# control (Cisco AI Defense + approval gating are the primary controls).
|
|
44
|
+
DEFAULT_COMMAND_DENYLIST: tuple[str, ...] = (
|
|
45
|
+
"rm -rf /",
|
|
46
|
+
"mkfs",
|
|
47
|
+
":(){:|:&};:", # fork bomb
|
|
48
|
+
"dd if=/dev/zero",
|
|
49
|
+
"dd if=/dev/random",
|
|
50
|
+
"> /dev/sda",
|
|
51
|
+
"chmod -r 000 /",
|
|
52
|
+
"shutdown",
|
|
53
|
+
"reboot",
|
|
54
|
+
"halt",
|
|
55
|
+
"poweroff",
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _env(name: str, default: str | None = None) -> str | None:
|
|
60
|
+
value = os.environ.get(name)
|
|
61
|
+
return value if value not in (None, "") else default
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _env_bool(name: str, default: bool) -> bool:
|
|
65
|
+
raw = _env(name)
|
|
66
|
+
if raw is None:
|
|
67
|
+
return default
|
|
68
|
+
return raw.strip().lower() in ("1", "true", "yes", "on")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class CiscoConfig:
|
|
73
|
+
"""Cisco AI Defense runtime-guardrail settings.
|
|
74
|
+
|
|
75
|
+
``mode`` mirrors the AI Defense Agent Runtime SDK:
|
|
76
|
+
- ``enforce``: block requests/responses that violate policy.
|
|
77
|
+
- ``monitor``: log violations but allow the call through.
|
|
78
|
+
- ``off``: do not call AI Defense at all.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
enabled: bool = True
|
|
82
|
+
mode: str = "enforce"
|
|
83
|
+
# Inspection-API key used for explicit MCP tool-call inspection.
|
|
84
|
+
inspection_api_key: str | None = None
|
|
85
|
+
# agentsec.protect() API-mode endpoint/key for auto-patched LLM+MCP calls.
|
|
86
|
+
runtime_endpoint: str | None = None
|
|
87
|
+
runtime_api_key: str | None = None
|
|
88
|
+
# Path to an agentsec.yaml; if present, it takes precedence for protect().
|
|
89
|
+
agentsec_config_path: str | None = None
|
|
90
|
+
|
|
91
|
+
@property
|
|
92
|
+
def can_inspect(self) -> bool:
|
|
93
|
+
return self.enabled and self.mode != "off" and bool(self.inspection_api_key)
|
|
94
|
+
|
|
95
|
+
@property
|
|
96
|
+
def can_protect(self) -> bool:
|
|
97
|
+
return self.enabled and self.mode != "off" and bool(
|
|
98
|
+
self.agentsec_config_path or (self.runtime_endpoint and self.runtime_api_key)
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass
|
|
103
|
+
class DuoConfig:
|
|
104
|
+
"""Cisco Duo Agentic Identity authorization settings.
|
|
105
|
+
|
|
106
|
+
Duo follows a "Duo decides, the gateway enforces" model: per-tool-call
|
|
107
|
+
authorization is evaluated against Duo's policy engine, keyed to the agent's
|
|
108
|
+
registered identity and its accountable human owner. This agent
|
|
109
|
+
authenticates via the OAuth 2.1 client-credentials grant (machine-to-machine)
|
|
110
|
+
and checks each tool call against the scopes/policy Duo grants.
|
|
111
|
+
|
|
112
|
+
``mode`` mirrors the other guardrails: ``enforce`` blocks unauthorized
|
|
113
|
+
calls, ``monitor`` logs them but allows, ``off`` disables.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
enabled: bool = False
|
|
117
|
+
mode: str = "enforce"
|
|
118
|
+
agent_id: str | None = None
|
|
119
|
+
token_url: str | None = None
|
|
120
|
+
client_id: str | None = None
|
|
121
|
+
client_secret: str | None = None
|
|
122
|
+
# Optional explicit per-tool-call decision endpoint. When unset, the granted
|
|
123
|
+
# OAuth scopes are used to authorize (scope-based access control).
|
|
124
|
+
authorization_url: str | None = None
|
|
125
|
+
# RFC 8707 resource indicator (the audience this agent intends to access).
|
|
126
|
+
resource: str | None = None
|
|
127
|
+
# Scopes requested at token time and/or matched per tool.
|
|
128
|
+
scopes: list[str] = field(default_factory=list)
|
|
129
|
+
# Map of tool name -> scope required to invoke it.
|
|
130
|
+
tool_scopes: dict[str, str] = field(default_factory=dict)
|
|
131
|
+
|
|
132
|
+
@property
|
|
133
|
+
def can_enforce(self) -> bool:
|
|
134
|
+
return (
|
|
135
|
+
self.enabled
|
|
136
|
+
and self.mode != "off"
|
|
137
|
+
and bool(self.token_url and self.client_id and self.client_secret)
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@dataclass
|
|
142
|
+
class StripeConfig:
|
|
143
|
+
"""Stripe usage-based (metered) billing settings.
|
|
144
|
+
|
|
145
|
+
A successful, authorized tool call emits a Stripe meter event so the agent
|
|
146
|
+
can be sold on a per-action basis. Billing never blocks or fails a tool
|
|
147
|
+
call — metering errors are logged and the action still returns.
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
enabled: bool = False
|
|
151
|
+
api_key: str | None = None
|
|
152
|
+
customer_id: str | None = None
|
|
153
|
+
event_name: str = "superuser_tool_call"
|
|
154
|
+
default_value: int = 1
|
|
155
|
+
# Optional per-tool billing weights (e.g. high-risk actions cost more).
|
|
156
|
+
per_tool_values: dict[str, int] = field(default_factory=dict)
|
|
157
|
+
|
|
158
|
+
@property
|
|
159
|
+
def can_bill(self) -> bool:
|
|
160
|
+
return self.enabled and bool(self.api_key and self.customer_id)
|
|
161
|
+
|
|
162
|
+
def value_for(self, tool_name: str) -> int:
|
|
163
|
+
return int(self.per_tool_values.get(tool_name, self.default_value))
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
@dataclass
|
|
167
|
+
class GitHubConfig:
|
|
168
|
+
"""Least-privilege GitHub access settings."""
|
|
169
|
+
|
|
170
|
+
token: str | None = None
|
|
171
|
+
api_url: str = "https://api.github.com"
|
|
172
|
+
# Empty means no repositories are permitted (fail closed).
|
|
173
|
+
allowed_repos: list[str] = field(default_factory=list)
|
|
174
|
+
allow_writes: bool = False
|
|
175
|
+
|
|
176
|
+
def repo_allowed(self, repo: str) -> bool:
|
|
177
|
+
if not self.allowed_repos:
|
|
178
|
+
return False
|
|
179
|
+
if "*" in self.allowed_repos:
|
|
180
|
+
return True
|
|
181
|
+
return repo in self.allowed_repos
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
@dataclass
|
|
185
|
+
class Config:
|
|
186
|
+
"""Top-level agent configuration."""
|
|
187
|
+
|
|
188
|
+
approval_required_at: Risk = Risk.MEDIUM
|
|
189
|
+
command_allowlist: list[str] = field(default_factory=list)
|
|
190
|
+
command_denylist: list[str] = field(default_factory=lambda: list(DEFAULT_COMMAND_DENYLIST))
|
|
191
|
+
command_timeout_seconds: int = 60
|
|
192
|
+
audit_log_path: Path = field(default_factory=lambda: Path("superuser-audit.log"))
|
|
193
|
+
human_owner: str = "unknown"
|
|
194
|
+
cisco: CiscoConfig = field(default_factory=CiscoConfig)
|
|
195
|
+
duo: DuoConfig = field(default_factory=DuoConfig)
|
|
196
|
+
stripe: StripeConfig = field(default_factory=StripeConfig)
|
|
197
|
+
github: GitHubConfig = field(default_factory=GitHubConfig)
|
|
198
|
+
|
|
199
|
+
def requires_approval(self, risk: Risk) -> bool:
|
|
200
|
+
return risk >= self.approval_required_at
|
|
201
|
+
|
|
202
|
+
@classmethod
|
|
203
|
+
def load(cls, config_path: str | os.PathLike[str] | None = None) -> "Config":
|
|
204
|
+
cfg = cls.from_env()
|
|
205
|
+
path = config_path or _env("SUPERUSER_CONFIG")
|
|
206
|
+
if path and Path(path).is_file():
|
|
207
|
+
cfg._apply_yaml(yaml.safe_load(Path(path).read_text()) or {})
|
|
208
|
+
return cfg
|
|
209
|
+
|
|
210
|
+
@classmethod
|
|
211
|
+
def from_env(cls) -> "Config":
|
|
212
|
+
cfg = cls()
|
|
213
|
+
cfg.human_owner = _env("SUPERUSER_HUMAN_OWNER", cfg.human_owner)
|
|
214
|
+
approval = _env("SUPERUSER_APPROVAL_AT")
|
|
215
|
+
if approval:
|
|
216
|
+
cfg.approval_required_at = Risk.parse(approval)
|
|
217
|
+
cfg.command_timeout_seconds = int(
|
|
218
|
+
_env("SUPERUSER_COMMAND_TIMEOUT", str(cfg.command_timeout_seconds))
|
|
219
|
+
)
|
|
220
|
+
audit = _env("SUPERUSER_AUDIT_LOG")
|
|
221
|
+
if audit:
|
|
222
|
+
cfg.audit_log_path = Path(audit)
|
|
223
|
+
|
|
224
|
+
cfg.cisco = CiscoConfig(
|
|
225
|
+
enabled=_env_bool("AI_DEFENSE_ENABLED", True),
|
|
226
|
+
mode=_env("AI_DEFENSE_MODE", "enforce"),
|
|
227
|
+
inspection_api_key=_env("AI_DEFENSE_INSPECTION_API_KEY"),
|
|
228
|
+
runtime_endpoint=_env("AI_DEFENSE_API_MODE_LLM_ENDPOINT"),
|
|
229
|
+
runtime_api_key=_env("AI_DEFENSE_API_MODE_LLM_API_KEY"),
|
|
230
|
+
agentsec_config_path=_env("AI_DEFENSE_AGENTSEC_CONFIG"),
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
duo_scopes = _env("DUO_SCOPES", "")
|
|
234
|
+
cfg.duo = DuoConfig(
|
|
235
|
+
enabled=_env_bool("DUO_ENABLED", False),
|
|
236
|
+
mode=_env("DUO_MODE", "enforce"),
|
|
237
|
+
agent_id=_env("DUO_AGENT_ID"),
|
|
238
|
+
token_url=_env("DUO_TOKEN_URL"),
|
|
239
|
+
client_id=_env("DUO_CLIENT_ID"),
|
|
240
|
+
client_secret=_env("DUO_CLIENT_SECRET"),
|
|
241
|
+
authorization_url=_env("DUO_AUTHORIZATION_URL"),
|
|
242
|
+
resource=_env("DUO_RESOURCE"),
|
|
243
|
+
scopes=[s.strip() for s in (duo_scopes or "").split() if s.strip()],
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
cfg.stripe = StripeConfig(
|
|
247
|
+
enabled=_env_bool("STRIPE_ENABLED", False),
|
|
248
|
+
api_key=_env("STRIPE_API_KEY"),
|
|
249
|
+
customer_id=_env("STRIPE_CUSTOMER_ID"),
|
|
250
|
+
event_name=_env("STRIPE_METER_EVENT_NAME", "superuser_tool_call"),
|
|
251
|
+
default_value=int(_env("STRIPE_DEFAULT_VALUE", "1")),
|
|
252
|
+
)
|
|
253
|
+
|
|
254
|
+
repos = _env("GITHUB_ALLOWED_REPOS", "")
|
|
255
|
+
cfg.github = GitHubConfig(
|
|
256
|
+
token=_env("GITHUB_TOKEN"),
|
|
257
|
+
api_url=_env("GITHUB_API_URL", "https://api.github.com"),
|
|
258
|
+
allowed_repos=[r.strip() for r in (repos or "").split(",") if r.strip()],
|
|
259
|
+
allow_writes=_env_bool("GITHUB_ALLOW_WRITES", False),
|
|
260
|
+
)
|
|
261
|
+
return cfg
|
|
262
|
+
|
|
263
|
+
def _apply_yaml(self, data: dict[str, Any]) -> None:
|
|
264
|
+
if "approval_required_at" in data:
|
|
265
|
+
self.approval_required_at = Risk.parse(data["approval_required_at"])
|
|
266
|
+
if "command_allowlist" in data:
|
|
267
|
+
self.command_allowlist = list(data["command_allowlist"] or [])
|
|
268
|
+
if "command_denylist" in data:
|
|
269
|
+
# Extend rather than replace, so operators can't accidentally drop
|
|
270
|
+
# the built-in dangerous-command backstops.
|
|
271
|
+
self.command_denylist = list(DEFAULT_COMMAND_DENYLIST) + list(
|
|
272
|
+
data["command_denylist"] or []
|
|
273
|
+
)
|
|
274
|
+
if "command_timeout_seconds" in data:
|
|
275
|
+
self.command_timeout_seconds = int(data["command_timeout_seconds"])
|
|
276
|
+
if "audit_log_path" in data:
|
|
277
|
+
self.audit_log_path = Path(data["audit_log_path"])
|
|
278
|
+
if "human_owner" in data:
|
|
279
|
+
self.human_owner = str(data["human_owner"])
|
|
280
|
+
|
|
281
|
+
cisco = data.get("cisco") or {}
|
|
282
|
+
for key in ("enabled", "mode", "inspection_api_key", "runtime_endpoint",
|
|
283
|
+
"runtime_api_key", "agentsec_config_path"):
|
|
284
|
+
if key in cisco:
|
|
285
|
+
setattr(self.cisco, key, cisco[key])
|
|
286
|
+
|
|
287
|
+
duo = data.get("duo") or {}
|
|
288
|
+
for key in ("enabled", "mode", "agent_id", "token_url", "client_id",
|
|
289
|
+
"client_secret", "authorization_url", "resource"):
|
|
290
|
+
if key in duo:
|
|
291
|
+
setattr(self.duo, key, duo[key])
|
|
292
|
+
if "scopes" in duo:
|
|
293
|
+
self.duo.scopes = list(duo["scopes"] or [])
|
|
294
|
+
if "tool_scopes" in duo:
|
|
295
|
+
self.duo.tool_scopes = dict(duo["tool_scopes"] or {})
|
|
296
|
+
|
|
297
|
+
stripe = data.get("stripe") or {}
|
|
298
|
+
for key in ("enabled", "api_key", "customer_id", "event_name", "default_value"):
|
|
299
|
+
if key in stripe:
|
|
300
|
+
setattr(self.stripe, key, stripe[key])
|
|
301
|
+
if "per_tool_values" in stripe:
|
|
302
|
+
self.stripe.per_tool_values = {
|
|
303
|
+
k: int(v) for k, v in (stripe["per_tool_values"] or {}).items()
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
gh = data.get("github") or {}
|
|
307
|
+
if "token" in gh:
|
|
308
|
+
self.github.token = gh["token"]
|
|
309
|
+
if "api_url" in gh:
|
|
310
|
+
self.github.api_url = gh["api_url"]
|
|
311
|
+
if "allowed_repos" in gh:
|
|
312
|
+
self.github.allowed_repos = list(gh["allowed_repos"] or [])
|
|
313
|
+
if "allow_writes" in gh:
|
|
314
|
+
self.github.allow_writes = bool(gh["allow_writes"])
|
superuser/guard.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"""The guard: the single choke point every tool invocation passes through.
|
|
2
|
+
|
|
3
|
+
Order of checks for each call:
|
|
4
|
+
1. Cisco AI Defense inspects the tool call (may block).
|
|
5
|
+
2. Approval gate: risky calls require explicit ``confirm=True`` from a human.
|
|
6
|
+
3. The operation runs.
|
|
7
|
+
4. Cisco AI Defense inspects the response (may block before it is returned).
|
|
8
|
+
5. The outcome is written to the audit log.
|
|
9
|
+
|
|
10
|
+
Every branch produces a structured dict so the MCP client always gets a clear,
|
|
11
|
+
machine-readable status instead of an opaque error.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import logging
|
|
17
|
+
from typing import Any, Callable
|
|
18
|
+
|
|
19
|
+
from .audit import AuditLog
|
|
20
|
+
from .authz import DuoAuthorizer
|
|
21
|
+
from .billing import StripeMeter
|
|
22
|
+
from .config import Config, Risk
|
|
23
|
+
from .security import CiscoAIDefense
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger("superuser.guard")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class Guard:
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
config: Config,
|
|
32
|
+
audit: AuditLog,
|
|
33
|
+
defense: CiscoAIDefense,
|
|
34
|
+
authorizer: DuoAuthorizer | None = None,
|
|
35
|
+
meter: StripeMeter | None = None,
|
|
36
|
+
) -> None:
|
|
37
|
+
self.config = config
|
|
38
|
+
self.audit = audit
|
|
39
|
+
self.defense = defense
|
|
40
|
+
self.authorizer = authorizer
|
|
41
|
+
self.meter = meter
|
|
42
|
+
|
|
43
|
+
def run(
|
|
44
|
+
self,
|
|
45
|
+
*,
|
|
46
|
+
tool_name: str,
|
|
47
|
+
args: dict[str, Any],
|
|
48
|
+
risk: Risk,
|
|
49
|
+
op: Callable[[], Any],
|
|
50
|
+
confirm: bool = False,
|
|
51
|
+
) -> dict[str, Any]:
|
|
52
|
+
risk_name = risk.name
|
|
53
|
+
|
|
54
|
+
# 1. Pre-execution inspection.
|
|
55
|
+
pre = self.defense.inspect_tool_call(tool_name, args)
|
|
56
|
+
if not pre.safe:
|
|
57
|
+
self.audit.record(tool_name, args, decision="blocked_by_ai_defense",
|
|
58
|
+
status="denied", risk=risk_name, detail=", ".join(pre.reasons))
|
|
59
|
+
return _denied(
|
|
60
|
+
tool_name,
|
|
61
|
+
reason="Cisco AI Defense blocked this tool call.",
|
|
62
|
+
risk=risk_name,
|
|
63
|
+
details=pre.reasons,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
# 2. Duo Agentic Identity authorization (per-tool-call policy).
|
|
67
|
+
if self.authorizer is not None:
|
|
68
|
+
authz = self.authorizer.authorize(tool_name, args, risk_name)
|
|
69
|
+
if not authz.allowed:
|
|
70
|
+
self.audit.record(tool_name, args, decision="denied_by_duo",
|
|
71
|
+
status="denied", risk=risk_name, detail=authz.reason)
|
|
72
|
+
return _denied(
|
|
73
|
+
tool_name,
|
|
74
|
+
reason="Cisco Duo Agentic Identity denied this tool call.",
|
|
75
|
+
risk=risk_name,
|
|
76
|
+
details=[authz.reason],
|
|
77
|
+
)
|
|
78
|
+
else:
|
|
79
|
+
authz = None
|
|
80
|
+
|
|
81
|
+
# 3. Approval gate.
|
|
82
|
+
if self.config.requires_approval(risk) and not confirm:
|
|
83
|
+
self.audit.record(tool_name, args, decision="approval_required",
|
|
84
|
+
status="pending", risk=risk_name)
|
|
85
|
+
return {
|
|
86
|
+
"status": "approval_required",
|
|
87
|
+
"tool": tool_name,
|
|
88
|
+
"risk": risk_name,
|
|
89
|
+
"protected": pre.protected,
|
|
90
|
+
"message": (
|
|
91
|
+
f"'{tool_name}' is a {risk_name}-risk action and needs explicit "
|
|
92
|
+
"human approval. Review the arguments and call again with confirm=true."
|
|
93
|
+
),
|
|
94
|
+
"arguments": args,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
# 4. Execute.
|
|
98
|
+
try:
|
|
99
|
+
output = op()
|
|
100
|
+
except Exception as exc:
|
|
101
|
+
self.audit.record(tool_name, args, decision="allowed", status="error",
|
|
102
|
+
risk=risk_name, detail=str(exc))
|
|
103
|
+
logger.exception("Tool %s failed", tool_name)
|
|
104
|
+
return {"status": "error", "tool": tool_name, "error": str(exc)}
|
|
105
|
+
|
|
106
|
+
# 5. Post-execution (response) inspection.
|
|
107
|
+
response_payload = output if isinstance(output, dict) else {"result": output}
|
|
108
|
+
post = self.defense.inspect_response(tool_name, _stringify_for_inspection(response_payload))
|
|
109
|
+
if not post.safe:
|
|
110
|
+
self.audit.record(tool_name, args, decision="response_blocked_by_ai_defense",
|
|
111
|
+
status="denied", risk=risk_name, detail=", ".join(post.reasons))
|
|
112
|
+
return _denied(
|
|
113
|
+
tool_name,
|
|
114
|
+
reason="Cisco AI Defense blocked the tool response (possible data leakage).",
|
|
115
|
+
risk=risk_name,
|
|
116
|
+
details=post.reasons,
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
# 6. Meter the successful call (best-effort; never blocks).
|
|
120
|
+
billing = self.meter.record(tool_name) if self.meter is not None else None
|
|
121
|
+
|
|
122
|
+
# 7. Success audit.
|
|
123
|
+
self.audit.record(tool_name, args, decision="allowed", status="success", risk=risk_name)
|
|
124
|
+
response: dict[str, Any] = {
|
|
125
|
+
"status": "ok",
|
|
126
|
+
"tool": tool_name,
|
|
127
|
+
"risk": risk_name,
|
|
128
|
+
"protected": pre.protected and post.protected,
|
|
129
|
+
"result": output,
|
|
130
|
+
}
|
|
131
|
+
if authz is not None:
|
|
132
|
+
response["governed"] = authz.governed
|
|
133
|
+
if billing is not None:
|
|
134
|
+
response["billed"] = billing.billed
|
|
135
|
+
return response
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _denied(tool_name: str, *, reason: str, risk: str, details: list[str]) -> dict[str, Any]:
|
|
139
|
+
return {
|
|
140
|
+
"status": "denied",
|
|
141
|
+
"tool": tool_name,
|
|
142
|
+
"risk": risk,
|
|
143
|
+
"reason": reason,
|
|
144
|
+
"details": details,
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _stringify_for_inspection(payload: dict[str, Any]) -> dict[str, Any]:
|
|
149
|
+
"""AI Defense response inspection expects text content blocks."""
|
|
150
|
+
import json
|
|
151
|
+
|
|
152
|
+
return {"content": [{"type": "text", "text": json.dumps(payload, default=str)[:20000]}]}
|
superuser/security.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""Cisco AI Defense integration.
|
|
2
|
+
|
|
3
|
+
Two layers of protection are wired in:
|
|
4
|
+
|
|
5
|
+
1. Runtime protection via ``agentsec.protect()`` — auto-patches LLM and MCP
|
|
6
|
+
client libraries so every model call and tool invocation is inspected.
|
|
7
|
+
Enabled once at process start.
|
|
8
|
+
|
|
9
|
+
2. Explicit MCP tool-call inspection via ``MCPInspectionClient`` — used by the
|
|
10
|
+
guard before a tool runs and after it returns, so this server inspects its
|
|
11
|
+
*own* tools even when the caller is not auto-patched.
|
|
12
|
+
|
|
13
|
+
The Cisco SDK is imported lazily. If it is not installed, or no credentials are
|
|
14
|
+
configured, the server still runs but every tool result is annotated as
|
|
15
|
+
UNPROTECTED so the gap is never silent.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import logging
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
|
|
23
|
+
from .config import CiscoConfig
|
|
24
|
+
|
|
25
|
+
logger = logging.getLogger("superuser.security")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class InspectionResult:
|
|
30
|
+
"""Normalized outcome of an AI Defense inspection."""
|
|
31
|
+
|
|
32
|
+
safe: bool
|
|
33
|
+
protected: bool
|
|
34
|
+
reasons: list[str]
|
|
35
|
+
action: str # "allow", "block", or "unprotected"
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def unprotected(cls) -> "InspectionResult":
|
|
39
|
+
return cls(safe=True, protected=False, reasons=[], action="unprotected")
|
|
40
|
+
|
|
41
|
+
@classmethod
|
|
42
|
+
def allow(cls) -> "InspectionResult":
|
|
43
|
+
return cls(safe=True, protected=True, reasons=[], action="allow")
|
|
44
|
+
|
|
45
|
+
@classmethod
|
|
46
|
+
def block(cls, reasons: list[str]) -> "InspectionResult":
|
|
47
|
+
return cls(safe=False, protected=True, reasons=reasons, action="block")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class CiscoAIDefense:
|
|
51
|
+
"""Wraps the Cisco AI Defense SDK with graceful degradation."""
|
|
52
|
+
|
|
53
|
+
def __init__(self, config: CiscoConfig) -> None:
|
|
54
|
+
self.config = config
|
|
55
|
+
self._mcp_client = None
|
|
56
|
+
self._protected = False
|
|
57
|
+
self._available = self._probe_sdk()
|
|
58
|
+
if config.enabled and not self._available:
|
|
59
|
+
logger.warning(
|
|
60
|
+
"Cisco AI Defense SDK not installed; tools will run UNPROTECTED. "
|
|
61
|
+
"Install with: pip install 'superuser[security]'"
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
@staticmethod
|
|
65
|
+
def _probe_sdk() -> bool:
|
|
66
|
+
try:
|
|
67
|
+
import aidefense # noqa: F401
|
|
68
|
+
except Exception:
|
|
69
|
+
return False
|
|
70
|
+
return True
|
|
71
|
+
|
|
72
|
+
def enable_runtime_protection(self) -> bool:
|
|
73
|
+
"""Call agentsec.protect() to auto-patch LLM + MCP clients.
|
|
74
|
+
|
|
75
|
+
Returns True if protection was enabled.
|
|
76
|
+
"""
|
|
77
|
+
if not (self._available and self.config.can_protect):
|
|
78
|
+
return False
|
|
79
|
+
try:
|
|
80
|
+
from aidefense.runtime import agentsec
|
|
81
|
+
|
|
82
|
+
if self.config.agentsec_config_path:
|
|
83
|
+
agentsec.protect(config=self.config.agentsec_config_path)
|
|
84
|
+
else:
|
|
85
|
+
agentsec.protect(
|
|
86
|
+
llm_integration_mode="api",
|
|
87
|
+
api_mode={
|
|
88
|
+
"llm": {
|
|
89
|
+
"mode": self.config.mode,
|
|
90
|
+
"endpoint": self.config.runtime_endpoint,
|
|
91
|
+
"api_key": self.config.runtime_api_key,
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
)
|
|
95
|
+
self._protected = True
|
|
96
|
+
logger.info("Cisco AI Defense runtime protection enabled (mode=%s).", self.config.mode)
|
|
97
|
+
except Exception as exc: # protection must never crash the server
|
|
98
|
+
logger.error("Failed to enable Cisco AI Defense runtime protection: %s", exc)
|
|
99
|
+
return self._protected
|
|
100
|
+
|
|
101
|
+
def _client(self):
|
|
102
|
+
if self._mcp_client is not None:
|
|
103
|
+
return self._mcp_client
|
|
104
|
+
if not (self._available and self.config.can_inspect):
|
|
105
|
+
return None
|
|
106
|
+
try:
|
|
107
|
+
from aidefense import MCPInspectionClient
|
|
108
|
+
|
|
109
|
+
self._mcp_client = MCPInspectionClient(api_key=self.config.inspection_api_key)
|
|
110
|
+
except Exception as exc:
|
|
111
|
+
logger.error("Could not initialize MCPInspectionClient: %s", exc)
|
|
112
|
+
self._mcp_client = None
|
|
113
|
+
return self._mcp_client
|
|
114
|
+
|
|
115
|
+
def inspect_tool_call(self, tool_name: str, arguments: dict) -> InspectionResult:
|
|
116
|
+
client = self._client()
|
|
117
|
+
if client is None:
|
|
118
|
+
return InspectionResult.unprotected()
|
|
119
|
+
try:
|
|
120
|
+
result = client.inspect_tool_call(tool_name=tool_name, arguments=arguments)
|
|
121
|
+
return self._normalize(result)
|
|
122
|
+
except Exception as exc:
|
|
123
|
+
logger.error("AI Defense tool-call inspection error: %s", exc)
|
|
124
|
+
# Fail closed in enforce mode, open in monitor mode.
|
|
125
|
+
if self.config.mode == "enforce":
|
|
126
|
+
return InspectionResult.block([f"inspection error: {exc}"])
|
|
127
|
+
return InspectionResult.unprotected()
|
|
128
|
+
|
|
129
|
+
def inspect_response(self, tool_name: str, result_data: dict) -> InspectionResult:
|
|
130
|
+
client = self._client()
|
|
131
|
+
if client is None:
|
|
132
|
+
return InspectionResult.unprotected()
|
|
133
|
+
try:
|
|
134
|
+
result = client.inspect_response(
|
|
135
|
+
result_data=result_data,
|
|
136
|
+
method="tools/call",
|
|
137
|
+
params={"name": tool_name},
|
|
138
|
+
)
|
|
139
|
+
return self._normalize(result)
|
|
140
|
+
except Exception as exc:
|
|
141
|
+
logger.error("AI Defense response inspection error: %s", exc)
|
|
142
|
+
if self.config.mode == "enforce":
|
|
143
|
+
return InspectionResult.block([f"inspection error: {exc}"])
|
|
144
|
+
return InspectionResult.unprotected()
|
|
145
|
+
|
|
146
|
+
def _normalize(self, result) -> InspectionResult:
|
|
147
|
+
"""Map the SDK's response object onto our InspectionResult."""
|
|
148
|
+
inner = getattr(result, "result", result)
|
|
149
|
+
is_safe = bool(getattr(inner, "is_safe", True))
|
|
150
|
+
reasons: list[str] = []
|
|
151
|
+
for rule in getattr(inner, "rules", None) or []:
|
|
152
|
+
name = getattr(rule, "rule_name", None) or getattr(rule, "classification", "rule")
|
|
153
|
+
reasons.append(str(name))
|
|
154
|
+
if is_safe:
|
|
155
|
+
return InspectionResult.allow()
|
|
156
|
+
# In monitor mode we surface the finding but do not block.
|
|
157
|
+
if self.config.mode == "monitor":
|
|
158
|
+
logger.warning("AI Defense flagged (monitor): %s", ", ".join(reasons) or "unsafe")
|
|
159
|
+
return InspectionResult(safe=True, protected=True, reasons=reasons, action="allow")
|
|
160
|
+
return InspectionResult.block(reasons or ["policy violation"])
|
|
161
|
+
|
|
162
|
+
@property
|
|
163
|
+
def status(self) -> dict:
|
|
164
|
+
return {
|
|
165
|
+
"sdk_installed": self._available,
|
|
166
|
+
"enabled": self.config.enabled,
|
|
167
|
+
"mode": self.config.mode,
|
|
168
|
+
"runtime_protection": self._protected,
|
|
169
|
+
"inspection_configured": bool(self.config.can_inspect),
|
|
170
|
+
}
|