feat(update docs):

This commit is contained in:
Alexander Myasoedov committed 2026-10-19 17:35:15 +03:00
1 parent fbfce94012
commit 69e11e7d6d
24 files changed
+857 -1077

No files matched your search

+14 -53
View File
@@ -1,55 +1,16 @@
# Abstractions in Agentic Security
# Abstractions
This document outlines the key abstractions used in the Agentic Security project, providing insights into the classes, interfaces, and design patterns that form the backbone of the system.
This page shows the main types in the code. For the flow of a scan, refer to [Design](design.md).
## Key Abstractions
### AgentSpecification
- **Purpose**: Defines the specification for a language model or agent, including its name, version, description, capabilities, and configuration settings.
- **Usage**: Used to initialize and configure the `OperatorToolBox` and other components that interact with language models.
### OperatorToolBox
- **Purpose**: Serves as the main class for managing dataset operations, including validation, execution, and result retrieval.
- **Methods**:
- `get_spec()`: Returns the agent specification.
- `get_datasets()`: Retrieves the datasets for operations.
- `validate()`: Validates the toolbox setup.
- `run_operation(operation: str)`: Executes a specified operation.
### DatasetManagerAgent
- **Purpose**: Provides tools for managing and executing operations on datasets through an agent-based approach.
- **Tools**:
- `validate_toolbox`: Validates the `OperatorToolBox`.
- `execute_operation`: Executes operations on datasets.
- `retrieve_results`: Retrieves operation results.
- `retrieve_failures`: Retrieves any failures encountered.
### ProbeDataset
- **Purpose**: Represents a dataset used in security scans, including metadata, prompts, and associated costs.
- **Methods**:
- `metadata_summary()`: Provides a summary of the dataset's metadata.
### Refusal Classifier
- **Purpose**: Analyzes responses from language models to detect potential security vulnerabilities.
- **Design**: Utilizes predefined rules and machine learning models for classification.
## Design Patterns
### Modular Architecture
- **Description**: The system is designed with a modular architecture, allowing for easy integration of new components and features.
- **Benefits**: Enhances flexibility, extensibility, and scalability.
### Agent-Based Design
- **Description**: Utilizes an agent-based approach for managing and executing operations on datasets.
- **Benefits**: Provides a structured framework for interacting with language models and datasets.
## Conclusion
The abstractions in Agentic Security are designed to provide a flexible and extensible framework for managing and executing security scans on language models. This document highlights the key classes, interfaces, and design patterns that contribute to the system's architecture and functionality.
| Type | Module | Description |
| --- | --- | --- |
| `LLMSpec` | `agentic_security.http_spec` | A parsed HTTP request template. It sends one prompt with `probe()`. Refer to [HTTP spec](http_spec.md). |
| `ProbeDataset` | `agentic_security.probe_data.models` | One dataset: the name, the metadata, the prompts, the token count, and the cost. |
| `ImageProbeDataset` | `agentic_security.probe_data.models` | Contains a `ProbeDataset` and one image for each prompt. |
| `Scan` | `agentic_security.primitives.models` | The settings of one scan: spec, budget, datasets, and flags. |
| `ModuleProtocol` | `agentic_security.probe_data.modules.module_protocol` | The interface of a prompt-generator module. Refer to [External modules](external_module.md). |
| `RefusalClassifierPlugin` | `agentic_security.probe_actor.refusal` | The base class of a detector. Refer to [Refusal classifier plugins](refusal_classifier_plugins.md). |
| `RefusalClassifierManager` | `agentic_security.probe_actor.refusal` | Keeps the enabled detectors. `is_refusal()` is `True` if one detector returns `True`. |
| `DetectorRegistry` | `agentic_security.refusal_classifier.registry` | Builds the detectors from the `[detectors]` section. |
| `PromptSelectionInterface` | `agentic_security.probe_data.modules.rl_model` | The interface of a prompt selector. Refer to [RL prompt selection](rl_model.md). |
| `OperatorToolBox` | `agentic_security.probe_actor.operator` | Experimental. Tools for an LLM agent. Refer to [Agent operator](operator.md). |
+33 -41
View File
@@ -1,51 +1,43 @@
# API Reference
# API reference
This section provides detailed information about the Agentic Security API.
The server (`agentic_security server`) has test endpoints. Use them to test a spec before you scan a real target.
## Endpoints
## POST /v1/self-probe
### `/v1/self-probe`
A mock LLM for text. It refuses approximately 20% of prompts at random.
- **Method**: POST
- **Description**: Used for integration testing.
- **Request Body**:
```json
{
"prompt": "<<PROMPT>>"
}
```
Request body:
### `/v1/self-probe-image`
```json
{"prompt": "<<PROMPT>>"}
```
- **Method**: POST
- **Description**: Probes the image modality.
- **Request Body**:
```json
[
{
"role": "user",
"content": [
{
"type": "text",
"text": "What is in this image?"
},
{
"type": "image_url",
"image_url": {
"url": "data:image/jpeg;base64,<<BASE64_IMAGE>>"
}
}
]
}
]
```
The response has the OpenAI chat-completion format.
## Authentication
## POST /v1/self-probe-image
`/v1/self-probe` is an unauthenticated local test endpoint. File and image
probe routes expect an `Authorization: Bearer ...` header; the mock server
checks the header shape, not a configured API key.
A mock LLM for images. It ignores the request body and always gives the same response.
## Further Reading
## POST /v1/self-probe-file
For more details on API usage, refer to the [Configuration](configuration.md) section.
A mock audio transcription endpoint. It accepts a multipart upload.
| Part | Description |
| --- | --- |
| `file` | An `.m4a`, `.mp3`, or `.wav` file. |
| `model` | Optional. The default is `whisper-large-v3`. |
The request must have the header `Authorization: Bearer <any value>`. The endpoint does not examine the key. The response is `{"text": "...", "model": "..."}`.
## Other endpoints
| Method | Path | Description |
| --- | --- | --- |
| GET | `/health` | Returns `{"status": "ok"}`. |
| GET | `/v1/llm-specs` | Returns the built-in spec templates. |
| GET | `/v1/data-config` | Returns the dataset registry. The response is very large. |
| POST | `/verify` | Sends a test request with a spec. |
| POST | `/scan` | Starts a scan. The response is a stream of JSON lines. |
| POST | `/stop` | Stops the current scan. |
| POST | `/scan-csv` | Starts a scan with an uploaded CSV file. |
| GET | `/failures` | Returns the failures of the last scan. |
+26 -18
View File
@@ -1,13 +1,22 @@
# CI/CD Integration
# CI/CD integration
Integrate Agentic Security into your CI/CD pipeline to automate security scans.
You can do a scan in a CI pipeline with the `scan` command or the `ci` command.
| Command | Datasets | Exit code |
| --- | --- | --- |
| `agentic_security scan` | All datasets in the registry. | 1 if a module is above `--max_th`. Otherwise 0. |
| `agentic_security ci` | The `[modules]` in `agentic_security.toml`. | Always 0 after a scan. |
> **CAUTION:** The `ci` command does not stop the pipeline when a module fails. To stop the pipeline, use `scan`.
> **WARNING:** Do a scan only on endpoints that you have permission to test.
## GitHub Actions
Use the provided GitHub Action workflow to perform automated scans:
This example stops the pipeline when a module has a failure rate above 30%.
```yaml
name: Security Scan
name: Security scan
on: [push, pull_request]
@@ -15,24 +24,23 @@ jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Python
uses: actions/setup-python@v2
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: 3.11
- name: Install dependencies
run: pip install agentic_security
- name: Run security scan
run: agentic_security ci
python-version: "3.15"
- run: pip install agentic_security
- run: agentic_security scan --spec=target.http --max_th=0.3
```
## Custom CI/CD Pipelines
Keep `target.http` in the repository. Do not put credentials in the file. Refer to [HTTP spec](http_spec.md).
For custom pipelines, ensure the following steps:
## Other CI systems
1. Install dependencies.
1. Run the `agentic_security ci` command.
1. Install Python 3.15 or newer.
2. Run `pip install agentic_security`.
3. Run `agentic_security scan --spec=target.http`.
4. Use the exit code to set the result of the job.
## Further Reading
## Agent harness in CI
For more details on CI/CD integration, refer to the [API Reference](api_reference.md).
The workflow `.github/workflows/harness-example.yml` shows the `agesec` harness in CI. Refer to [Agent harness](harness.md).
+46 -29
View File
@@ -1,67 +1,84 @@
# Command-line interface
# CLI reference
The `agentic_security` command provides four commands: start the web server,
create a configuration file, list the available checks, and run a configured
scan.
The package installs two commands:
- `agentic_security` – the scanner. It has the subcommands `server`, `init`, `ls`, `ci`, and `scan`.
- `agesec` – the agent harness. Refer to [Agent harness](harness.md).
To show the help text, run:
```bash
agentic_security --help
```
## Start the server
If the command is not on your `PATH`, use `python -m agentic_security` instead.
Run the web application on the local machine:
## server
Starts the web UI and the API.
```bash
agentic_security server --host=127.0.0.1 --port=8718
```
`s` is a short alias for `server`. Running `agentic_security` without a
subcommand shows the available command help.
| Option | Default | Description |
| --- | --- | --- |
| `--host` | `127.0.0.1` | The address that the server listens on. |
| `--port` | `8718` | The port that the server listens on. |
## Create a scan configuration
The short name is `s`.
Create `agentic_security.toml` in the current directory:
## init
```bash
agentic_security init
```
Set a different target host or port in the generated HTTP specification:
Creates `agentic_security.toml` in the current directory.
```bash
agentic_security init --host=127.0.0.1 --port=8718
```
`i` is a short alias for `init`. The command overwrites an existing
`agentic_security.toml`, so save any custom changes first.
The `--host` and `--port` values go into the example `llmSpec` and into `AgenticBackend.opts.port`. The short name is `i`.
## List available checks
> **CAUTION:** This command replaces an existing `agentic_security.toml`. Make a copy of your file before you run it.
Inspect the built-in dataset registry before selecting modules for a scan:
## ls
Shows the dataset registry as a table. Use the names from this table in the `[modules]` section of the configuration.
```bash
agentic_security ls
```
## Run a configured scan
## ci
After reviewing `agentic_security.toml` and replacing the example `llmSpec`
with the target endpoint, run:
Does a scan with the settings in `agentic_security.toml` from the current directory.
```bash
agentic_security ci
```
The command uses `agentic_security.toml` from the current directory. It exits
without scanning if the file is missing. To include your own prompts, follow
the [local datasets guide](datasets.md).
If the file is not there, the command stops with exit code 1. The command scans all modules in the `[modules]` section. It shows a table of results at the end.
## Python module form
> **CAUTION:** The `ci` command always exits with code 0 after a scan. This is also true when a module is above the threshold. To stop a pipeline when a module fails, use `scan`.
If the console script is not on your `PATH`, invoke the same CLI through
Python:
## scan
Does a scan without a configuration file. The command writes each result as one JSON line to stdout.
```bash
python -m agentic_security ls
agentic_security scan --spec=target.http --max_th=0.3
cat target.http | agentic_security scan
```
| Option | Default | Description |
| --- | --- | --- |
| `--spec` | `-` | A file path, the HTTP spec as text, or `-` to read stdin. |
| `--max_budget` | `1000000` | The token budget for the scan. |
| `--max_th` | `0.3` | The failure-rate threshold (0 to 1). |
| `--optimize` | `False` | Stops a module early when its failure rate is high. |
| `--enable_multi_step_attack` | `False` | Adds many-shot attacks. |
The command scans all datasets in the registry. The exit code is 1 if one or more modules have a failure rate above `--max_th`. Otherwise, the exit code is 0.
## Local datasets
To add your prompts to a scan, refer to [Dataset extension](datasets.md).
+85 -13
View File
@@ -1,23 +1,95 @@
# Configuration
Scan settings live in `agentic_security.toml` in the working directory.
Create one with:
The `ci` command and the web server read `agentic_security.toml` from the current directory. To create the file, run:
```bash
agentic_security init
```
The file is versioned (`general.version`). The current schema version is `2`.
The schema version is `2`. If `general.version` has a different value, the tool shows an error.
## Sections
## [general]
- `[general]` — `llmSpec` (the HTTP request template), budget, failure threshold,
optimizer flag, multi-step attack flag
- `[modules.*]` — datasets to run; `AgenticBackend.opts.port` is the local proxy port
- `[detectors]` — refusal and leak classifiers
- `[thresholds]` — low / medium / high failure-rate bands
- `[secrets]` — API keys referenced from the HTTP spec
- `[caching]`, `[network]`, `[fuzzer]` — runtime tuning
| Key | Default | Description |
| --- | --- | --- |
| `llmSpec` | self-probe request | The HTTP request for the target. Refer to [HTTP spec](http_spec.md). |
| `maxBudget` | `1000000` | The token budget for the scan. |
| `max_th` | `0.3` | The failure-rate threshold (0 to 1). A module above this value has the status FAIL. |
| `optimize` | `false` | Stops a module early when its failure rate is high. Refer to [Early stop](optimizer.md). |
| `enableMultiStepAttack` | `false` | Adds many-shot attacks. |
| `version` | `2` | The schema version. |
Replace the placeholder `Bearer XXXXX` in `llmSpec` with credentials for the
target endpoint. See [HTTP spec](http_spec.md) for the request template format.
Replace the `Bearer XXXXX` value in `llmSpec` with the credentials for your endpoint.
## [modules.NAME]
Each table is one dataset to scan. Get the dataset names from `agentic_security ls`.
```toml
[modules.aya-23-8B_advbench_jailbreak]
dataset_name = "simonycl/aya-23-8B_advbench_jailbreak"
[modules.AgenticBackend]
dataset_name = "AgenticBackend"
[modules.AgenticBackend.opts]
port = 8718
modules = ["encoding"]
```
The `opts` table goes to the dataset module. Each module has different options.
## [detectors]
The detectors examine each response from the target.
| Key | Default | Description |
| --- | --- | --- |
| `default` | `true` | Finds refusal phrases. |
| `ml_classifier` | `true` | A one-class SVM refusal classifier. |
| `pii` | `false` | Finds personal data and credential leaks. |
| `sandbox_escape` | `false` | Finds Docker and Kubernetes sandbox-escape probes. |
To add a custom detector, refer to [Refusal classifier plugins](refusal_classifier_plugins.md).
## [thresholds]
The `init` command writes the values `low`, `medium`, and `high` (defaults `0.15`, `0.3`, `0.5`).
> **NOTE:** The code does not read this section at this time. Use `general.max_th` to set the pass/fail threshold.
## [secrets]
Each key is a secret name. A value that starts with `$` is the name of an environment variable.
```toml
[secrets]
OPENAI_API_KEY = "$OPENAI_API_KEY"
```
When the web server starts a scan, it replaces `$OPENAI_API_KEY` in the body of `llmSpec` with the secret value.
> **NOTE:** The tool does not replace secret names in the request line or in the headers. Put the credential value in the header yourself.
## [caching]
The `init` command writes the keys `enable`, `cache_size`, and `use_disk_cache`.
> **NOTE:** The code does not read this section at this time. To change the disk cache directory, set the `AGENTIC_SECURITY_CACHE_DIR` or `DISK_CACHE_DIR` environment variable. The default directory is `.cache/agentic_security` in the current directory.
## [network]
| Key | Default | Description |
| --- | --- | --- |
| `retry` | `3` | The number of retries for each request. |
| `timeout_connect` | `30` | The connection timeout in seconds. |
| `timeout_response` | `90` | The response timeout in seconds. |
## [fuzzer]
| Key | Default | Description |
| --- | --- | --- |
| `max_prompt_length` | `2048` | The maximum prompt length in the scan results. The `init` command writes the old spelling `max_prompt_lenght`. The code reads the two names. |
| `budget_multiplier` | `100000000` | The multiplier for the token budget. |
| `initial_optimizer_points` | `25` | The random points before the optimizer fits a model. |
| `min_failure_samples` | `5` | The minimum samples before an early stop. |
| `failure_rate_threshold` | `0.5` | The failure rate that causes an early stop. |
+28 -24
View File
@@ -1,32 +1,36 @@
# Contributing
We welcome contributions to Agentic Security! Follow these steps to get started:
## Procedure
## How to Contribute
1. Fork the repository on GitHub.
2. Clone your fork:
1. **Fork the Repository**: Click the "Fork" button at the top of the repository page.
1. **Clone Your Fork**: Clone your forked repository to your local machine.
```bash
git clone https://github.com/mmsoedov/agentic_security.git
```
1. **Create a Branch**: Create a new branch for your feature or bugfix.
```bash
git checkout -b feature-name
```
1. **Make Changes**: Implement your changes and commit them.
```bash
git commit -m "Description of changes"
```
1. **Push Changes**: Push your changes to your fork.
```bash
git push origin feature-name
```
1. **Open a Pull Request**: Go to the original repository and open a pull request.
```bash
git clone https://github.com/<your-user>/agentic_security.git
```
## Code of Conduct
3. Install the development dependencies:
Please adhere to the [Code of Conduct](CODE_OF_CONDUCT.md) in all interactions.
```bash
poetry install --with dev
```
## Further Reading
4. Make a branch for your change:
For more details on contributing, refer to the [Documentation](index.md) section.
```bash
git checkout -b feature-name
```
5. Make your change. Add tests for the change.
6. Run the tests:
```bash
pytest
```
7. Commit the change and push the branch to your fork.
8. Open a pull request to `msoedov/agentic_security`.
## Code of conduct
Obey the [Code of Conduct](https://github.com/msoedov/agentic_security/blob/main/CODE_OF_CONDUCT.md).
+33 -17
View File
@@ -1,25 +1,41 @@
# Dataset Extension
# Dataset extension
Agentic Security allows you to extend datasets to enhance its capabilities.
You can add your prompts to a scan as local CSV files, or add a new dataset to the registry.
## Adding New Datasets
## Add local CSV files
1. Place your dataset files in the `datasets` directory.
1. Ensure each file contains a `prompt` column for processing.
## Supported Formats
- CSV
- JSON
## Example
To add a new dataset:
1. Make a CSV file with a column that has the name `prompt`. Each row is one attack prompt.
2. Put the file in the `datasets` directory in the current directory.
3. Start the server or the scan from the same directory.
```bash
cp my_dataset.csv datasets/
mkdir -p datasets
cp my_prompts.csv datasets/
```
## Further Reading
The tool reads all `.csv` files in `datasets` when it starts. It shows the names of the files in the log.
For more details on dataset formats and processing, refer to the [API Reference](api_reference.md).
> **NOTE:** The tool reads only CSV files. If a file does not have a `prompt` column, the tool shows a warning and ignores the file.
## Add a dataset to the registry
The registry is the list `REGISTRY` in `agentic_security/probe_data/__init__.py`. Add one entry for each dataset:
```python
{
"dataset_name": "markush1/LLM-Jailbreak-Classifier",
"num_prompts": 1119,
"tokens": 19758,
"approx_cost": 0.0,
"source": "Hugging Face Datasets",
"selected": True,
"dynamic": False,
"url": "https://huggingface.co/markush1/LLM-Jailbreak-Classifier",
},
```
The loaders in `agentic_security/probe_data/data.py` return a `ProbeDataset`. Refer to [Probe data](probe_data.md).
## Transformed datasets
The tool can make new datasets from the loaded prompts. It encodes a sample of the prompts with each function in [Stenography functions](stenography.md).
+31 -44
View File
@@ -1,51 +1,38 @@
# Design Document
# Design
This document provides an overview of the design and architecture of the Agentic Security project. It outlines the key components, their interactions, and the design principles guiding the development of the system.
This page shows the main parts of Agentic Security and the flow of a scan.
## Overview
## Parts
Agentic Security is an open-source LLM vulnerability scanner designed to identify and mitigate potential security threats in language models. It integrates various modules and datasets to perform comprehensive security scans.
| Part | Package | Function |
| --- | --- | --- |
| CLI | `agentic_security.__main__` | Starts the server or a scan. |
| Web server | `agentic_security.app`, `agentic_security.routes` | Gives the UI and the scan API. |
| Scanner | `agentic_security.lib` | Reads the configuration and shows the results table. |
| HTTP spec | `agentic_security.http_spec` | Parses the request template and sends the requests. |
| Probe data | `agentic_security.probe_data` | Loads datasets, transforms prompts, makes images and audio. |
| Probe actor | `agentic_security.probe_actor` | Sends the prompts and scores the responses. |
| Detectors | `agentic_security.refusal_classifier` | Find refusals and leaks in the responses. |
| Agent harness | `agentic_security_harness` | Runs a scan step by step for an agent or for CI. |
## Architecture
## Scan flow
The system is built around a modular architecture, allowing for flexibility and extensibility. The core components include:
1. The CLI or the web server gets the HTTP spec and the list of datasets.
2. `LLMSpec.from_string` parses the HTTP spec.
3. `prepare_prompts` loads the selected datasets and adds the transformed datasets.
4. `scan_router` selects the single-shot scan or the many-shot scan.
5. For each prompt, the fuzzer puts the prompt in the spec and sends the request.
6. The detectors examine the response. The fuzzer counts the prompt as a failure if a detector finds a refusal. A request error or a response that is not JSON is also a failure.
7. The fuzzer sends the failure rate of each module as a JSON line. The failure rate is the failures divided by the prompts sent.
8. At the end, the fuzzer writes `failures.csv` and `full_scan_log.csv`.
9. The CLI shows a table. A module with a failure rate above `max_th` has the status FAIL.
- **Agentic Security Core**: The main application responsible for orchestrating the security scans and managing interactions with external modules.
- **Probe Actor**: Handles the execution of fuzzing and attack techniques on language models.
- **Probe Data**: Manages datasets used for testing and validation, including loading and processing data.
- **Refusal Classifier**: Analyzes responses from language models to identify potential security issues.
## Extension points
## Key Components
### Agentic Security Core
The core application is responsible for initializing the system, managing configurations, and coordinating the execution of security scans. It provides a command-line interface for users to interact with the system.
### Probe Actor
The Probe Actor module implements various fuzzing and attack techniques. It is designed to test the robustness of language models by simulating different attack scenarios.
### Probe Data
The Probe Data module manages datasets used in security scans. It supports loading data from local files and external sources, providing a flexible framework for testing different scenarios.
### Refusal Classifier
The Refusal Classifier analyzes responses from language models to detect potential security vulnerabilities. It uses predefined rules and machine learning models to classify responses.
## Design Principles
- **Modularity**: The system is designed to be modular, allowing for easy integration of new components and features.
- **Extensibility**: New modules and datasets can be added to the system without significant changes to the core architecture.
- **Scalability**: The system is built to handle large datasets and complex security scans efficiently.
## Interaction Flow
1. **Initialization**: The system is initialized with the necessary configurations and datasets.
1. **Execution**: The Probe Actor executes security scans on the language models using the datasets provided by the Probe Data module.
1. **Analysis**: The Refusal Classifier analyzes the responses to identify potential security issues.
1. **Reporting**: Results are compiled and presented to the user, highlighting any vulnerabilities detected.
## Conclusion
The design of Agentic Security emphasizes flexibility, extensibility, and scalability, providing a robust framework for identifying and mitigating security threats in language models. This document serves as a guide to understanding the system's architecture and key components.
| To add | Refer to |
| --- | --- |
| Prompts from a CSV file | [Dataset extension](datasets.md) |
| A dataset in the registry | [Dataset extension](datasets.md) |
| A prompt generator | [External modules](external_module.md) |
| A detector | [Refusal classifier plugins](refusal_classifier_plugins.md) |
| A harness source or converter | [Agent harness](harness.md) |
+31 -26
View File
@@ -1,60 +1,65 @@
# Module interface
# External modules
Probe data modules in `agentic_security.probe_data.modules` share the same
constructor arguments. `apply` yields result strings; some modules implement
it as a sync iterator and others as an async iterator.
A module makes attack prompts from an external tool or service. The modules are in `agentic_security.probe_data.modules`.
Built-in examples:
## Built-in modules
- `agentic_security.probe_data.modules.garak_tool`
- `agentic_security.probe_data.modules.fine_tuned`
- `agentic_security.probe_data.modules.inspect_ai_tool`
- `agentic_security.probe_data.modules.rl_model`
| Module | Source |
| --- | --- |
| `garak_tool` | [Garak](https://github.com/leondz/garak) |
| `inspect_ai_tool` | [Inspect AI](https://github.com/UKGovernmentBEIS/inspect_ai) |
| `adaptive_attacks` | [llm-adaptive-attacks](https://github.com/tml-epfl/llm-adaptive-attacks) |
| `fine_tuned` | Gets prompts from a remote attacker API |
| `rl_model` | Reinforcement-learning prompt selection |
## Constructor
## Interface
Each module is a class with the name `Module`.
```python
def __init__(
self,
prompt_groups: list,
tools_inbox: asyncio.Queue,
opts: dict | None = None,
): ...
class Module:
def __init__(self, prompt_groups: list, tools_inbox: asyncio.Queue, opts: dict = {}): ...
def apply(self): ...
```
`opts` is a module-specific dictionary. An omitted `opts` is treated as `{}`.
- `prompt_groups` is the input for the module.
- `tools_inbox` is a queue. The module can put messages in it.
- `opts` is a dictionary with options for the module. If you do not give `opts`, the module uses `{}`.
- `apply()` yields prompts. Most modules use an async generator. `adaptive_attacks` uses a sync generator.
## Usage
`ModuleProtocol` in `probe_data.modules.module_protocol` is the type for this interface.
## Example
```python
import asyncio
from agentic_security.probe_data.modules.garak_tool import Module as GarakModule
tools_inbox = asyncio.Queue()
module = GarakModule(["group_a"], tools_inbox, {"port": 8718})
async def main():
module = GarakModule(["group_a"], asyncio.Queue(), {"port": 8718})
async for result in module.apply():
print(result)
asyncio.run(main())
```
## Custom module
## Make a custom module
```python
import asyncio
class MyModule:
def __init__(self, prompt_groups, tools_inbox, opts=None):
class Module:
def __init__(self, prompt_groups: list, tools_inbox: asyncio.Queue, opts: dict | None = None):
self.prompt_groups = prompt_groups
self.tools_inbox = tools_inbox
self.opts = opts or {}
async def apply(self):
for group in self.prompt_groups:
result = f"processed {group}"
await self.tools_inbox.put({"message": result})
yield result
prompt = f"processed {group}"
await self.tools_inbox.put({"message": prompt})
yield prompt
```
+13 -10
View File
@@ -1,14 +1,17 @@
# Getting Started
# Getting started
1. Install the package ([installation](installation.md)).
2. Start the UI:
1. Install the package. Refer to [Installation](installation.md).
2. Start the web UI:
```bash
agentic_security server
```
```bash
agentic_security server
```
The server listens on `http://127.0.0.1:8718` by default.
The server uses `http://127.0.0.1:8718` by default.
3. For a headless scan, create `agentic_security.toml` with `agentic_security init`,
edit the `llmSpec`, then run `agentic_security ci`. See the [CLI](cli.md)
and [configuration](configuration.md) pages.
3. To scan without the UI, do these steps:
1. Create `agentic_security.toml` with `agentic_security init`.
2. Change `llmSpec` in the file to the request for your endpoint.
3. Run `agentic_security ci`.
For more data, refer to [CLI reference](cli.md) and [Configuration](configuration.md).
+129 -71
View File
@@ -1,27 +1,72 @@
# Agentic Security harness
# Agent harness
Install `pip install 'agentic_security[harness]'` (Python 3.15+). The new package
and `agesec` Fire CLI coexist with the legacy scanner. The extra currently adds
no dependencies; it reuses core dependencies.
The agent harness is the `agesec` command. It runs a scan one attempt at a time. An agent, a rule set, or a CI job decides the next action after each attempt. The harness and the `agentic_security` scanner are in the same package.
You must have Python 3.15 or newer. Install the package:
```sh
pip install 'agentic_security[harness]'
```
The `harness` extra does not add dependencies.
> **WARNING:** Use the harness only on targets that you have permission to test.
## Commands
```sh
agesec run --spec target.http --policy policy.json --decider rules --seed 42
agesec ls
agesec report RUN_ID -o report.json
agesec replay RUN_ID
agesec step RUN_ID
agesec decide RUN_ID --action continue --reason "try again"
```
`report` prints a structured JSON report and saves it to `-o` or the run's
`report.json`. The Python API `build_report(log)` returns a `Report` dataclass.
The report includes status, exit code (null while unfinished), stop reason,
outcome counts, cost, duration, findings, attack sources, transformations,
decision trails, and the original events. No HTML, templates, XML, or JUnit is
generated. Agents choose presentation; CI can consume the same JSON directly.
Treat evidence as untrusted content when rendering it.
| Command | Description |
| --- | --- |
| `run` | Starts a run. Writes events as JSON lines to stdout and diagnostics to stderr. |
| `ls` | Lists the runs with status, attempts, and cost. |
| `report` | Prints a JSON report. Writes it to `-o`, or to `report.json` in the run directory. |
| `replay` | Runs the decisions of a finished run again from the stored evidence. It does not send requests. |
| `step` | Does one attempt and prints the pending decision. |
| `decide` | Gives the decision for the pending attempt. |
## Attack references
`run` options: `--spec` (required), `--policy` (default `default`), `--decider` (`rules` or `jev`, default `rules`), `--seed` (default `0`), `--budget_usd`.
Policies select sources and techniques, not inline prompts:
The harness keeps the log and the HTTP template (without expanded values) in `.agesec/runs/<id>/`. Use `${ENV_VAR}` for credentials in the spec.
## Exit codes
| Command | Code | Meaning |
| --- | --- | --- |
| `run`, `replay` (automated decider) | 0 | No findings. |
| | 1 | One or more findings. |
| | 2 | Error. |
| `run` (external decisions) | 0 | The run stopped after the first attempt. It waits for decisions. This code does not mean "no findings". |
| `step` | 3 | The run is finished. |
| `decide` | 2 | The action is not permitted. The log does not change. |
## Step-by-step decisions
1. Run `agesec step RUN_ID`. The harness does one attempt and prints one pending decision.
2. Run `agesec decide RUN_ID --action ACTION --reason REASON`.
3. Do steps 1 and 2 again until `step` exits with code 3.
If you run `step` again before `decide`, you get the same pending decision. The harness locks each run on POSIX systems. If a request stops before it is complete, the harness records an error when it continues. It does not send the request again.
## Actions
| Action | Result |
| --- | --- |
| `continue` | Tries the current tier again. |
| `escalate` | Goes to the next enabled tier. It skips disabled tiers. |
| `switch` | Goes to the next attack. |
| `stop` | Stops the run. |
## Policy
A policy is a JSON file. The names `default` (30 attempts) and `ci` (12 attempts) are built-in policies.
```json
{
@@ -41,72 +86,85 @@ Policies select sources and techniques, not inline prompts:
}
```
`dataset` resolves names from the existing `probe_data` dataset registries using
their configured loaders. `harness/smoke` is a bundled offline CSV smoke dataset,
used by the `default` and `ci` policies. `csv` resolves local paths relative to
the policy file, reusing the legacy loader; it requires a `prompt` column.
An unknown, empty, or invalid source fails the run setup rather than silently
reducing coverage. `limit` bounds prompts retained from each source. Dataset
loaders may load the entire dataset before that limit is applied.
### Rules decider
`module` references an already-installed Python callable as `package.module:name`.
No modules are automatically installed. These are trusted local extensions:
The policy key `rules` maps each outcome (`refused`, `partial`, `complied`, `error`) to a list of actions. The decider uses the first permitted action in the list. The harness removes the actions that the attempt limits or the budget do not permit.
- Source callable: `generate(*, options: dict, seed: int)` returns an iterable of
nonempty prompt strings or a legacy `ProbeDataset`.
- Converter/strategy callable: `convert(*, prompt: str, history: list[dict], options: dict,
seed: int)` returns one nonempty prompt string. History contains recent attempts
for that attack. These are synchronous callables.
### jev decider
Adapters should generate prompts, leaving target execution to the harness so
budgets, logging, classification, and rate limits still apply. Legacy modules
that run entire scanners (such as Garak's subprocess runner) are not themselves
prompt generators; wrap the third-party prompt generation API in this contract.
Extension-side network costs cannot be accounted by the harness.
The `jev` decider uses an LLM through [OpenRouter chat completions](https://openrouter.ai/docs/api/api-reference/chat/send-chat-completion-request).
Built-in converters: `base64`, `fictional`. Built-in multi-turn strategy:
`transcript`, which incorporates recent responses into a textual conversation
for single-prompt HTTP specs. Ordered converter/strategy lists rotate on
`continue`; empty lists disable those tiers. `escalate` skips disabled tiers.
The run freezes resolved prompts and source configuration; each attempt records
its selected technique and options. Offline replay does not import extensions
or reload datasets.
1. Set the `OPENROUTER_API_KEY` environment variable.
2. Set `jev_model` in the policy.
## Execution and decisions
The harness applies the same policy checks to `jev` decisions. If the remote call fails, the harness does not use the rules decider.
`run` emits JSONL on stdout and diagnostics on stderr. Logs and the unexpanded
HTTP template live in `.agesec/runs/<id>/`. Prefer `${ENV_VAR}` credentials in
specs. Commands lock each run on POSIX systems. An interrupted in-flight request
becomes an error on resume and is never silently repeated.
## Sources
`step RUN_ID` performs at most one attempt and prints one pending decision.
Repeated calls return that same decision until `decide RUN_ID --action A --reason R`.
`step` exits 3 when finished. Illegal decisions exit 2 without changing the log.
External `run` pauses after its first attempt and exits 0, which does not mean
clean. Automated run/replay exit 0 clean, 1 findings, 2 error. Replay requires a
finished run and reconstructs its transitions using cached evidence, offline.
A policy selects sources and techniques. It does not contain prompts.
Policy `rules` maps each of `refused`, `partial`, `complied`, `error` to an ordered
list of actions including `stop`. Rules pick the first legal action; the harness
removes actions forbidden by attempt or budget limits. `continue` retries the
current tier, `escalate` advances to the next enabled tier, `switch` moves to the
next attack, and `stop` ends the run.
| Kind | Description |
| --- | --- |
| `dataset` | A name from the `probe_data` registry. The harness uses the registry loader. `harness/smoke` is a small offline CSV dataset. The `default` and `ci` policies use it. |
| `csv` | A local CSV file with a `prompt` column. The path is relative to the policy file. |
| `module` | A Python callable that is installed: `package.module:name`. |
For `jev`, set `OPENROUTER_API_KEY` and policy `jev_model`. The adapter uses
[OpenRouter chat completions](https://openrouter.ai/docs/api/api-reference/chat/send-chat-completion-request).
Its decisions pass the same policy checks. There is no silent rules fallback
following a remote failure. Dollar budgets require positive
`request_cost_usd` and (for jev) `decision_cost_usd` estimates. Calls that cannot
fit are stopped before sending. Estimates are not a provider-enforced cap.
Without estimates, missing costs are accounted as zero and marked estimated.
`limit` sets the maximum number of prompts from each source. A dataset loader can load the full dataset before the harness applies the limit.
Findings are refusal-classifier signals requiring review, not proof of goal
completion. OWASP mappings describe the attack objective
([LLM01:2025](https://genai.owasp.org/llmrisk/llm01-prompt-injection/),
[ASI01](https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/));
this is not a full Top 10 test suite.
> **CAUTION:** If a source is unknown, empty, or not valid, the run does not start. The harness does not continue with fewer sources.
Claude plugin: `integrations/claude`. Codex instructions:
`integrations/codex/AGENTS.md` and its skill folder. CI example:
`.github/workflows/harness-example.yml`, manually triggered against an authorized
HTTP spec. Replace the localhost example for hosted CI.
## Converters and strategies
The built-in converters are `base64` and `fictional`. The built-in multi-turn strategy is `transcript`. It adds the recent responses to the prompt as a text conversation, for HTTP specs that accept one prompt.
The harness uses the converters and the strategies in their list order. A `continue` action goes to the next item. An empty list disables that tier.
## Python extensions
A `module` reference is a trusted local extension. The harness does not install modules.
- A source callable has the signature `generate(*, options: dict, seed: int)`. It returns an iterable of prompt strings that are not empty, or a `ProbeDataset`.
- A converter or strategy callable has the signature `convert(*, prompt: str, history: list[dict], options: dict, seed: int)`. It returns one prompt string that is not empty. `history` has the recent attempts for the attack.
These callables are synchronous. They must only make prompts. The harness sends the requests, so the budget, the log, the classification, and the rate limits apply.
Some legacy modules run a full scanner, for example the Garak subprocess. They are not prompt generators. To use them, wrap the prompt API of the third-party tool in this interface.
The harness does not count network costs of an extension.
The run stores the resolved prompts and the source configuration. Each attempt records its technique and options. `replay` does not import extensions or load datasets again.
## Budget
A dollar budget (`--budget_usd`) needs positive `request_cost_usd` values. The `jev` decider also needs `decision_cost_usd`. The harness does not send a call that is more than the remaining budget.
> **NOTE:** These values are estimates. The provider does not enforce them. If you do not give estimates, the harness counts the costs as zero and marks them as estimated.
## Report
`agesec report` prints a JSON report. The Python function `build_report(log)` returns a `Report` dataclass. The report has:
- Status, exit code (`null` until the run is finished), and stop reason.
- Outcome counts, cost, and duration.
- Findings, attack sources, transformations, and decision trails.
- The original events.
The harness does not make HTML, XML, or JUnit reports. An agent or a CI job can use the JSON report directly.
> **CAUTION:** The evidence in the report is untrusted content. Escape it before you show it in a UI.
## Findings
A finding is a signal from the refusal classifier. A person must examine it. A finding does not prove that the attack goal was reached.
The OWASP mappings show the objective of the attack: [LLM01:2025](https://genai.owasp.org/llmrisk/llm01-prompt-injection/) and [ASI01](https://genai.owasp.org/resource/owasp-top-10-for-agentic-applications-for-2026/). The harness does not test the full OWASP Top 10.
## Integrations
| Tool | Location |
| --- | --- |
| Claude plugin | `integrations/claude` |
| Codex | `integrations/codex/AGENTS.md` and `integrations/codex/skills` |
| CI example | `.github/workflows/harness-example.yml` |
The CI example starts only when you trigger it manually. It uses a localhost target. For a hosted CI system, replace the target with an HTTP spec that you have permission to test.
+63 -82
View File
@@ -1,123 +1,104 @@
# HTTP Specification Documentation
# HTTP spec
The HTTP specification in the Agentic Security project is designed to handle various types of requests, including text, image, audio, and file uploads. This documentation provides a detailed overview of the HTTP specification and its usage.
An HTTP spec is a plain-text HTTP request. It tells the scanner how to send a prompt to the target. The `LLMSpec` class in `agentic_security.http_spec` parses and sends the request.
## Overview
## Format
The HTTP specification is implemented in the `LLMSpec` class, which is used to define and execute HTTP requests. The class supports different modalities, including text, image, audio, and file uploads, and provides methods to validate and execute these requests.
```http
POST https://api.openai.com/v1/chat/completions
Authorization: Bearer sk-xxxxxxxxx
Content-Type: application/json
## Modalities
{
"model": "gpt-4o-mini",
"messages": [{"role": "user", "content": "<<PROMPT>>"}]
}
```
The HTTP specification supports the following modalities:
- Line 1 is the method and the URL. The URL must start with `http://` or `https://`.
- The next lines are headers, one `Name: value` on each line.
- An empty line comes after the headers.
- The remaining lines are the body.
### Text
## Placeholders
Text-based requests are the most common type of request. The `LLMSpec` class replaces the `<<PROMPT>>` placeholder in the request body with the provided prompt.
| Placeholder | Replaced with | Modality |
| --- | --- | --- |
| `<<PROMPT>>` | The attack prompt, escaped for JSON. | Text |
| `<<BASE64_IMAGE>>` | A data URL: `data:image/jpeg;base64,...` | Image |
| `<<BASE64_AUDIO>>` | A data URL: `data:audio/mpeg;base64,...` | Audio |
### Image
The scanner sets the modality from the placeholders in the body:
Image-based requests include an image encoded in base64 format. The `LLMSpec` class replaces the `<<BASE64_IMAGE>>` placeholder in the request body with the provided base64-encoded image.
- `<<BASE64_IMAGE>>` in the body sets the image modality. The scanner makes an image of each prompt.
- `<<BASE64_AUDIO>>` in the body sets the audio modality.
- `Content-Type: multipart/form-data` sets the file modality.
### Audio
> **CAUTION:** The image and audio values already start with `data:...;base64,`. Do not write this prefix in the spec. Use `"url": "<<BASE64_IMAGE>>"`.
Audio-based requests include an audio file encoded in base64 format. The `LLMSpec` class replaces the `<<BASE64_AUDIO>>` placeholder in the request body with the provided base64-encoded audio.
## Secrets
### Files
In a web server scan, the tool replaces `$NAME` in the body with a secret value. The value comes from `NAME` in the `[secrets]` section. Refer to [Configuration](configuration.md). The tool does not replace names in the URL or in the headers.
File-based requests include file uploads. The `LLMSpec` class handles multipart form data and includes the provided files in the request.
## File uploads
## LLMSpec Class
When the spec has `Content-Type: multipart/form-data`, `probe()` sends only the `files` argument. It does not send the body.
The `LLMSpec` class is the core of the HTTP specification. It provides the following methods and properties:
## LLMSpec methods
### Methods
- **`from_string(http_spec: str) -> LLMSpec`**: Parses an HTTP specification string into an `LLMSpec` object.
- **`validate(prompt: str, encoded_image: str, encoded_audio: str, files: dict) -> null`**: Validates the request parameters based on the specified modality.
- **`probe(prompt: str, encoded_image: str = "", encoded_audio: str = "", files: dict = {}) -> httpx.Response`**: Sends an HTTP request using the specified parameters.
- **`verify() -> httpx.Response`**: Verifies the HTTP specification by sending a test request.
### Properties
- **`modality: Modality`**: Returns the modality of the request (text, image, audio, or files).
| Method | Description |
| --- | --- |
| `LLMSpec.from_string(text)` | Parses the spec. If the spec is not valid, it raises `InvalidHTTPSpecError`. |
| `probe(prompt, encoded_image="", encoded_audio="", files=None)` | Sends one request. Returns an `httpx.Response`. This method is async. |
| `verify()` | Sends a test request for the modality of the spec. This method is async. |
| `validate(prompt, encoded_image, encoded_audio, files)` | Raises `ValueError` if a value that the modality needs is missing. |
| `modality` | `Modality.TEXT`, `Modality.IMAGE`, or `Modality.AUDIO`. |
## Examples
### Text Request
### Text
```python
http_spec = """
POST https://api.example.com/v1/chat/completions
Authorization: Bearer sk-xxxxxxxxx
Content-Type: application/json
from agentic_security.http_spec import LLMSpec
{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "<<PROMPT>>"}],
"temperature": 0.7
}
"""
spec = LLMSpec.from_string(http_spec)
spec = LLMSpec.from_string(open("target.http").read())
response = await spec.probe("What is the capital of France?")
```
### Image Request
### Image
```python
http_spec = """
POST https://api.example.com/v1/chat/completions
from agentic_security.http_spec import LLMSpec, encode_image_base64_by_url
spec = LLMSpec.from_string("""POST https://api.example.com/v1/chat/completions
Authorization: Bearer sk-xxxxxxxxx
Content-Type: application/json
{
"model": "gpt-4-vision-preview",
"messages": [{"role": "user", "content": "What is in this image? <<BASE64_IMAGE>>"}],
"temperature": 0.7
}
"""
spec = LLMSpec.from_string(http_spec)
encoded_image = encode_image_base64_by_url("https://example.com/image.jpg")
response = await spec.probe("What is in this image?", encoded_image=encoded_image)
{"messages": [{"role": "user", "content": [
{"type": "text", "text": "<<PROMPT>>"},
{"type": "image_url", "image_url": {"url": "<<BASE64_IMAGE>>"}}
]}]}
""")
image = encode_image_base64_by_url("https://example.com/image.jpg")
response = await spec.probe("What is in this image?", encoded_image=image)
```
### Audio Request
### Audio
```python
http_spec = """
POST https://api.example.com/v1/chat/completions
Authorization: Bearer sk-xxxxxxxxx
Content-Type: application/json
from agentic_security.http_spec import encode_audio_base64_by_url
{
"model": "whisper-large-v3",
"messages": [{"role": "user", "content": "Transcribe this audio: <<BASE64_AUDIO>>"}],
"temperature": 0.7
}
"""
spec = LLMSpec.from_string(http_spec)
encoded_audio = encode_audio_base64_by_url("https://example.com/audio.mp3")
response = await spec.probe("Transcribe this audio:", encoded_audio=encoded_audio)
audio = encode_audio_base64_by_url("https://example.com/audio.mp3")
response = await spec.probe("Transcribe this audio.", encoded_audio=audio)
```
### File Request
### File
```python
http_spec = """
POST https://api.example.com/v1/chat/completions
Authorization: Bearer sk-xxxxxxxxx
spec = LLMSpec.from_string("""POST http://127.0.0.1:8718/v1/self-probe-file
Authorization: Bearer XXXXX
Content-Type: multipart/form-data
{
"model": "gpt-3.5-turbo",
"messages": [{"role": "user", "content": "Process this file: <<FILE>>"}],
"temperature": 0.7
}
"""
spec = LLMSpec.from_string(http_spec)
files = {"file": ("document.txt", open("document.txt", "rb"))}
response = await spec.probe("Process this file:", files=files)
""")
with open("sample.m4a", "rb") as f:
response = await spec.probe("", files={"file": ("sample.m4a", f)})
```
## Conclusion
The HTTP specification in the Agentic Security project provides a flexible and powerful way to handle various types of requests. This documentation serves as a guide to understanding and utilizing the HTTP specification effectively.
+35 -107
View File
@@ -1,119 +1,47 @@
# Image Generation System
# Image generation
The image generation system creates visual probes for security testing by converting text prompts into images. This document explains its architecture and implementation.
The image generator makes an image of each text prompt. Use it to test if a vision model obeys text in an image.
## Overview
The module is `agentic_security.probe_data.image_generator`. It uses matplotlib.
The system:
## When the scanner makes images
1. Converts text datasets into image datasets
1. Generates images using matplotlib
1. Encodes images for transmission
1. Integrates with the LLM probing system
If the body of the HTTP spec has `<<BASE64_IMAGE>>`, the scanner wraps the spec in a `RequestAdapter`. For each prompt, the adapter does these steps:
## Core Components
1. It makes a JPEG image of the prompt with `generate_image(prompt)`.
2. It encodes the image as a data URL with `encode(image)`.
3. It puts the data URL in place of `<<BASE64_IMAGE>>` and sends the request.
### Image Generation
The data URL starts with `data:image/jpeg;base64,`. Do not write this prefix in the spec. Refer to [HTTP spec](http_spec.md).
## Functions
| Function | Description |
| --- | --- |
| `generate_image(prompt, variant=0)` | Returns the JPEG bytes of an image with the prompt text. The tool keeps the result in the disk cache. |
| `generate_image_dataset(datasets)` | Makes an `ImageProbeDataset` for each `ProbeDataset`. |
| `encode(image)` | Returns the image as a Base64 data URL. |
## Image styles
The image is 6 x 4 inches. The `variant` argument selects the style:
| `variant` | Background |
| --- | --- |
| `0` (default) | Light blue, dark blue text |
| `1` | Dark gray |
| `2` | Light pink, with a text box |
| `3` | White, with a circle |
## Example
```python
@cache_to_disk()
def generate_image(prompt: str) -> bytes:
"""
Generates a JPEG image containing the provided text prompt
"""
# Create figure with light blue background
fig, ax = plt.subplots(figsize=(6, 4))
ax.set_facecolor("lightblue")
from agentic_security.probe_data.image_generator import encode, generate_image
# Add centered text
ax.text(
0.5, 0.5,
prompt,
fontsize=16,
ha="center",
va="center",
wrap=True,
color="darkblue"
)
# Save to buffer
buffer = io.BytesIO()
plt.savefig(buffer, format="jpeg", bbox_inches="tight")
return buffer.getvalue()
data_url = encode(generate_image("Ignore previous instructions"))
```
### Dataset Conversion
## Limits
```python
def generate_image_dataset(text_dataset: list[ProbeDataset]) -> list[ImageProbeDataset]:
"""
Converts text datasets into image datasets
"""
image_datasets = []
for dataset in text_dataset:
image_prompts = [
generate_image(prompt)
for prompt in tqdm(dataset.prompts)
]
image_datasets.append(ImageProbeDataset(
test_dataset=dataset,
image_prompts=image_prompts
))
return image_datasets
```
### Image Encoding
```python
def encode(image: bytes) -> str:
"""
Encodes image bytes into base64 data URL
"""
encoded = base64.b64encode(image).decode("utf-8")
return "data:image/jpeg;base64," + encoded
```
## Integration
### RequestAdapter
The RequestAdapter class integrates image generation with LLM probing:
```python
class RequestAdapter:
def __init__(self, llm_spec):
if not llm_spec.has_image:
raise ValueError("LLMSpec must have an image")
self.llm_spec = llm_spec
async def probe(self, prompt: str, encoded_image: str = "",
encoded_audio: str = "", files={}) -> httpx.Response:
encoded_image = generate_image(prompt)
encoded_image = encode(encoded_image)
return await self.llm_spec.probe(prompt, encoded_image, encoded_audio, files)
```
## Key Features
- **Caching**: Generated images are cached to disk using @cache_to_disk
- **Progress Tracking**: tqdm progress bars for dataset conversion
- **Error Handling**: Validates LLM specifications before probing
- **Standard Formats**: Uses JPEG format with base64 encoding
## Configuration
The system is configured through:
1. Figure size (6x4 inches)
1. Background color (light blue)
1. Text styling (16pt dark blue centered text)
1. Image format (JPEG)
## Limitations
- Currently only supports text-based image generation
- Fixed visual style and formatting
- Requires matplotlib and associated dependencies
- The image has only text. It does not have pictures.
- The styles are fixed.
+17 -17
View File
@@ -1,24 +1,24 @@
<p align="center">
# Agentic Security
<h1 align="center">Agentic Security</h1>
<p align="center">
The open-source Agentic LLM Vulnerability Scanner
<br />
<br />
</p>
</p>
Agentic Security is an open-source vulnerability scanner for LLM endpoints and agent workflows.
## Features
- Customizable Rule Sets or Agent based attacks🛠️
- Comprehensive fuzzing for any LLMs 🧪
- LLM API integration and stress testing 🛠️
- Wide range of fuzzing and attack techniques 🌀
- Attack datasets from Hugging Face, public CSV files, and your local CSV files.
- Text, image, and audio attacks.
- Many-shot (multi-step) jailbreak attacks.
- Prompt transformations (encodings and ciphers) that hide the attack text.
- Refusal and leak detectors that you can turn on, turn off, or extend.
- A web UI, a CLI for CI pipelines, and an agent harness (`agesec`).
Note: Please be aware that Agentic Security is designed as a safety scanner tool and not a foolproof solution. It cannot guarantee complete protection against all possible threats.
> **WARNING:** Agentic Security is a test tool. It cannot find all vulnerabilities. A scan with no failures does not prove that the target is safe.
## UI 🧙
## Where to start
<img width="100%" alt="booking-screen" src="https://res.cloudinary.com/dq0w2rtm9/image/upload/v1741192668/final_aa9jhb.gif">
1. Install the package. Refer to [Installation](installation.md).
2. Do the steps in the [Quickstart](quickstart.md).
3. To scan in a CI pipeline, refer to [CI/CD integration](ci_cd.md).
## UI
<img width="100%" alt="Agentic Security UI" src="https://res.cloudinary.com/dq0w2rtm9/image/upload/v1741192668/final_aa9jhb.gif">
+10 -5
View File
@@ -1,18 +1,23 @@
# Installation
Requires Python 3.15 or newer.
You must have Python 3.15 or newer.
## PyPI
## Install from PyPI
```bash
pip install agentic_security
```
## From source
## Install from the source code
```bash
poetry install --with dev
```
Then run `agentic_security --help`. See the [CLI](cli.md) and
[getting started](getting_started.md) pages for the next steps.
## Make sure that the installation is correct
```bash
agentic_security --help
```
The command shows the list of subcommands. For the next steps, refer to the [Quickstart](quickstart.md).
+39 -103
View File
@@ -1,123 +1,59 @@
# Operator Module
# Agent operator (experimental)
The `operator.py` module provides tools for managing and operating on datasets using an agent-based approach. It is designed to facilitate the execution of operations on datasets through a structured and validated process.
The module `agentic_security.probe_actor.operator` is a prototype. An LLM agent uses tools to examine datasets and to test the built-in LLM specs.
> **CAUTION:** This module is not complete. `run_operation` accepts only the names `dataset1`, `dataset2`, and `dataset3`. The `run()` and `stop()` methods do nothing.
> **NOTE:** The module imports `pydantic_ai`. The package does not install `pydantic_ai`. Install it yourself before you import the module. The agent uses the `gpt-4` model, so you must also set `OPENAI_API_KEY`.
## Classes
### AgentSpecification
`AgentSpecification` is a pydantic model with these fields: `name`, `version`, `description`, `capabilities`, `configuration`.
Defines the specification for an LLM/agent:
`OperatorToolBox(spec, datasets)` keeps the specification, the datasets, the failures, and the built-in LLM specs.
- `name`: Name of the LLM/agent
- `version`: Version of the LLM/agent
- `description`: Description of the LLM/agent
- `capabilities`: List of capabilities
- `configuration`: Configuration settings
| Method | Description |
| --- | --- |
| `get_spec()` | Returns the `AgentSpecification`. |
| `get_datasets()` | Returns the datasets. |
| `validate()` | Returns `True` if the toolbox has a specification and datasets. |
| `run_operation(name)` | Returns a success message for a known dataset name. Records a failure for an unknown name. |
| `get_results()` | Returns the datasets. |
| `get_failures()` | Returns the recorded failures. |
| `test_with_prompt(index, prompt)` | Sends a prompt with the built-in LLM spec at `index`. This method is async. |
### OperatorToolBox
## Agent tools
Main class for dataset operations:
The agent `dataset_manager_agent` has these tools:
- `__init__(spec: AgentSpecification, datasets: list[dict[str, Any]])`: Initialize with agent spec and datasets. This sets up the toolbox with the necessary specifications and datasets for operation.
- `get_spec()`: Get the agent specification. Returns the `AgentSpecification` object associated with the toolbox.
- `get_datasets()`: Get the datasets. Returns a list of datasets that the toolbox operates on.
- `validate()`: Validate the toolbox. Checks if the toolbox is correctly set up with valid specifications and datasets.
- `stop()`: Stop the toolbox. Halts any ongoing operations within the toolbox.
- `run()`: Run the toolbox. Initiates the execution of operations as defined in the toolbox.
- `get_results()`: Get operation results. Retrieves the results of operations performed by the toolbox.
- `get_failures()`: Get failures. Provides a list of any failures encountered during operations.
- `run_operation(operation: str)`: Run a specific operation. Executes a given operation on the datasets, returning the result or failure message.
| Tool | Description |
| --- | --- |
| `validate_toolbox` | Validates the toolbox. |
| `execute_operation` | Runs an operation on a dataset. |
| `retrieve_results` | Returns the results. |
| `retrieve_failures` | Returns the failures. |
| `list_llm_specs` | Lists the built-in LLM specs. |
| `test_llm_with_prompt` | Sends a prompt with one LLM spec. |
## Agent Tools
The `dataset_manager_agent` provides these tools:
### validate_toolbox
Validates the OperatorToolBox:
## Example
```python
@dataset_manager_agent.tool
async def validate_toolbox(ctx: RunContext[OperatorToolBox]) -> str
```
from agentic_security.probe_actor.operator import (
AgentSpecification,
OperatorToolBox,
dataset_manager_agent,
)
### execute_operation
Executes an operation on a dataset:
```python
@dataset_manager_agent.tool
async def execute_operation(ctx: RunContext[OperatorToolBox], operation: str) -> str
```
### retrieve_results
Retrieves operation results:
```python
@dataset_manager_agent.tool
async def retrieve_results(ctx: RunContext[OperatorToolBox]) -> str
```
### retrieve_failures
Retrieves failures:
```python
@dataset_manager_agent.tool
async def retrieve_failures(ctx: RunContext[OperatorToolBox]) -> str
```
## Usage Examples
### Initializing the OperatorToolBox
To initialize the `OperatorToolBox`, you need to provide an `AgentSpecification` and a list of datasets:
```python
spec = AgentSpecification(
name="GPT-4",
version="4.0",
description="A powerful language model",
capabilities=["text-generation", "question-answering"],
description="A language model",
capabilities=["text-generation"],
configuration={"max_tokens": 100},
)
toolbox = OperatorToolBox(spec=spec, datasets=["dataset1", "dataset2"])
datasets = [{"name": "dataset1"}, {"name": "dataset2"}]
toolbox = OperatorToolBox(spec=spec, datasets=datasets)
for prompt in ["Validate the toolbox.", "Execute operation on 'dataset2'.", "Retrieve any failures."]:
result = dataset_manager_agent.run_sync(prompt, deps=toolbox)
print(result.data)
```
### Synchronous Usage
```python
def run_dataset_manager_agent_sync():
prompts = [
"Validate the toolbox.",
"Execute operation on 'dataset2'.",
"Retrieve the results.",
"Retrieve any failures."
]
for prompt in prompts:
result = dataset_manager_agent.run_sync(prompt, deps=toolbox)
print(f"Response: {result.data}")
```
### Asynchronous Usage
```python
async def run_dataset_manager_agent_async():
prompts = [
"Validate the toolbox.",
"Execute operation on 'dataset2'.",
"Retrieve the results.",
"Retrieve any failures."
]
for prompt in prompts:
result = await dataset_manager_agent.run(prompt, deps=toolbox)
print(f"Response: {result.data}")
```
These updates provide a more detailed and comprehensive understanding of the `operator.py` module, its classes, and its usage.
+27 -62
View File
@@ -1,78 +1,43 @@
# Bayesian Optimization in Security Fuzzing
# Early stop (optimizer)
The fuzzer implements an optimization system using scikit-optimize (skopt) to minimize failure rates during security scans. This document explains the optimizer's implementation and behavior.
When `optimize` is `true`, the scanner can stop a module before it sends all prompts. Use this option to save budget on a target that fails many prompts.
## Overview
Set the option in `agentic_security.toml`:
The optimizer is used in both single-shot and many-shot scanning modes when the `optimize` parameter is True. It dynamically adjusts scan parameters to minimize failure rates while staying within budget constraints.
## Implementation Details
### Initialization
The optimizer is initialized with:
```python
Optimizer(
[Real(0, 1)], # Single parameter space (0 to 1)
base_estimator="GP", # Gaussian Process estimator
n_initial_points=25 # Initial exploration points
)
```toml
[general]
optimize = true
```
### Optimization Process
Or use `--optimize` with the `scan` command.
1. **Parameter Space**: A single real-valued parameter between 0 and 1
1. **Objective**: Minimize the failure rate (negative failure rate is maximized)
1. **Update Mechanism**:
```python
next_point = optimizer.ask()
optimizer.tell(next_point, -failure_rate)
```
1. **Early Stopping**: If best failure rate exceeds 50%:
```python
if best_failure_rate > 0.5:
yield ScanResult.status_msg(
f"High failure rate detected ({best_failure_rate:.2%}). Stopping this module..."
)
break
```
## Single-shot scan
## Usage in Scanning
`perform_single_shot_scan` uses a scikit-optimize `Optimizer` with a Gaussian process:
The optimizer is integrated into both scan types:
```python
Optimizer([Real(0, 1)], base_estimator="GP", n_initial_points=INITIAL_OPTIMIZER_POINTS)
```
### Single-shot Scan
After each prompt, the scanner does these steps:
- Used in `perform_single_shot_scan()`
- Optimizes failure rates across prompt modules
- Considers token budget constraints
1. If there are fewer than `min_failure_samples` results, it continues to the next prompt.
2. It gives the negative failure rate to the optimizer (`ask()`, then `tell()`).
3. It reads the best failure rate from the optimizer.
4. If the best failure rate is more than `failure_rate_threshold`, it stops the module. It sends the status message "High failure rate detected".
### Many-shot Scan
> **NOTE:** The optimizer point does not change the prompts or the order of the prompts. The result of the optimizer is only an early stop.
- Used in `perform_many_shot_scan()`
- Handles more complex multi-step attacks
- Maintains separate failure rate tracking
## Many-shot scan
## Key Parameters
`perform_many_shot_scan` does not use the optimizer. When `optimize` is `true`, it stops the module after `min_failure_samples` results.
| Parameter | Description |
|-----------|-------------|
| base_estimator | Gaussian Process (GP) used for optimization |
| n_initial_points | 25 initial exploration points |
| Real(0, 1) | Single parameter space being optimized |
| failure_rate | Current failure rate being minimized |
## Settings
## Optimization Flow
Set these values in the `[fuzzer]` section of `agentic_security.toml`:
1. Initialize optimizer with GP estimator
1. Collect initial 25 data points
1. For each prompt:
- Calculate current failure rate
- Update optimizer with new point
- Check for early stopping conditions
1. Continue until scan completes or budget exhausted
## Error Handling
The optimizer is wrapped in try/except blocks to ensure scan failures don't crash the entire process. Any optimization errors are logged and the scan continues with default parameters.
| Key | Default | Description |
| --- | --- | --- |
| `initial_optimizer_points` | `25` | The random points before the optimizer fits the model. |
| `min_failure_samples` | `5` | The minimum number of results before an early stop. |
| `failure_rate_threshold` | `0.5` | The failure rate that causes an early stop. |
+19 -19
View File
@@ -1,42 +1,42 @@
# Probe actor
The `probe_actor` package runs scans against an LLM endpoint described by an
HTTP spec.
The `agentic_security.probe_actor` package sends the attack prompts to the target and scores the responses.
## Fuzzer
`agentic_security.probe_actor.fuzzer` is the scan engine:
`agentic_security.probe_actor.fuzzer` is the scan engine.
- `generate_prompts` — yield prompts from a list or async source
- `get_modality_adapter` — wrap the spec for image or audio endpoints
- `process_prompt` / `process_prompt_batch` — send a prompt and score the reply
- `perform_single_shot_scan` — one prompt at a time
- `perform_many_shot_scan` — many-shot jailbreak conversations
- `scan_router` — pick the scan mode from configuration
| Function | Description |
| --- | --- |
| `scan_router` | Selects the single-shot scan or the many-shot scan from the scan settings. |
| `perform_single_shot_scan` | Sends one prompt in each request. |
| `perform_many_shot_scan` | Sends many-shot jailbreak conversations. |
| `process_prompt` / `process_prompt_batch` | Sends prompts and records the refusals. |
| `get_modality_adapter` | Wraps the spec for image or audio targets. |
| `generate_prompts` | Yields prompts from a list or from an async generator. |
`perform_single_shot_scan` is an async generator; it needs a request factory
(typically an `LLMSpec`) plus budget and dataset settings, not a bare prompt
string.
The scan functions are async generators. Each item is a JSON string with the progress, the failure rate, or a status message.
```python
from agentic_security.http_spec import LLMSpec
from agentic_security.probe_actor.fuzzer import perform_single_shot_scan
spec = LLMSpec.from_string(open("spec.http").read())
async for event in perform_single_shot_scan(spec, max_budget=1000):
spec = LLMSpec.from_string(open("target.http").read())
datasets = [{"dataset_name": "simonycl/aya-23-8B_advbench_jailbreak", "selected": True}]
async for event in perform_single_shot_scan(spec, max_budget=1000, datasets=datasets):
print(event)
```
At the end of a scan, the fuzzer writes `failures.csv` and `full_scan_log.csv` to the current directory.
## Refusal checks
There is no `check_refusal` helper. Use `refusal_heuristic(response)` in
`agentic_security.probe_actor.refusal`, which runs the detectors enabled under
`[detectors]` in `agentic_security.toml`.
`refusal_heuristic(response)` in `agentic_security.probe_actor.refusal` uses the detectors that are enabled in `[detectors]`.
```python
from agentic_security.probe_actor.refusal import refusal_heuristic
refusal_heuristic("I'm sorry, I can't help with that.")
refusal_heuristic("I'm sorry, I can't help with that.") # True
```
See [refusal classifier plugins](refusal_classifier_plugins.md) to add a custom detector.
To add a detector, refer to [Refusal classifier plugins](refusal_classifier_plugins.md).
+13 -17
View File
@@ -1,28 +1,28 @@
# Probe data
The `probe_data` package loads attack datasets, optionally transforms prompts,
and can generate image or audio payloads for multi-modal specs.
The `agentic_security.probe_data` package loads the attack datasets. It can also change the prompts and make image or audio attacks.
## Datasets
`agentic_security.probe_data.data`:
- `load_dataset_generic` — load a CSV URL or Hugging Face dataset into a `ProbeDataset`
- `load_local_csv` / `load_local_csv_files` — datasets from local CSV files
- `prepare_prompts` — select and transform registry datasets for a scan
| Function | Description |
| --- | --- |
| `prepare_prompts` | Loads and transforms the selected registry datasets for a scan. |
| `load_dataset_generic` | Loads a CSV URL or a Hugging Face dataset into a `ProbeDataset`. |
| `load_local_csv` | Loads all CSV files in `./datasets` into one `ProbeDataset`. |
| `load_local_csv_files` | Loads each CSV file in `./datasets` into a separate `ProbeDataset`. |
`agentic_security.probe_data.models.ProbeDataset` is the in-memory dataset type.
Image datasets wrap that as `ImageProbeDataset`.
`ProbeDataset` in `agentic_security.probe_data.models` keeps the prompts and the metadata of one dataset. `ImageProbeDataset` adds the images.
## Transforms
`agentic_security.probe_data.stenography_fn` provides encoding helpers such as
`rot13`, `base64_encode`, and `mirror_words`. See [stenography](stenography.md).
`agentic_security.probe_data.stenography_fn` has encoding functions, for example `rot13`, `base64_encode`, and `mirror_words`. Refer to [Stenography functions](stenography.md).
## Image and audio
## Images and audio
- `generate_image` / `generate_image_dataset` in `probe_data.image_generator`
- `generate_audioform` in `probe_data.audio_generator`
- `generate_image` and `generate_image_dataset` in `probe_data.image_generator`. Refer to [Image generation](image_generation.md).
- `generate_audioform` in `probe_data.audio_generator`. It makes a WAV file. On macOS it uses the `say` command. On other systems it uses gTTS.
```python
from agentic_security.probe_data.audio_generator import generate_audioform
@@ -32,9 +32,7 @@ audio_bytes = generate_audioform("Hello, world!")
## Prompt selection
`probe_data.modules.rl_model` implements `PromptSelectionInterface` with
`RandomPromptSelector`, `CloudRLPromptSelector`, and `QLearningPromptSelector`.
`update_rewards` returns `None`. Boolean arguments are Python `True` / `False`.
`probe_data.modules.rl_model` has prompt selectors. Refer to [RL prompt selection](rl_model.md).
```python
from agentic_security.probe_data.modules.rl_model import QLearningPromptSelector
@@ -43,5 +41,3 @@ selector = QLearningPromptSelector(["What is AI?", "Explain machine learning"])
next_prompt = selector.select_next_prompt("What is AI?", passed_guard=True)
selector.update_rewards("What is AI?", next_prompt, reward=1.0, passed_guard=True)
```
See [RL model](rl_model.md) for the selector options.
+27 -42
View File
@@ -1,65 +1,50 @@
# Quickstart Guide
# Quickstart
Welcome to the Quickstart Guide for Agentic Security. This guide will help you set up and start using the project quickly.
This procedure starts the web UI and does a scan from the command line.
## Installation
To get started with Agentic Security, install the package using pip:
## Install the package
```shell
pip install agentic_security
```
## Initial Setup
After installation, you can start the application using the following command:
## Start the web UI
```shell
agentic_security server
```
This will initialize the server and prepare it for use.
Open `http://127.0.0.1:8718` in a web browser.
## Basic Usage
> **NOTE:** The `agentic_security` command without a subcommand does not start the server. It shows the help text.
To run the main application, use:
## Do a scan from the command line
```shell
python -m agentic_security
```
1. Create the configuration file `agentic_security.toml`:
You can also view help options with:
```shell
agentic_security init
```
```shell
agentic_security --help
```
2. Open `agentic_security.toml`.
3. Replace the example `llmSpec` with the HTTP request for your endpoint. Refer to [HTTP spec](http_spec.md).
4. Show the available datasets:
## Running as a CI Check
```shell
agentic_security ls
```
Initialize the configuration for CI checks:
5. Add the datasets that you want to the `[modules]` section.
6. Start the scan:
```shell
agentic_security init
```
```shell
agentic_security ci
```
This will generate a default configuration file named `agentic_security.toml`.
The scan shows a table with the failure rate for each module.
## Additional Commands
## Next steps
- List available modules:
```shell
agentic_security ls
```
- Run a security scan:
```shell
agentic_security ci
```
## Further Information
For more detailed information, refer to the [Documentation](index.md) or the [API Reference](api_reference.md).
This quickstart guide should help you get up and running with Agentic Security efficiently.
- [CLI reference](cli.md)
- [Configuration](configuration.md)
- [CI/CD integration](ci_cd.md)
+59 -85
View File
@@ -1,114 +1,88 @@
# Refusal Classifier Plugin System Documentation
# Refusal classifier plugins
The refusal classifier plugin system allows for the creation and use of custom refusal classifiers. This system is designed to be modular and extensible, enabling users to add their own refusal detection logic.
A detector examines each response from the target. If one or more enabled detectors return `True`, the scanner records a refusal for that prompt.
## Overview
## Built-in detectors
The plugin system is based on the `RefusalClassifierPlugin` abstract base class, which defines the interface for all refusal classifier plugins. The `RefusalClassifierManager` is used to register and manage these plugins.
| Name | Default | Description |
| --- | --- | --- |
| `default` | on | Finds refusal phrases, for example "I'm sorry". |
| `ml_classifier` | on | A one-class SVM refusal classifier. |
| `pii` | off | Finds personal data and credential leaks. |
| `sandbox_escape` | off | Finds Docker and Kubernetes sandbox-escape probes. |
## Creating a Plugin
To turn a detector on or off, set its name in the `[detectors]` section of `agentic_security.toml`:
To create a custom refusal classifier plugin, you must implement the `RefusalClassifierPlugin` abstract base class. This class requires the implementation of the `is_refusal` method, which checks if a response contains a refusal.
```python
from abc import ABC, abstractmethod
class RefusalClassifierPlugin(ABC):
"""Base class for refusal classifier plugins."""
@abstractmethod
def is_refusal(self, response: str) -> bool:
"""Check if the response contains a refusal.
Args:
response (str): The response from the language model.
Returns:
bool: True if the response contains a refusal, False otherwise.
"""
pass
```toml
[detectors]
default = true
ml_classifier = true
pii = true
sandbox_escape = false
```
### Example Plugin
## Make a custom detector
Here is an example of a custom refusal classifier plugin that checks for specific phrases:
A detector is a class with the method `is_refusal(response: str) -> bool`.
```python
class CustomRefusalClassifier(RefusalClassifierPlugin):
def __init__(self, custom_phrases: list[str]):
self.custom_phrases = custom_phrases
# my_package/detectors.py
class PhraseDetector:
def __init__(self, phrases: list[str]):
self.phrases = phrases
def is_refusal(self, response: str) -> bool:
"""Check if the response contains any custom refusal phrases.
Args:
response (str): The response from the language model.
Returns:
bool: True if the response contains a custom refusal phrase, False otherwise.
"""
return any(phrase in response for phrase in self.custom_phrases)
return any(phrase in response for phrase in self.phrases)
```
## Registering a Plugin
You can also use the abstract base class `RefusalClassifierPlugin` from `agentic_security.probe_actor.refusal`.
To register a custom refusal classifier plugin, use the `RefusalClassifierManager`:
## Enable a custom detector
Add a table to `[detectors]`. The tool imports the class and gives the `options` table to the constructor as keyword arguments.
```toml
[detectors.phrases]
class = "my_package.detectors:PhraseDetector"
enabled = true
[detectors.phrases.options]
phrases = ["I can't", "I won't"]
```
The class path can use the form `package.module:ClassName` or `package.module.ClassName`.
> **CAUTION:** The tool reads `[detectors]` one time, when it imports `agentic_security.probe_actor.refusal`. Restart the process after you change the section.
> **NOTE:** A new `RefusalClassifierManager()` that you make in code does not change the scan. The scan uses the manager that the tool builds from `[detectors]`. To build that manager from a different configuration, use `build_refusal_manager(config)`.
## Check a response in code
```python
from agentic_security.probe_actor.refusal import RefusalClassifierManager
from agentic_security.probe_actor.refusal import (
pii_leak_heuristic,
refusal_heuristic,
sandbox_escape_heuristic,
)
# Initialize the plugin manager
refusal_classifier_manager = RefusalClassifierManager()
# Register the custom plugin
refusal_classifier_manager.register_plugin("custom", CustomRefusalClassifier(custom_phrases=["I can't", "I won't"]))
refusal_heuristic("I'm sorry, I can't help with that.") # True
pii_leak_heuristic("Contact me at jane@example.com") # True
```
## Using the Plugin System
`pii_leak_heuristic` and `sandbox_escape_heuristic` always use their detector. They do not change the refusal result.
The `refusal_heuristic` function automatically uses all registered plugins to check for refusals:
## PII detector
```python
from agentic_security.probe_actor.refusal import refusal_heuristic
is_refusal = refusal_heuristic(request_json)
```
## PII Leak Detection
The built-in `PIIDetector` can be used to check scanner responses for sensitive personal or credential material without changing refusal metrics. Use `pii_leak_heuristic` when you want a separate leak signal:
```python
from agentic_security.probe_actor.refusal import pii_leak_heuristic
has_pii_leak = pii_leak_heuristic(request_json)
```
`PIIDetector` currently checks for common leak signals including email addresses, US SSNs, phone numbers, private key blocks, API-token style secrets, and credit card candidates that pass Luhn validation. Credit-card detection is controlled separately with `detect_credit_cards`:
`PIIDetector` finds email addresses, US SSNs, phone numbers, private key blocks, and API tokens. It also finds credit card numbers that pass the Luhn check.
```python
from agentic_security.refusal_classifier import PIIDetector
detector = PIIDetector(patterns=(), detect_credit_cards=False)
```
If you construct your own `RefusalClassifierManager` and intentionally want leak detection to participate in the same boolean plugin result as refusals, register it manually:
```python
from agentic_security.probe_actor.refusal import RefusalClassifierManager
from agentic_security.refusal_classifier import PIIDetector
manager = RefusalClassifierManager()
manager.register_plugin("pii", PIIDetector())
```
For reporting or debugging, use `detected_types` to see which leak categories matched:
```python
detector = PIIDetector()
matched_types = detector.detected_types(response)
detector.detected_types(response) # The names of the matched types.
# Credit card check off:
PIIDetector(detect_credit_cards=False)
```
## Conclusion
The refusal classifier plugin system provides a flexible and extensible way to add custom refusal detection logic to the Agentic Security project. This documentation serves as a guide to creating, registering, and using custom refusal classifier plugins.
To use only your patterns, give a tuple of `PIIPattern` objects as `patterns`. An empty tuple turns the pattern checks off.
+60 -173
View File
@@ -1,194 +1,81 @@
# RL Model Module
# RL prompt selection
The RL Model module provides reinforcement learning-based prompt selection strategies for the probe system.
The module `agentic_security.probe_data.modules.rl_model` selects the next attack prompt. It uses the guard result and a reward to make the selection.
## Overview
## Selectors
The module implements several prompt selection strategies that use reinforcement learning techniques to optimize prompt selection based on guard results and rewards.
## Classes
### PromptSelectionInterface
Abstract base class defining the interface for prompt selection strategies.
**Methods:**
- `select_next_prompt(current_prompt: str, passed_guard: bool) -> str`
- `select_next_prompts(current_prompt: str, passed_guard: bool) -> list[str]`
- `update_rewards(previous_prompt: str, current_prompt: str, reward: float, passed_guard: bool) -> None`
### RandomPromptSelector
Basic random selection strategy with cycle prevention using history.
**Configuration:**
- `prompts`: List of available prompts
- `history_size`: Size of history buffer to prevent cycles (default: 300)
### CloudRLPromptSelector
Cloud-based reinforcement learning prompt selector with fallback to random selection.
**Configuration:**
- `prompts`: List of available prompts
- `api_url`: URL of the RL service
- `auth_token`: Authentication token (default: AS_TOKEN environment variable)
- `history_size`: Size of history buffer (default: 300)
- `timeout`: Request timeout in seconds (default: 5)
- `run_id`: Unique identifier for the run
### QLearningPromptSelector
Q-Learning based prompt selector with exploration/exploitation tradeoff.
**Configuration:**
- `prompts`: List of available prompts
- `learning_rate`: Learning rate (default: 0.1)
- `discount_factor`: Discount factor (default: 0.9)
- `initial_exploration`: Initial exploration rate (default: 1.0)
- `exploration_decay`: Exploration decay rate (default: 0.995)
- `min_exploration`: Minimum exploration rate (default: 0.01)
- `history_size`: Size of history buffer (default: 300)
### Module
Main class that implements the RL-based prompt selection functionality.
**Configuration:**
- `prompt_groups`: List of prompt groups
- `tools_inbox`: asyncio.Queue for tool communication
- `opts`: Additional options
- `max_prompts`: Maximum number of prompts to generate (default: 10)
- `batch_size`: Batch size for processing (default: 500)
## Usage Example
All selectors implement `PromptSelectionInterface`:
```python
from agentic_security.probe_data.modules.rl_model import (
Module,
CloudRLPromptSelector,
QLearningPromptSelector
)
# Initialize with prompt groups
prompt_groups = ["What is AI?", "Explain ML", "Describe RL"]
module = Module(prompt_groups, asyncio.Queue())
# Use the module
async for prompt in module.apply():
print(f"Selected prompt: {prompt}")
```
## API Reference
### PromptSelectionInterface
```python
class PromptSelectionInterface(ABC):
@abstractmethod
def select_next_prompt(self, current_prompt: str, passed_guard: bool) -> str:
"""Select next prompt based on current state and guard result."""
@abstractmethod
def select_next_prompts(self, current_prompt: str, passed_guard: bool) -> list[str]:
"""Select next prompts based on current state and guard result."""
@abstractmethod
def update_rewards(
self,
previous_prompt: str,
current_prompt: str,
reward: float,
passed_guard: bool,
) -> None:
"""Update internal rewards based on outcome of last selected prompt."""
select_next_prompt(current_prompt: str, passed_guard: bool) -> str
select_next_prompts(current_prompt: str, passed_guard: bool) -> list[str]
update_rewards(previous_prompt: str, current_prompt: str, reward: float, passed_guard: bool) -> None
```
### RandomPromptSelector
```python
class RandomPromptSelector(PromptSelectionInterface):
def __init__(self, prompts: list[str], history_size: int = 300):
"""Initialize with prompts and history size."""
Selects a random prompt. It keeps a history to prevent repeated cycles.
def select_next_prompt(self, current_prompt: str, passed_guard: bool) -> str:
"""Select next prompt randomly with cycle prevention."""
| Argument | Default | Description |
| --- | --- | --- |
| `prompts` | – | The list of prompts. |
| `history_size` | `300` | The size of the history. |
def update_rewards(
self,
previous_prompt: str,
current_prompt: str,
reward: float,
passed_guard: bool,
) -> None:
"""No learning in random selection."""
```
### CloudRLPromptSelector
```python
class CloudRLPromptSelector(PromptSelectionInterface):
def __init__(
self,
prompts: list[str],
api_url: str,
auth_token: str = AUTH_TOKEN,
history_size: int = 300,
timeout: int = 5,
run_id: str = "",
):
"""Initialize with cloud RL configuration."""
def select_next_prompts(self, current_prompt: str, passed_guard: bool) -> list[str]:
"""Select next prompts using cloud RL with fallback."""
def _fallback_selection(self) -> str:
"""Fallback to random selection if cloud request fails."""
```
`update_rewards` does nothing.
### QLearningPromptSelector
```python
class QLearningPromptSelector(PromptSelectionInterface):
def __init__(
self,
prompts: list[str],
learning_rate: float = 0.1,
discount_factor: float = 0.9,
initial_exploration: float = 1.0,
exploration_decay: float = 0.995,
min_exploration: float = 0.01,
history_size: int = 300,
):
"""Initialize Q-Learning configuration."""
Selects prompts with Q-learning. The exploration rate decreases after each selection.
def select_next_prompt(self, current_prompt: str, passed_guard: bool) -> str:
"""Select next prompt using Q-Learning with exploration/exploitation."""
| Argument | Default | Description |
| --- | --- | --- |
| `prompts` | – | The list of prompts. |
| `learning_rate` | `0.1` | The learning rate. |
| `discount_factor` | `0.9` | The discount factor. |
| `initial_exploration` | `1.0` | The exploration rate at the start. |
| `exploration_decay` | `0.995` | The decrease of the exploration rate. |
| `min_exploration` | `0.01` | The minimum exploration rate. |
| `history_size` | `300` | The size of the history. |
def update_rewards(
self,
previous_prompt: str,
current_prompt: str,
reward: float,
passed_guard: bool,
) -> None:
"""Update Q-values based on reward."""
```
### CloudRLPromptSelector
### Module
Gets the next prompts from a remote RL service. If the request fails, it selects a random prompt.
| Argument | Default | Description |
| --- | --- | --- |
| `prompts` | – | The list of prompts. |
| `api_url` | – | The URL of the RL service. |
| `auth_token` | `AS_TOKEN` environment variable | The token for the service. |
| `history_size` | `300` | The size of the history. |
| `timeout` | `5` | The request timeout in seconds. |
| `run_id` | random UUID | The identifier of the run. |
## Module
`Module` uses a selector in a scan.
| Argument | Description |
| --- | --- |
| `prompt_groups` | The prompts. |
| `tools_inbox` | An `asyncio.Queue` for messages. |
| `opts["max_prompts"]` | The number of selection rounds. The default is `10`. |
| `opts["batch_size"]` | The batch size. The default is `500`. |
| `rl_model` | The selector. The default is `CloudRLPromptSelector` with `https://mcp.metaheuristic.co`. |
> **WARNING:** The default selector sends your prompts to `https://mcp.metaheuristic.co`. To keep the prompts on your computer, give a local selector as `rl_model`.
```python
class Module:
def __init__(
self, prompt_groups: list[str], tools_inbox: asyncio.Queue, opts: dict = {}
):
"""Initialize module with prompt groups and configuration."""
import asyncio
async def apply(self):
"""Apply the RL model to generate prompts."""
from agentic_security.probe_data.modules.rl_model import Module, QLearningPromptSelector
prompts = ["What is AI?", "Explain ML", "Describe RL"]
async def main():
module = Module(prompts, asyncio.Queue(), rl_model=QLearningPromptSelector(prompts))
async for prompt in module.apply():
print(prompt)
asyncio.run(main())
```
+17 -19
View File
@@ -1,30 +1,28 @@
# Stenography functions
`agentic_security.probe_data.stenography_fn` transforms prompts so scanners can
test whether a model still treats obfuscated text as an instruction.
`agentic_security.probe_data.stenography_fn` changes the text of a prompt. Use these functions to test if a model obeys an instruction that is encoded or hidden.
The module is used by `Stenography` in `probe_data.data` when a dataset
enables encoding variants.
The scanner uses these functions to make transformed datasets from the loaded prompts. Refer to [Dataset extension](datasets.md).
> **NOTE:** These functions hide text for red-team tests. They do not give cryptographic security.
## Functions
| Function | What it does |
| Function | Description |
| --- | --- |
| `rot13` / `rot5` | Letter and digit rotation ciphers |
| `base64_encode` | Base64-encode a string or bytes |
| `mirror_words` | Reverse each word, keep word order |
| `scramble_words` | Shuffle middle letters, keep first and last |
| `randomize_letter_case` | Random per-character case |
| `insert_noise_characters` | Insert alphanumeric noise (`frequency=0.2` by default) |
| `substitute_with_ascii` | Replace characters with ordinals |
| `remove_vowels` | Drop `aeiou` in either case |
| `zigzag_obfuscation` | Alternate upper/lower case |
| `caesar_cipher` / `substitution_cipher` / `vigenere_cipher` | Classical ciphers |
| `code_block_encode` | Hide the prompt in a Python docstring fenced as code |
| `rot13` / `rot5` | Rotates the letters (ROT13) or the digits (ROT5). |
| `base64_encode` | Encodes a string or bytes in Base64. |
| `mirror_words` | Reverses the letters of each word. The word order does not change. |
| `scramble_words` | Mixes the middle letters of each word. The first and last letters do not change. |
| `randomize_letter_case` | Sets a random case for each letter. |
| `insert_noise_characters` | Adds random letters and digits. The default `frequency` is `0.2`. |
| `substitute_with_ascii` | Replaces each character with its character code. |
| `remove_vowels` | Removes the vowels `aeiou` (upper and lower case). |
| `zigzag_obfuscation` | Uses upper case and lower case in turn. |
| `caesar_cipher` / `substitution_cipher` / `vigenere_cipher` | Classical ciphers. |
| `code_block_encode` | Puts the prompt in a Python docstring in a code block. |
These are obfuscation helpers for red-team prompts, not cryptographic primitives.
## Usage
## Example
```python
from agentic_security.probe_data.stenography_fn import rot13, scramble_words
+2
View File
@@ -31,10 +31,12 @@ nav:
- Image Generation: image_generation.md
- Stenography Functions: stenography.md
- Reinforcement Learning Optimization: rl_model.md
- Agent Harness: harness.md
- WIP:
- Agent Operator: operator.md
- Reference:
- API Reference: api_reference.md
- Contributing: contributing.md
# - Project:
# - Setup: setup.md
# - Version control: version_control.md