|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""A security guardrail plugin backed by Agent Threat Rules (ATR). |
| 16 | +
|
| 17 | +ATR (https://github.com/Agent-Threat-Rule/agent-threat-rules) is an open, |
| 18 | +MIT-licensed detection ruleset for AI-agent threats such as prompt injection, |
| 19 | +instruction override, and data exfiltration. This sample wires the `pyatr` |
| 20 | +engine into ADK's plugin callbacks so that a single plugin enforces policy |
| 21 | +*globally* across every agent, model call, and tool call managed by a Runner. |
| 22 | +
|
| 23 | +Install the engine before running: |
| 24 | +
|
| 25 | + pip install pyatr |
| 26 | +
|
| 27 | +Enforcement points (each one short-circuits the rest of the lifecycle): |
| 28 | + * `before_run_callback` -- halts the run on a malicious user message. |
| 29 | + * `before_model_callback` -- skips the model call if the assembled prompt |
| 30 | + still carries a threat (defense in depth, e.g. injected tool/context text). |
| 31 | + * `before_tool_callback` -- fails closed: returns an error dict instead of |
| 32 | + executing a tool whose arguments match a rule. |
| 33 | +""" |
| 34 | + |
| 35 | +from typing import Any |
| 36 | +from typing import Optional |
| 37 | + |
| 38 | +from google.adk.agents.callback_context import CallbackContext |
| 39 | +from google.adk.agents.invocation_context import InvocationContext |
| 40 | +from google.adk.models.llm_request import LlmRequest |
| 41 | +from google.adk.models.llm_response import LlmResponse |
| 42 | +from google.adk.plugins.base_plugin import BasePlugin |
| 43 | +from google.adk.tools.base_tool import BaseTool |
| 44 | +from google.adk.tools.tool_context import ToolContext |
| 45 | +from google.genai import types |
| 46 | + |
| 47 | +# pyatr is an optional, third-party engine (`pip install pyatr`). Import it |
| 48 | +# lazily so this sample module can still be imported for inspection without it. |
| 49 | +try: |
| 50 | + from pyatr import scan as _atr_scan |
| 51 | +except ImportError: # pragma: no cover - exercised only without pyatr installed |
| 52 | + _atr_scan = None |
| 53 | + |
| 54 | +# Ordering used to compare a match's severity against `min_severity`. |
| 55 | +_SEVERITY_RANK = { |
| 56 | + 'info': 0, |
| 57 | + 'low': 1, |
| 58 | + 'medium': 2, |
| 59 | + 'high': 3, |
| 60 | + 'critical': 4, |
| 61 | +} |
| 62 | + |
| 63 | + |
| 64 | +def _text_of(content: Optional[types.Content]) -> str: |
| 65 | + """Concatenate the text parts of a `types.Content`.""" |
| 66 | + if content is None or not content.parts: |
| 67 | + return '' |
| 68 | + return '\n'.join(part.text for part in content.parts if part.text) |
| 69 | + |
| 70 | + |
| 71 | +class AtrGuardrailPlugin(BasePlugin): |
| 72 | + """Blocks agent activity that matches an Agent Threat Rules signature.""" |
| 73 | + |
| 74 | + def __init__(self, min_severity: str = 'high') -> None: |
| 75 | + """Initialize the guardrail. |
| 76 | +
|
| 77 | + Args: |
| 78 | + min_severity: The lowest rule severity that should block. One of |
| 79 | + `info`, `low`, `medium`, `high`, `critical`. |
| 80 | + """ |
| 81 | + super().__init__(name='atr_guardrail') |
| 82 | + self.min_severity = min_severity |
| 83 | + self._threshold = _SEVERITY_RANK.get(min_severity, 3) |
| 84 | + |
| 85 | + def _first_block(self, text: str) -> Optional[Any]: |
| 86 | + """Return the highest-severity ATR match at/above the threshold, else None.""" |
| 87 | + if _atr_scan is None: |
| 88 | + raise RuntimeError( |
| 89 | + 'pyatr is not installed. Run `pip install pyatr` to enable the ATR' |
| 90 | + ' guardrail.' |
| 91 | + ) |
| 92 | + if not text.strip(): |
| 93 | + return None |
| 94 | + blocking = [ |
| 95 | + match |
| 96 | + for match in _atr_scan(text) |
| 97 | + if _SEVERITY_RANK.get(match.severity, 0) >= self._threshold |
| 98 | + ] |
| 99 | + if not blocking: |
| 100 | + return None |
| 101 | + return max(blocking, key=lambda m: _SEVERITY_RANK.get(m.severity, 0)) |
| 102 | + |
| 103 | + async def before_run_callback( |
| 104 | + self, *, invocation_context: InvocationContext |
| 105 | + ) -> Optional[types.Content]: |
| 106 | + """Halt the run if the user's message matches a threat rule.""" |
| 107 | + match = self._first_block(_text_of(invocation_context.user_content)) |
| 108 | + if match is None: |
| 109 | + return None |
| 110 | + print( |
| 111 | + f'[ATR] Blocked user message: rule {match.rule_id} ({match.severity}) -' |
| 112 | + f' {match.title}' |
| 113 | + ) |
| 114 | + return types.Content( |
| 115 | + role='model', |
| 116 | + parts=[ |
| 117 | + types.Part.from_text( |
| 118 | + text=f'Request blocked by ATR rule {match.rule_id}.' |
| 119 | + ) |
| 120 | + ], |
| 121 | + ) |
| 122 | + |
| 123 | + async def before_model_callback( |
| 124 | + self, *, callback_context: CallbackContext, llm_request: LlmRequest |
| 125 | + ) -> Optional[LlmResponse]: |
| 126 | + """Skip the model call if the assembled prompt still carries a threat.""" |
| 127 | + text = '\n'.join(_text_of(content) for content in llm_request.contents) |
| 128 | + match = self._first_block(text) |
| 129 | + if match is None: |
| 130 | + return None |
| 131 | + print( |
| 132 | + f'[ATR] Blocked model request: rule {match.rule_id} ({match.severity})' |
| 133 | + f' - {match.title}' |
| 134 | + ) |
| 135 | + return LlmResponse( |
| 136 | + content=types.Content( |
| 137 | + role='model', |
| 138 | + parts=[ |
| 139 | + types.Part.from_text( |
| 140 | + text=f'Request blocked by ATR rule {match.rule_id}.' |
| 141 | + ) |
| 142 | + ], |
| 143 | + ) |
| 144 | + ) |
| 145 | + |
| 146 | + async def before_tool_callback( |
| 147 | + self, |
| 148 | + *, |
| 149 | + tool: BaseTool, |
| 150 | + tool_args: dict[str, Any], |
| 151 | + tool_context: ToolContext, |
| 152 | + ) -> Optional[dict]: |
| 153 | + """Fail closed: refuse to run a tool whose arguments match a rule.""" |
| 154 | + text = '\n'.join(str(value) for value in tool_args.values()) |
| 155 | + match = self._first_block(text) |
| 156 | + if match is None: |
| 157 | + return None |
| 158 | + print( |
| 159 | + f'[ATR] Blocked tool `{tool.name}`: rule {match.rule_id}' |
| 160 | + f' ({match.severity}) - {match.title}' |
| 161 | + ) |
| 162 | + return { |
| 163 | + 'error': f'blocked by ATR rule {match.rule_id}', |
| 164 | + 'rule_id': match.rule_id, |
| 165 | + 'severity': match.severity, |
| 166 | + } |
0 commit comments