|
| 1 | +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | + |
| 16 | +"""Agent Threat Rules (ATR) detection rail. |
| 17 | +
|
| 18 | +Evaluates the input against Agent Threat Rules -- an open, community-maintained |
| 19 | +detection standard for AI-agent attacks (like Sigma, but for prompt injection, |
| 20 | +jailbreak, tool poisoning, MCP attacks, and skill compromise) -- via the |
| 21 | +``pyatr`` package. As an input rail it operates on the user message, so it is |
| 22 | +most effective against input-borne attacks such as prompt injection and |
| 23 | +jailbreak. Rules are bundled inside ``pyatr``; no rule files or API keys needed. |
| 24 | +""" |
| 25 | + |
| 26 | +import logging |
| 27 | +from typing import List, Optional, Set, TypedDict |
| 28 | + |
| 29 | +from nemoguardrails import RailsConfig |
| 30 | +from nemoguardrails.actions import action |
| 31 | + |
| 32 | +log = logging.getLogger(__name__) |
| 33 | + |
| 34 | +# ATR severities that flag the content by default. Lower severities |
| 35 | +# ("medium", "low") match but do not flag, keeping false positives low. |
| 36 | +DEFAULT_BLOCK_SEVERITIES = ("critical", "high") |
| 37 | + |
| 38 | + |
| 39 | +class ATRDetectionResult(TypedDict): |
| 40 | + """Result of evaluating text against Agent Threat Rules. |
| 41 | +
|
| 42 | + Attributes: |
| 43 | + flagged: True if a rule at or above the block severity matched. |
| 44 | + rules: Matched ATR rule IDs (e.g. ``["ATR-2026-00001"]``). |
| 45 | + max_severity: Highest matched severity, or None when nothing flagged. |
| 46 | + """ |
| 47 | + |
| 48 | + flagged: bool |
| 49 | + rules: List[str] |
| 50 | + max_severity: Optional[str] |
| 51 | + |
| 52 | + |
| 53 | +def _block_severities(config: Optional[RailsConfig]) -> Set[str]: |
| 54 | + """Read block severities from ``rails.config.atr``, falling back to default.""" |
| 55 | + try: |
| 56 | + atr_config = config.rails.config.atr # type: ignore[union-attr] |
| 57 | + severities = getattr(atr_config, "block_severities", None) or atr_config.get( |
| 58 | + "block_severities" |
| 59 | + ) |
| 60 | + if severities: |
| 61 | + return {str(s).lower() for s in severities} |
| 62 | + except (AttributeError, TypeError): |
| 63 | + pass |
| 64 | + return {s.lower() for s in DEFAULT_BLOCK_SEVERITIES} |
| 65 | + |
| 66 | + |
| 67 | +@action() |
| 68 | +async def atr_detection(text: str, config: RailsConfig) -> ATRDetectionResult: |
| 69 | + """Detect AI-agent threats in *text* using Agent Threat Rules. |
| 70 | +
|
| 71 | + Args: |
| 72 | + text: The text to evaluate (typically the user message for an input rail). |
| 73 | + config: The Rails configuration; ``rails.config.atr.block_severities`` |
| 74 | + overrides the default ``["critical", "high"]`` block list. |
| 75 | +
|
| 76 | + Returns: |
| 77 | + ATRDetectionResult with the flag, matched rule IDs, and max severity. |
| 78 | +
|
| 79 | + Raises: |
| 80 | + ImportError: If the ``pyatr`` package is not installed. |
| 81 | + """ |
| 82 | + try: |
| 83 | + from pyatr import scan |
| 84 | + except ImportError as exc: |
| 85 | + raise ImportError( |
| 86 | + "The `pyatr` package is required for the ATR rail. Install it with: pip install pyatr" |
| 87 | + ) from exc |
| 88 | + |
| 89 | + if not text: |
| 90 | + return ATRDetectionResult(flagged=False, rules=[], max_severity=None) |
| 91 | + |
| 92 | + block = _block_severities(config) |
| 93 | + matches = scan(text) # bundled ATR rules; returns matches sorted by severity |
| 94 | + blocking = [match for match in matches if match.severity.lower() in block] |
| 95 | + if not blocking: |
| 96 | + return ATRDetectionResult(flagged=False, rules=[], max_severity=None) |
| 97 | + |
| 98 | + rule_ids = [match.rule_id for match in blocking] |
| 99 | + log.info("ATR rail flagged input on rule(s): %s", ", ".join(rule_ids)) |
| 100 | + return ATRDetectionResult( |
| 101 | + flagged=True, rules=rule_ids, max_severity=blocking[0].severity |
| 102 | + ) |
0 commit comments