Petru Constantin is the founder of DeviDevs and designed the multi-agent platform the company runs on, with guardrails enforced in code. Code examples are written against the ART 1.20.1, Python 3.13, actions/checkout v7, actions/setup-python v7 and actions/upload-artifact v7 documentation.
AI Security Testing Automation: Comprehensive ML System Vulnerability Assessment
Automated security testing is essential for identifying vulnerabilities in AI systems before deployment. This guide covers comprehensive testing frameworks for ML system security assessment.
AI Security Testing Framework
Core Testing Architecture
from dataclasses import dataclass, field
from datetime import datetime, timezone
from enum import Enum
from typing import Any, Callable, Dict, List, Optional
import time
import numpy as np
from art.attacks.evasion import FastGradientMethod, ProjectedGradientDescent
from art.attacks.inference.membership_inference import MembershipInferenceBlackBox
from art.estimators.classification import PyTorchClassifier
class TestCategory(Enum):
ADVERSARIAL = "adversarial"
INPUT_VALIDATION = "input_validation"
PRIVACY = "privacy"
ROBUSTNESS = "robustness"
class TestResult(Enum):
PASSED = "passed"
FAILED = "failed"
ERROR = "error"
SKIPPED = "skipped"
@dataclass
class TestData:
x_train: np.ndarray # samples the model was trained on (members)
y_train: np.ndarray # integer class labels
x_test: np.ndarray # held-out samples the model never saw (non-members)
y_test: np.ndarray
@dataclass
class SecurityTest:
id: str
name: str
category: TestCategory
severity: str # critical, high, medium, low
test_function: Callable[[TestData], Dict]
enabled: bool = True
@dataclass
class TestExecutionResult:
test_id: str
test_name: str
category: TestCategory
result: TestResult
severity: str
details: Dict[str, Any]
vulnerabilities_found: List[Dict]
execution_time_ms: float
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
class AISecurityTestFramework:
"""Runs ART attacks against a classifier wrapped in PyTorchClassifier.
Every number in the report comes from an attack or a prediction that
actually ran. Passing means the model held up against these attacks at
these budgets; it is not proof against stronger or adaptive attacks.
"""
def __init__(self, classifier: PyTorchClassifier, config: Optional[Dict] = None,
input_validator: Optional[Callable[[np.ndarray], None]] = None):
self.classifier = classifier # set clip_values so eps budgets match your input scale
self.config = config or {}
# The validator your serving code runs before predict(); it must raise ValueError on bad input
self.input_validator = input_validator
self.tests: Dict[str, SecurityTest] = {}
self.results: List[TestExecutionResult] = []
self._register_default_tests()
def _register_default_tests(self):
for test in [
SecurityTest("ADV-001", "FGSM attack resistance", TestCategory.ADVERSARIAL, "high", self._test_fgsm),
SecurityTest("ADV-002", "PGD attack resistance", TestCategory.ADVERSARIAL, "high", self._test_pgd),
SecurityTest("INP-001", "Invalid input rejection", TestCategory.INPUT_VALIDATION, "medium", self._test_invalid_inputs),
SecurityTest("PRV-001", "Membership inference resistance", TestCategory.PRIVACY, "high", self._test_membership_inference),
SecurityTest("ROB-001", "Gaussian noise tolerance", TestCategory.ROBUSTNESS, "medium", self._test_noise_tolerance),
]:
self.register_test(test)
def register_test(self, test: SecurityTest):
self.tests[test.id] = test
def run_all_tests(self, data: TestData) -> Dict:
self.results = []
start_time = datetime.now(timezone.utc)
for test in self.tests.values():
if not test.enabled:
self.results.append(TestExecutionResult(
test.id, test.name, test.category, TestResult.SKIPPED,
test.severity, {"reason": "Test disabled"}, [], 0.0))
continue
self.results.append(self._execute_test(test, data))
return self._generate_report(start_time)
def _execute_test(self, test: SecurityTest, data: TestData) -> TestExecutionResult:
start = time.perf_counter()
try:
outcome = test.test_function(data)
vulns = outcome.get("vulnerabilities", [])
status = TestResult.FAILED if vulns else TestResult.PASSED
return TestExecutionResult(test.id, test.name, test.category, status, test.severity,
outcome.get("details", {}), vulns,
(time.perf_counter() - start) * 1000)
except Exception as e: # an attack that crashed is an ERROR, never a pass
return TestExecutionResult(test.id, test.name, test.category, TestResult.ERROR,
test.severity, {"error": str(e)}, [],
(time.perf_counter() - start) * 1000)
def _sample(self, x: np.ndarray, y: np.ndarray):
n = min(len(x), self.config.get("max_samples", 500))
return x[:n], y[:n]
def _accuracy(self, x: np.ndarray, y: np.ndarray) -> float:
predictions = self.classifier.predict(x)
return float(np.mean(np.argmax(predictions, axis=1) == y))
def _evasion_test(self, data: TestData, attack_name: str, make_attack, budgets) -> Dict:
x, y = self._sample(data.x_test, data.y_test)
max_drop = self.config.get("max_accuracy_drop", 0.3)
clean_acc = self._accuracy(x, y)
details = {"clean_accuracy": clean_acc, "adversarial_accuracy": {}}
vulns = []
for eps in budgets:
x_adv = make_attack(eps).generate(x=x)
adv_acc = self._accuracy(x_adv, y)
details["adversarial_accuracy"][str(eps)] = adv_acc
if clean_acc - adv_acc > max_drop:
vulns.append({"type": f"{attack_name} vulnerability", "epsilon": eps,
"clean_accuracy": clean_acc, "adversarial_accuracy": adv_acc,
"severity": "high"})
return {"details": details, "vulnerabilities": vulns}
def _test_fgsm(self, data: TestData) -> Dict:
return self._evasion_test(
data, "FGSM",
lambda eps: FastGradientMethod(estimator=self.classifier, eps=eps),
self.config.get("fgsm_epsilons", [0.01, 0.03, 0.1]))
def _test_pgd(self, data: TestData) -> Dict:
max_iter = self.config.get("pgd_max_iter", 40)
return self._evasion_test(
data, "PGD",
lambda eps: ProjectedGradientDescent(estimator=self.classifier, eps=eps,
eps_step=eps / 4, max_iter=max_iter,
verbose=False),
self.config.get("pgd_epsilons", [0.03, 0.1]))
def _test_invalid_inputs(self, data: TestData) -> Dict:
if self.input_validator is None:
return {"details": {"reason": "No input validator configured"},
"vulnerabilities": [{"type": "Input validation missing", "severity": "medium"}]}
sample = data.x_test[:1].astype(np.float32)
cases = {
"nan_values": np.full_like(sample, np.nan),
"inf_values": np.full_like(sample, np.inf),
"wrong_shape": sample.reshape(-1)[:-1],
"empty_input": sample[:0],
}
if self.classifier.clip_values is not None:
cases["out_of_range"] = np.full_like(sample, np.max(self.classifier.clip_values[1]) + 1000.0)
details, vulns = {}, []
for name, bad_input in cases.items():
try:
self.input_validator(bad_input)
details[name] = "accepted"
vulns.append({"type": "Input validation failure", "test_case": name, "severity": "medium"})
except ValueError as e:
details[name] = f"rejected: {e}"
return {"details": details, "vulnerabilities": vulns}
def _test_membership_inference(self, data: TestData) -> Dict:
threshold = self.config.get("membership_inference_threshold", 0.6)
x_in, y_in = self._sample(data.x_train, data.y_train)
x_out, y_out = self._sample(data.x_test, data.y_test)
n = min(len(x_in), len(x_out)) // 2
# Train the attack model on one half, measure it on the other half
attack = MembershipInferenceBlackBox(self.classifier)
attack.fit(x=x_in[:n], y=y_in[:n], test_x=x_out[:n], test_y=y_out[:n])
inferred_in = np.ravel(attack.infer(x_in[n:2 * n], y_in[n:2 * n]))
inferred_out = np.ravel(attack.infer(x_out[n:2 * n], y_out[n:2 * n]))
attack_accuracy = float((np.sum(inferred_in == 1) + np.sum(inferred_out == 0))
/ (len(inferred_in) + len(inferred_out)))
vulns = []
if attack_accuracy > threshold:
vulns.append({"type": "Membership inference vulnerability",
"attack_accuracy": attack_accuracy, "threshold": threshold,
"severity": "high"})
return {"details": {"attack_accuracy": attack_accuracy, "threshold": threshold,
"baseline": 0.5},
"vulnerabilities": vulns}
def _test_noise_tolerance(self, data: TestData) -> Dict:
x, y = self._sample(data.x_test, data.y_test)
max_drop = self.config.get("max_noise_accuracy_drop", 0.1)
rng = np.random.default_rng(self.config.get("seed", 0))
clean_acc = self._accuracy(x, y)
details, vulns = {"clean_accuracy": clean_acc, "noisy_accuracy": {}}, []
for sigma in self.config.get("noise_levels", [0.01, 0.05, 0.1]):
x_noisy = x + rng.normal(0.0, sigma, size=x.shape).astype(x.dtype)
if self.classifier.clip_values is not None:
x_noisy = np.clip(x_noisy, *self.classifier.clip_values)
noisy_acc = self._accuracy(x_noisy, y)
details["noisy_accuracy"][str(sigma)] = noisy_acc
if clean_acc - noisy_acc > max_drop:
vulns.append({"type": "Excessive noise sensitivity", "sigma": sigma,
"accuracy_drop": clean_acc - noisy_acc, "severity": "medium"})
return {"details": details, "vulnerabilities": vulns}
def _generate_report(self, start_time: datetime) -> Dict:
end_time = datetime.now(timezone.utc)
def count(status: TestResult) -> int:
return sum(1 for r in self.results if r.result == status)
vulns = [v for r in self.results for v in r.vulnerabilities_found]
by_severity = {s: sum(1 for v in vulns if v.get("severity") == s)
for s in ("critical", "high", "medium", "low")}
return {
"report_id": f"security_test_{start_time:%Y%m%d_%H%M%S}",
"execution_time": {
"start": start_time.isoformat(),
"end": end_time.isoformat(),
"duration_seconds": (end_time - start_time).total_seconds(),
},
"summary": {
"total_tests": len(self.results),
"passed": count(TestResult.PASSED),
"failed": count(TestResult.FAILED),
"errors": count(TestResult.ERROR),
"skipped": count(TestResult.SKIPPED),
},
"vulnerabilities": {"total": len(vulns), "by_severity": by_severity, "details": vulns},
"detailed_results": [
{"test_id": r.test_id, "test_name": r.test_name, "category": r.category.value,
"result": r.result.value, "severity": r.severity, "details": r.details,
"execution_time_ms": r.execution_time_ms, "vulnerabilities": r.vulnerabilities_found}
for r in self.results
],
"recommendations": self._generate_recommendations(vulns),
}
def _generate_recommendations(self, vulnerabilities: List[Dict]) -> List[Dict]:
vuln_types = {v.get("type", "") for v in vulnerabilities}
recommendations = []
if any("FGSM" in t or "PGD" in t for t in vuln_types):
recommendations.append({
"priority": "high", "area": "Adversarial Robustness",
"recommendation": "Evaluate adversarial training and re-run with stronger attacks",
"references": ["https://arxiv.org/abs/1412.6572"]})
if any("Input validation" in t for t in vuln_types):
recommendations.append({
"priority": "high", "area": "Input Validation",
"recommendation": "Reject NaN, Inf, wrong shapes and out-of-range values before predict()",
"references": []})
if any("Membership inference" in t for t in vuln_types):
recommendations.append({
"priority": "high", "area": "Privacy",
"recommendation": "Reduce overfitting; consider differential privacy for training",
"references": []})
if any("noise" in t for t in vuln_types):
recommendations.append({
"priority": "medium", "area": "Robustness",
"recommendation": "Add noise augmentation and monitor input quality in production",
"references": []})
return recommendationsCI/CD Integration
# .github/workflows/ai-security-tests.yml
name: AI Security Tests
on:
push:
paths:
- 'models/**'
- 'src/ml/**'
pull_request:
paths:
- 'models/**'
- 'src/ml/**'
schedule:
- cron: '0 2 * * 1' # Mondays 02:00 UTC
permissions:
contents: read
jobs:
security-tests:
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write # PRs from forks still get a read-only token, so the comment step fails there
steps:
- uses: actions/checkout@v7
- name: Set up Python
uses: actions/setup-python@v7
with:
python-version: '3.13'
- name: Install dependencies
run: |
pip install -r requirements-ml.txt
pip install adversarial-robustness-toolbox
- name: Run AI security tests
# Builds the PyTorchClassifier and TestData, runs AISecurityTestFramework
# and writes the report dict as JSON
run: python scripts/run_ai_security_tests.py --output security-report.json
- name: Upload results
if: always()
uses: actions/upload-artifact@v7
with:
name: security-test-results
path: security-report.json
- name: Comment on PR
if: always() && github.event_name == 'pull_request'
env:
GH_TOKEN: ${{ github.token }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: |
python - <<'EOF' > pr-comment.md
import json
report = json.load(open("security-report.json"))
summary, vulns = report["summary"], report["vulnerabilities"]
print("## AI Security Test Results\n")
print("| Metric | Value |\n|---|---|")
for key in ("total_tests", "passed", "failed", "errors", "skipped"):
print(f"| {key} | {summary[key]} |")
print(f"| vulnerabilities | {vulns['total']} |\n")
for severity, n in vulns["by_severity"].items():
print(f"- {severity}: {n}")
if report["recommendations"]:
print("\n### Recommendations")
for rec in report["recommendations"]:
print(f"- **{rec['area']}**: {rec['recommendation']}")
EOF
gh pr comment "$PR_NUMBER" --body-file pr-comment.md
- name: Fail on high or critical findings and on errored tests
run: |
python - <<'EOF'
import json, sys
report = json.load(open("security-report.json"))
sev = report["vulnerabilities"]["by_severity"]
errors = report["summary"]["errors"]
if sev["critical"] or sev["high"] or errors:
print(f"{sev['critical']} critical, {sev['high']} high, {errors} errored tests")
sys.exit(1)
EOFBest Practices
Testing Strategy
- Regular testing: Run security tests on every model update
- Comprehensive coverage: Test adversarial, privacy, and robustness aspects
- Threshold tuning: Adjust pass/fail thresholds based on risk tolerance
- Continuous monitoring: Monitor for new attack vectors
Integration Guidelines
- Include security tests in CI/CD pipelines
- Block deployments with critical vulnerabilities
- Generate reports for security team review
- Track vulnerability trends over time
Automated AI security testing ensures vulnerabilities are identified early and consistently across the ML development lifecycle.
From production
JARVIS, the multi-agent platform DeviDevs runs on Claude Code, keeps its security rules in code as hooks, and those hooks have their own tests: 47 test files, and as of 15 November 2026 the tests for the security rules pass. Two lessons from that suite apply to any AI security test setup. First, regressions look like cleanups: a narrowing of a regex in the prompt injection detector looked clean but lost real protection (a "SYSTEM PROMPT: You are..." string was no longer caught); a measurement caught it, and a test now pins that string. An exception on a substring would likewise have switched the detector off exactly when a command also carried a real attack vector. Both changes were rejected. Second, tests that exist but do not run protect nothing: until September 2026 nobody ran the hook tests, neither CI nor pre-commit, and then they got a runner. What JARVIS does not have is a security evaluation set or benchmark of its own; it measures token cost per run and the correction rate from transcripts.
Official references
- Evasion Attacks - Adversarial Robustness Toolbox documentation
- Membership Inference - Adversarial Robustness Toolbox documentation
- Releases - Trusted-AI/adversarial-robustness-toolbox
- Releases - actions/checkout
- gh pr comment - GitHub CLI manual
- datetime - Basic date and time types
Related on this site: Every AI Security Startup Got Acquired. Now What?, Your AI Agent Framework Is Probably Compromised Right Now, AI API Security: Auth, Authorization & Rate Limiting. More articles in the AI Security category, and the engineering work behind them is on the services page.
Need an AI system built and running in production, with the scope agreed in writing and a delivery guarantee? See how a DeviDevs Sprint works →