Skip to main content

AI Security Testing Framework - Comprehensive adversarial testing for AI systems

Project description

๐Ÿ›ก๏ธ NPersona: AI Security Testing Framework

Making AI Systems Safer, One Test at a Time

License: MIT Python 3.9+ Code style: black Tests Passing PyPI Version


๐ŸŽฏ What is NPersona?

NPersona is a comprehensive, production-ready framework for adversarial security testing of AI systems. It automates the discovery of vulnerabilities in large language models and AI agents through intelligent test generation, execution, and evaluation.

Think of it as a professional penetration testing tool specifically designed for AI systems. Just like security researchers stress-test web applications to find vulnerabilities, NPersona stress-tests AI systems to discover security flaws before they reach production.

Why NPersona?

  • ๐Ÿš€ Production Ready: 115+ comprehensive tests, enterprise-grade architecture
  • ๐ŸŽฏ Comprehensive: 28 attack categories + 40+ research-backed vulnerabilities
  • โšก Fast: Test your AI system in 2-10 minutes
  • ๐Ÿ”ง Flexible: Works with any AI API (OpenAI, Azure, Groq, Ollama, etc.)
  • ๐Ÿ“Š Professional Reports: JSON, HTML, Markdown with detailed analysis
  • ๐Ÿ” Secure: Multiple authentication methods, rate limiting, retry logic
  • ๐Ÿงช Real Testing: Test against actual APIs with production data

โœจ Key Features

๐Ÿ—๏ธ 7-Stage Security Pipeline

Profile โ†’ AttackMap โ†’ Generate โ†’ Execute โ†’ Evaluate โ†’ Analyze โ†’ Report

Each stage is optimized for discovering different classes of AI vulnerabilities.

๐Ÿ“‹ Comprehensive Attack Coverage

  • 28 Attack Categories: OWASP AI Security taxonomy
  • 40+ Known Vulnerabilities: Research-backed attack patterns
  • Adversarial Tests: A01-A20 (prompt injection, jailbreaks, etc.)
  • User-Centric Tests: U01-U08 (usability, accessibility attacks)

๐Ÿ”‘ Multi-Authentication Support

  • Bearer Token
  • OAuth2 (with auto-refresh)
  • API Key (custom headers)
  • Basic Authentication
  • Custom callable adapters

๐ŸŒ LLM Agnostic

Works seamlessly with:

  • OpenAI (GPT-4, GPT-4o)
  • Azure OpenAI (Enterprise)
  • Groq (Fast & affordable)
  • Google Gemini
  • Anthropic Claude
  • Ollama (Local/private)

๐Ÿ”Œ HTTP Adapter Pattern

  • JSON POST (default)
  • OpenAI Chat format
  • AWS Bedrock Agent
  • Custom callable adapters

โš™๏ธ Enterprise Features

  • Parallel test execution with configurable concurrency
  • Token bucket rate limiting
  • Exponential backoff retry logic
  • Per-request timeouts
  • Session-based multi-turn testing
  • Detailed telemetry & analytics

๐Ÿš€ Quick Start (5 minutes)

Installation

pip install npersona

Or from source:

git clone https://github.com/NPersona-AI/NPersona.git
cd NPersona
pip install -e .

Your First Security Assessment

import asyncio
from npersona import NPersonaClient
from npersona.models.auth import BearerTokenAuth

async def test_my_ai():
    # 1. Create client with any LLM provider
    client = NPersonaClient(
        provider="groq",  # or openai, azure, gemini, ollama
        api_key="gsk_YOUR_KEY"
    )
    
    # 2. Define your AI system
    system_doc = """
    A customer support chatbot that:
    - Answers product questions
    - Processes refund requests
    - Never shares internal policies
    """
    
    # 3. Run security assessment
    report = await client.run(
        system_doc=system_doc,
        system_endpoint="https://your-api.example.com/chat",
        auth_config=BearerTokenAuth(token="your-token"),
        num_adversarial=20,  # LLM-generated adversarial tests
        num_user_centric=10  # User behavior tests
    )
    
    # 4. Get results
    print(f"โœ… Tests Passed: {report.evaluation.passed_count}")
    print(f"โŒ Tests Failed: {report.evaluation.failed_count}")
    print(f"๐Ÿ“Š Pass Rate: {report.evaluation.pass_rate}%")
    print(f"๐Ÿ”ด Critical Issues: {len(report.critical_vulnerabilities)}")
    
    # 5. Save reports
    report.export_json("security_report.json")
    report.export_html("security_report.html")

asyncio.run(test_my_ai())

Output:

โœ… Tests Passed: 35
โŒ Tests Failed: 8
๐Ÿ“Š Pass Rate: 81.4%
๐Ÿ”ด Critical Issues: 3
Reports saved!

๐Ÿ“Š What Gets Tested

Prompt Injection Attacks

  • Direct prompt injection
  • Indirect injection via data fields
  • Constraint enumeration
  • System instruction leakage

Information Disclosure

  • Debug mode exploitation
  • Sensitive data leakage
  • Training data extraction
  • Privacy pattern leakage

Harmful Content Generation

  • Jailbreak attempts
  • Roleplay exploitation
  • Behavioral override
  • Multi-turn manipulation

And 18+ More Categories...

See Attack Patterns Catalog for complete taxonomy.


๐ŸŽฏ Real-World Example

Test a Fitness Coaching AI

system_doc = """
A fitness AI that:
- Generates workout routines
- Provides nutrition advice
- Never recommends dangerous practices
"""

report = await client.run(
    system_doc=system_doc,
    system_endpoint="https://gym-api.example.com/chat",
    num_adversarial=25,
    num_user_centric=15
)

Example Results

Test Results Summary
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•
Tests Executed: 40
Tests Passed: 32 (80%)
Tests Failed: 8 (20%)

Vulnerabilities Found:

๐Ÿ”ด CRITICAL (Immediate action required)
  โ€ข Debug Mode Information Disclosure
    Fix time: < 1 hour
  
  โ€ข Constraint Enumeration Attack
    Fix time: < 2 hours

๐ŸŸ  HIGH (Address within 1 week)
  โ€ข Prompt Injection via Roleplay
    Severity: High
    
  โ€ข Training Data Extraction
    Severity: High

๐ŸŸก MEDIUM (Address within 1 month)
  โ€ข Indirect Injection via JSON
    Severity: Medium

Remediation Timeline:
  After CRITICAL fixes: 95% pass rate
  After HIGH fixes: 99%+ pass rate

๐Ÿ” Authentication Examples

Bearer Token (Simplest)

auth = BearerTokenAuth(token="your_token_here")

OAuth2 (Enterprise)

auth = OAuth2Config(
    client_id="your_id",
    client_secret="your_secret",
    token_endpoint="https://auth.example.com/token",
    scope="api:read api:write"
)

API Key (Custom Header)

auth = APIKeyAuth(
    api_key="sk_abc123",
    header_name="X-API-Key"
)

See SECURITY.md for more authentication options.


๐Ÿ“ˆ Advanced Usage

Configure Everything

from npersona.models.config import NPersonaConfig, LLMConfig

config = NPersonaConfig(
    # Use Azure OpenAI with GPT-4o
    llm=LLMConfig(
        provider="azure",
        model="gpt-4o",
        api_key="your_key",
        base_url="https://your-resource.openai.azure.com/",
        temperature=0.7,
        max_tokens=8192
    ),
    
    # Execution settings
    executor_concurrency=5,        # Parallel requests
    executor_retries=3,            # Retry logic
    executor_rate_limit_rps=10.0,  # Rate limiting
    per_request_timeout=30.0,      # Timeouts
    
    # Test generation
    num_adversarial=30,
    num_user_centric=15
)

client = NPersonaClient(config=config)

Custom HTTP Adapters

from npersona.adapters.custom import CustomCallableAdapter

async def my_adapter(test_case):
    # Your custom logic
    return {
        "url": "https://api.example.com/v1/chat",
        "method": "POST",
        "json": {"message": test_case.prompt},
        "headers": {"Authorization": "Bearer ..."}
    }

adapter = CustomCallableAdapter(handler=my_adapter)
report = await client.run(..., adapter=adapter)

See USER_GUIDE.md for more advanced examples.


๐Ÿ’ฐ Cost Estimation

LLM Provider Cost per Run Speed Best For
Groq (Recommended) ~$0.01 10-30s Development
OpenAI GPT-4o ~$0.10 30-60s Production
Azure OpenAI ~$0.05-0.15 30-60s Enterprise
Ollama (Local) FREE Varies Privacy-first

Run an assessment for the cost of a coffee โ˜•


๐Ÿงช CI/CD Integration

GitHub Actions

name: AI Security Tests

on: [push, pull_request]

jobs:
  security:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: '3.11'
      
      - name: Run NPersona assessment
        env:
          GROQ_API_KEY: ${{ secrets.GROQ_API_KEY }}
          TARGET_API: ${{ secrets.STAGING_API }}
          AUTH_TOKEN: ${{ secrets.AUTH_TOKEN }}
        run: |
          pip install npersona
          python assess_security.py
      
      - name: Check for critical issues
        run: |
          python check_results.py --fail-on-critical

๐Ÿ“š Documentation

Document Purpose
INSTALLATION_GUIDE.md Setup & configuration
QUICK_START_TUTORIAL.md 10-minute tutorial
USER_GUIDE.md Complete reference
CONTRIBUTING.md Contribute code
SECURITY.md Security policy
CHANGELOG.md Release notes

๐Ÿ—๏ธ Architecture

NPersona Pipeline (7 Stages)
โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

Stage 1: PROFILER
  Input: System documentation
  Output: SystemProfile (agents, guardrails, capabilities)
  
Stage 2: MAPPER
  Input: SystemProfile
  Output: AttackSurfaceMap (attack categories coverage)
  
Stage 3: GENERATOR
  Input: Profile + AttackMap
  Output: TestSuite (40+ test cases)
  
Stage 4: EXECUTOR
  Input: TestSuite
  Output: TestResults (API responses, latency, errors)
  
Stage 5: EVALUATOR
  Input: TestResults
  Output: EvaluationResult (pass/fail analysis)
  
Stage 6: RCA ANALYZER
  Input: Failures + Architecture
  Output: RCAFindings (root causes)
  
Stage 7: REPORTER
  Input: Everything
  Output: SecurityReport (JSON/HTML/Markdown)

๐Ÿงฌ Extensibility

Custom Evaluation Criteria

class MyEvaluator(Evaluator):
    async def evaluate(self, result, test_case):
        # Your custom logic
        if "forbidden_word" in result.response:
            return False
        return True

Custom Request Adapter

class MyAdapter(RequestAdapter):
    async def build_request(self, test_case):
        return HTTPRequest(
            method="POST",
            url="https://api.example.com/test",
            json={"input": test_case.prompt}
        )
    
    async def parse_response(self, response):
        return response.get("output")

See docs/ for more examples.


๐Ÿค Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

# Development setup
git clone https://github.com/NPersona-AI/NPersona.git
cd NPersona
pip install -e ".[dev]"

# Run tests
pytest tests/ -v

# Code quality
black . && flake8 . && mypy npersona/

๐Ÿ“œ License

MIT License - See LICENSE for details


๐Ÿ™ Acknowledgments

  • Attack taxonomy based on OWASP AI Security
  • LLM integration via LiteLLM
  • Authentication patterns inspired by industry standards
  • Evaluation methodology from academic security research

๐Ÿ“ž Support & Contact


๐Ÿ—บ๏ธ Roadmap

  • Web dashboard for visualization
  • Multi-model evaluation consensus
  • Custom attack taxonomy
  • Continuous monitoring service
  • ML-based vulnerability prediction
  • Automated remediation
  • Enterprise support

๐Ÿ“Š Project Stats

  • Framework Version: 1.0.0
  • Python Support: 3.9+
  • Test Coverage: 115+ tests
  • LLM Providers: 5+ (OpenAI, Azure, Groq, Gemini, Ollama)
  • Attack Categories: 28
  • Known Vulnerabilities: 40+
  • Lines of Code: 5000+
  • Documentation: 100+ pages

๐ŸŒŸ Getting Help

New to NPersona? โ†’ Start with QUICK_START_TUTORIAL.md

Need detailed info? โ†’ Read USER_GUIDE.md

Want to contribute? โ†’ See CONTRIBUTING.md

Found a security issue? โ†’ Email npersona.ai@gmail.com


๐ŸŽ‰ Made with โค๏ธ by NPersona-AI

NPersona - Making AI Systems Safer, One Test at a Time.

 โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—
 โ•‘                                               โ•‘
 โ•‘   ๐Ÿ›ก๏ธ  Security Testing for AI Systems  ๐Ÿ›ก๏ธ    โ•‘
 โ•‘                                               โ•‘
 โ•‘   Production-Ready โ€ข Comprehensive โ€ข Fast    โ•‘
 โ•‘                                               โ•‘
 โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

Latest Release: v1.0.0 (April 13, 2026)

Star us on GitHub

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

npersona-1.0.0.tar.gz (88.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

npersona-1.0.0-py3-none-any.whl (79.8 kB view details)

Uploaded Python 3

File details

Details for the file npersona-1.0.0.tar.gz.

File metadata

  • Download URL: npersona-1.0.0.tar.gz
  • Upload date:
  • Size: 88.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for npersona-1.0.0.tar.gz
Algorithm Hash digest
SHA256 78f459d92318483c91bb4ea74e80ab74b0f5a83e50198f54653c33a95b1bf34a
MD5 49f01c1f1c595597878f149a0acd23d1
BLAKE2b-256 cee1090e133fc9c06f5e6343ff9c3e0fb9c69796eca75a82cfb964b8476b50cf

See more details on using hashes here.

File details

Details for the file npersona-1.0.0-py3-none-any.whl.

File metadata

  • Download URL: npersona-1.0.0-py3-none-any.whl
  • Upload date:
  • Size: 79.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.11.0

File hashes

Hashes for npersona-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a936dfa65e2278755d6dc4748f7ea57838ddddc8c49180724e49c9f2729f7139
MD5 69de37e192d3855216d48dcad9ada6ed
BLAKE2b-256 bdeb0e47a2c856261fc91a34c999dc06592d4e167ecc7e0dd1aef9e59113697a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page