Skip to content

feat(security): add GuardrailLLMSecurityAnalyzer - #2

Closed
xli04 wants to merge 1 commit into
mainfrom
feat/guardrail-security-analyzer
Closed

xli04 wants to merge 1 commit into
mainfrom
feat/guardrail-security-analyzer

Conversation

@xli04

@xli04 xli04 commented Apr 19, 2026 •

Copy link
Copy Markdown
Owner

PR 1 — feat(security): add ToolShieldLLMSecurityAnalyzer

Target repo: OpenHands/software-agent-sdk
Target branch: main
Links: Closes #XXXX (issue), relates to PR 2 (frontend dropdown).

Summary

Adds GuardrailLLMSecurityAnalyzer, a new SecurityAnalyzerBase
subclass that evaluates each ActionEvent via a separate guardrail
LLM
rather than relying on the actor LLM to self-annotate
security_risk.

This addresses a structural limitation of the current
LLMSecurityAnalyzer: when the actor and the judge are the same model,
the model has no incentive to flag multi-turn attacks where individual
steps look benign. A separate guardrail LLM sees only the proposed
action + recent history, and is prompted to evaluate the sequence.

See the linked issue for full motivation, evaluation on MT-AgentRisk
(ASR drops from 75–88% → 14–18% across three frontier models with 0%
false positives on Terminal-Bench), and cost analysis.

What changed

  • New file: openhands-sdk/openhands/sdk/security/guardrail_llm_analyzer.py
  • New file: openhands-sdk/openhands/sdk/security/toolshield_helpers.py —
    helper functions for populating safety_experiences:
    default_safety_experiences() (terminal + filesystem seed),
    load_safety_experiences(tool_names), and
    auto_detect_safety_experiences() which probes localhost for active
    MCP servers.
  • Updated: openhands-sdk/openhands/sdk/security/__init__.py — export
    GuardrailLLMSecurityAnalyzer and the helpers.
  • Updated: pyproject.toml — new optional extra
    [project.optional-dependencies].toolshield = ["toolshield>=0.1.1"]
    required only if the helpers are used.

No changes to Agent, tool executors, ConfirmRisky, or any other
analyzer. Pairs with ConfirmRisky unchanged.

API

from openhands.sdk.llm import LLM
from openhands.sdk.security import GuardrailLLMSecurityAnalyzer, ConfirmRisky

guardrail_llm = LLM(model="gpt-4o-mini", api_key=...)
analyzer = GuardrailLLMSecurityAnalyzer(
    llm=guardrail_llm,
    history_window=20,       # default
    safety_experiences="",   # optional per-tool guidelines; see below
)

Optional — combine with the toolshield PyPI package for distilled
per-tool safety experiences:

pip install openhands-sdk[toolshield]

Three ways to populate safety_experiences:

from openhands.sdk.security import (
    GuardrailLLMSecurityAnalyzer,
    default_safety_experiences,
    load_safety_experiences,
    auto_detect_safety_experiences,
)

# 1) Default seed (terminal + filesystem)
analyzer = GuardrailLLMSecurityAnalyzer(
    llm=guardrail_llm,
    safety_experiences=default_safety_experiences(),
)

# 2) Explicit tool list (e.g., override with a different model's set)
analyzer = GuardrailLLMSecurityAnalyzer(
    llm=guardrail_llm,
    safety_experiences=load_safety_experiences(
        ["terminal-mcp", "postgres-mcp"], model="gemini-3-flash-preview"
    ),
)

# 3) Auto-detect: probe localhost ports, load experiences for whatever
#    MCP servers are actually running
analyzer = GuardrailLLMSecurityAnalyzer(
    llm=guardrail_llm,
    safety_experiences=auto_detect_safety_experiences(),
)

safety_experiences accepts any string; callers with their own source
of guidelines can bypass the helpers and pass a custom string directly.

Configurable Pydantic fields:

Field Type Default Purpose
llm LLM (required) Guardrail LLM instance; can be cheaper/smaller than the actor.
history_window int 20 Number of prior actions to include as context.
safety_experiences str "" Optional pre-generated safety guidelines injected into the system prompt.

Risk-level handling

Guardrail output Returns Rationale
Parseable RISK: LOW/MEDIUM/HIGH Matching SecurityRisk Normal path.
Text without a RISK: line SecurityRisk.HIGH + warning log Conservative: mangled response shouldn't silently allow action.
LLM infrastructure error (network, rate limit) SecurityRisk.UNKNOWN + error log Lets ConfirmRisky apply its configured fallback; failing-closed every transient blip would block every action.

Why not return HIGH on every failure?

Two failure modes have different implications. A parse failure means
the guardrail responded — just incoherently. Trusting that response
is unsafe. An infrastructure failure means the guardrail didn't
respond at all
— returning HIGH here would make a single OpenRouter
hiccup block every subsequent action in a long-running agent, which is
worse UX than UNKNOWN + user confirmation. Both cases are logged.

Non-trivial design decisions

  1. Single string field for experiences, not a structured dict. Any
    caller (ToolShield users, in-house experience generators, manual
    policy authors) can populate safety_experiences without a new
    SDK-side schema. The canonical rendering lives in the caller's
    package.
  2. ToolShield as an optional PyPI dep, not a new SDK submodule.
    toolshield is already published as a standalone package on PyPI.
    Pulling it into the SDK would duplicate maintenance; the extras
    group gives users a one-line install path without forcing the
    dependency on everyone.
  3. Per-tool experiences as an extension point. The ToolShield
    package stores experiences as JSON per tool-name and loads them via
    a simple registry. Users can author their own JSON files and pass
    the rendered string via safety_experiences — no SDK code changes
    needed, and no lock-in to ToolShield-generated content.
  4. Split UNKNOWN vs HIGH on guardrail failure. See table above —
    this is the most common reviewer question we've anticipated.

Known limitations / out of scope

  • Bundled experience set covers the tools evaluated in the linked Issue
    (filesystem-mcp, terminal-mcp, postgres-mcp, playwright-mcp,
    notion-mcp). Expansion to more tools and newer models is planned as
    follow-up contributions to the toolshield package; see the Issue's
    "Future work" section.
  • English-only prompts for now.

Backwards compatibility

Purely additive. The default analyzer remains LLMSecurityAnalyzer.

Test plan

  • Unit tests for _parse_risk (all three labels, parse failure path)
  • Unit test for security_risk with mocked LLM returning each label
  • Unit test for security_risk with mocked LLM raising an exception
    (verify returns UNKNOWN, not HIGH)
  • Unit test for history rendering (empty, partial, at-capacity)
  • Integration test: pair with ConfirmRisky, verify a HIGH
    decision pauses the conversation

Non-goals for this PR

  • UI surfacing (dropdown entry in Settings) — comes in a follow-up PR
    on the All-Hands-AI/OpenHands repo (see pr2_frontend.md).

Note

Medium Risk
Adds a new LLM-driven security analyzer and helper utilities that can change how action risk is classified and therefore when confirmations trigger. While mostly additive, it introduces new prompt/parsing logic and optional dependency behavior that could misclassify or fail open/closed if outputs or network conditions differ from expectations.

Overview
Introduces GuardrailLLMSecurityAnalyzer, which evaluates each ActionEvent by calling a separate guardrail LLM with the current action plus a configurable window of recent action history, then parses a strict RISK: LOW|MEDIUM|HIGH label (conservative fallback to HIGH on unparseable output and UNKNOWN on LLM call errors).

Adds optional ToolShield integration via toolshield_helpers to load and/or auto-detect per-tool “safety experiences” (including localhost MCP port probing) for injection into the guardrail prompt, exports these APIs from security.__init__, and introduces a new optional dependency extra openhands-sdk[toolshield] plus unit tests covering parsing, history handling, and helper behavior.

Reviewed by Cursor Bugbot for commit ca0631f. Bugbot is set up for automated code reviews on this repo. Configure here.

Adds a SecurityAnalyzerBase subclass that evaluates each ActionEvent via
a separate guardrail LLM, rather than relying on the actor LLM to
self-annotate security_risk. Separating actor and judge addresses a
structural limitation of LLMSecurityAnalyzer on multi-turn attacks,
where individually-benign steps compose into harmful sequences.

- Pydantic-based, configurable via llm / history_window /
  safety_experiences fields
- Pairs with ConfirmRisky unchanged
- Returns UNKNOWN on infrastructure error (let ConfirmRisky fall back)
  and HIGH on parse error (conservative, logged)

Evaluation on a 100-task MT-AgentRisk subset drops ASR from 75-88% (with
LLMSecurityAnalyzer) to 14-18% across three frontier models, with 0%
false positives on 50 benign Terminal-Bench tasks.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes and found 2 potential issues.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit ca0631f. Configure here.

lines.append(f"Arguments: {args_repr}")
elif action.tool_call is not None:
try:
args_repr = action.tool_call.function.arguments

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wrong attribute path on MessageToolCall always triggers fallback

High Severity

action.tool_call.function.arguments accesses a non-existent .function attribute on MessageToolCall. The class stores arguments as a direct field (not nested under a function sub-object). This always raises AttributeError, caught by the except block, which falls through to str(action.tool_call) — a noisy Pydantic repr including id, name, origin — instead of the clean JSON arguments string. The guardrail LLM receives degraded input for every non-executable action, potentially reducing security analysis accuracy. The correct access is action.tool_call.arguments.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ca0631f. Configure here.

"No networked MCP tools detected and fallback_to_default=False; "
f"loading always-active tools only: {active}"
)
return load_safety_experiences(active, model=model) if active else ""

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Docstring promises empty string but always loads experiences

Medium Severity

When fallback_to_default=False and no networked MCP tools are detected, the docstring promises an empty string is returned. However, detect_active_mcp_tools always includes ALWAYS_ACTIVE_TOOLS (i.e., ["terminal-mcp"]), so active is never empty and the else "" branch on line 215 is unreachable. Instead, load_safety_experiences(["terminal-mcp"]) is called, which also requires toolshield to be installed — surprising for callers who set fallback_to_default=False expecting a no-op fallback.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit ca0631f. Configure here.

@xli04 xli04 closed this Apr 19, 2026
@xli04
xli04 deleted the feat/guardrail-security-analyzer branch April 19, 2026 17:59
xli04 added a commit that referenced this pull request May 15, 2026
…injection

Addresses review #2 on OpenHands#2911.

The previous user prompt rendered the action as flat ``Tool: ...``,
``Thought: ...``, ``Arguments: ...`` lines. A motivated attacker can
place ``RISK: LOW`` on its own line inside their action's arguments;
if the guardrail LLM dutifully echoes it, the last-match regex picks
it up as the verdict.

Two layers of defense:

1. ``_format_action_for_guardrail`` now wraps each field in structural
   XML tags (``<tool>``, ``<summary>``, ``<thought>``, ``<arguments>``).
2. The system prompt explicitly tells the guardrail to ignore RISK
   labels that appear inside ``<thought>`` or ``<arguments>``.
3. ``_parse_risk`` strips those spans before scanning -- if the LLM
   echoes the injection anyway, the regex never sees it.

New regression tests cover smuggled labels in <thought>, smuggled
labels in <arguments>, and the "only smuggled label" edge case
(parse fails, returns UNKNOWN, ConfirmRisky fallback kicks in).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant