-
-
Notifications
You must be signed in to change notification settings - Fork 35
feat: add Sanitization Filter Layer for prompt injection detection #231
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
shrixtacy
merged 1 commit into
shrixtacy:master
from
ishanraj953:feat/sanitization-filter-layer
Mar 31, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| """ | ||
| Sanitization Filter Layer for AI Council. | ||
|
|
||
| Provides prompt injection detection and blocking before prompt construction. | ||
|
|
||
| Public API: | ||
| SanitizationFilter – main entry point; chains multiple BaseFilter instances | ||
| BaseFilter – abstract base for all filter implementations | ||
| KeywordFilter – exact / substring keyword matching | ||
| RegexFilter – precompiled regex pattern matching | ||
| FilterResult – result dataclass returned by every filter | ||
| Severity – enum for LOW / MEDIUM / HIGH rule severity | ||
| """ | ||
|
|
||
| from .base import BaseFilter, FilterResult, Severity | ||
| from .keyword_filter import KeywordFilter | ||
| from .regex_filter import RegexFilter | ||
| from .sanitization_filter import SanitizationFilter | ||
|
|
||
| __all__ = [ | ||
| "SanitizationFilter", | ||
| "BaseFilter", | ||
| "KeywordFilter", | ||
| "RegexFilter", | ||
| "FilterResult", | ||
| "Severity", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| """Abstract base classes and shared data types for the sanitization layer.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from abc import ABC, abstractmethod | ||
| from dataclasses import dataclass, field | ||
| from enum import Enum | ||
| from typing import List, Optional | ||
|
|
||
|
|
||
| class Severity(str, Enum): | ||
| """Severity level assigned to a matched rule.""" | ||
|
|
||
| LOW = "low" | ||
| MEDIUM = "medium" | ||
| HIGH = "high" | ||
|
|
||
|
|
||
| @dataclass | ||
| class FilterResult: | ||
| """Encapsulates the outcome of a single filter check. | ||
|
|
||
| Attributes: | ||
| is_safe: True when no threat was detected. | ||
| triggered_rule: Human-readable description of the rule that matched. | ||
| severity: Severity level of the detected threat. | ||
| matched_text: The portion of the input that triggered the rule. | ||
| filter_name: Name of the filter that produced this result. | ||
| """ | ||
|
|
||
| is_safe: bool = True | ||
| triggered_rule: Optional[str] = None | ||
| severity: Optional[Severity] = None | ||
| matched_text: Optional[str] = None | ||
| filter_name: str = "" | ||
|
|
||
| # Structured error payload returned to callers when the input is blocked. | ||
| @property | ||
| def error_response(self) -> dict: | ||
| """Return a structured error dict when the input was blocked.""" | ||
| if self.is_safe: | ||
| return {} | ||
| return { | ||
| "error": "Unsafe input detected. Request blocked due to potential prompt injection.", | ||
| "details": { | ||
| "filter": self.filter_name, | ||
| "rule": self.triggered_rule, | ||
| "severity": self.severity.value if self.severity else None, | ||
| }, | ||
| } | ||
|
|
||
|
|
||
| @dataclass | ||
| class RuleDefinition: | ||
| """A single configurable detection rule. | ||
|
|
||
| Attributes: | ||
| id: Unique identifier for the rule. | ||
| pattern: The keyword or regex pattern string. | ||
| severity: Severity when this rule fires. | ||
| enabled: Whether this rule is active. | ||
| description: Human-readable explanation of the rule. | ||
| """ | ||
|
|
||
| id: str | ||
| pattern: str | ||
| severity: Severity = Severity.HIGH | ||
| enabled: bool = True | ||
| description: str = "" | ||
|
|
||
|
|
||
| class BaseFilter(ABC): | ||
| """Abstract base class that every filter must implement. | ||
|
|
||
| Subclasses should be lightweight; their :meth:`check` method is called | ||
| synchronously in the hot path and must complete in well under 5 ms for | ||
| typical inputs. | ||
| """ | ||
|
|
||
| def __init__(self, name: str, rules: List[RuleDefinition]): | ||
| self._name = name | ||
| self._rules: List[RuleDefinition] = [r for r in rules if r.enabled] | ||
|
|
||
| @property | ||
| def name(self) -> str: | ||
| return self._name | ||
|
|
||
| @abstractmethod | ||
| def check(self, text: str) -> FilterResult: | ||
| """Inspect *text* and return a :class:`FilterResult`. | ||
|
|
||
| Args: | ||
| text: The raw user input to inspect. | ||
|
|
||
| Returns: | ||
| FilterResult with ``is_safe=True`` when no threat was detected. | ||
| """ | ||
|
|
||
| def add_rule(self, rule: RuleDefinition) -> None: | ||
| """Dynamically add a rule at runtime.""" | ||
| if rule.enabled: | ||
| self._rules.append(rule) | ||
|
|
||
| def disable_rule(self, rule_id: str) -> bool: | ||
| """Disable a rule by its id. Returns True if the rule was found.""" | ||
| before = len(self._rules) | ||
| self._rules = [r for r in self._rules if r.id != rule_id] | ||
| return len(self._rules) < before | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
FilterResult.error_response includes the triggered_rule string in the user-facing payload. Because KeywordFilter/RegexFilter fall back to embedding the raw keyword/regex pattern in triggered_rule when a rule has no description, this can leak detection patterns to end users and help attackers iterate around the filter. Consider returning only a generic message (and maybe a non-sensitive rule id/category) to callers, while keeping full match details only in logs/telemetry.