ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.
Python active-directorycloud-securitydefensive-validationfastapigood-first-issuemitre-attackopsecreactred-teamreportingsecurity
feat(sdk): modernize ARES SDK to v2 standard, add testing harness, client SDK, and update docs
Mafifrizidc1acaf95b82
diff --git a/QUICKSTART.md b/QUICKSTART.mdindex febc19a..a1df480 100644--- a/QUICKSTART.md+++ b/QUICKSTART.md@@ -393,22 +393,26 @@ export OPENAI_API_KEY="..."Use Strategy only after a campaign exists, scope is correct, authorizationnotes are clear, and the selected LLM backend is configured.-### Public SDK+### Public SDK (v2 Modern Standard)-Use the public SDK import path for custom modules:+Use the modern, type-safe SDK import path for custom modules, unit testing, and automation:```python-from ares.sdk import BaseModule, ExecutionContext, Finding, ModuleResult+from ares.sdk import (+ BaseModule, ExecutionContext, ModuleResult,+ ModuleParams, param, SecretParam,+ OpsecLevel, Severity, ares_module,+ ModuleTestHarness, AresClient,+)```-`ares.modules.sdk` remains as a compatibility shim, but new code should use-`ares.sdk`.+`ares.modules.sdk` remains as a 100% backward-compatible shim, but new modules should use `ares.sdk`.See:-- `docs/module-development.md`-- `docs/module_sdk.md`-- `docs/examples/example_http_enum.py`+- [`docs/module_sdk.md`](docs/module_sdk.md) (Full v2 SDK Architecture & Client Guide)+- [`docs/module-development.md`](docs/module-development.md) (Step-by-step authoring guide)+- [`example_modules/example_modern_v2_module.py`](example_modules/example_modern_v2_module.py) (Reference implementation)### Validation labdiff --git a/README.md b/README.mdindex e434c87..1258dbb 100644--- a/README.md+++ b/README.md@@ -125,6 +125,12 @@ The ARES Platform features a high-performance, responsive operator dashboard eng*Executive Command Center displaying real-time telemetry, confirmed findings by severity, and operational health.*+<br>++++*Tactical Zero-State Overview — Clean onboarding hero with instant readiness strip and initialization actions when running zero active campaigns.*+</div>- **The Problem Solved**: Aggregates scattered offensive metrics into a single real-time operational pane without requiring manual status queries.@@ -398,42 +404,72 @@ ARES enforces strict RBAC permissions across all API endpoints and UI controls:----## 🛠️ Extensible Developer SDK+## 🛠️ Extensible Developer SDK (v2 Modern Standard)-Build custom adversary modules, integrate proprietary attack tools, or extend telemetry parsers using the clean `ares.sdk` interface:+ARES provides a first-class, type-safe Python SDK (`ares.sdk`) to build custom adversary modules, simulate techniques in isolated test harnesses, and automate engagements programmatically:++### 1. Type-Safe Module Authoring (Generic `BaseModule[P, R]` & `@ares_module`)+Declare validated parameter schemas with Pydantic v2 and write modules with full IDE autocomplete:```python-from ares.sdk import BaseModule, ExecutionContext, ModuleResult--class CustomKerberoastModule(BaseModule):- id = "custom.ad.kerberoast"- name = "Custom SPN Extraction & Kerberoasting"- description = "Extracts SPNs from targeted Active Directory domain controllers."- category = "active_directory"- mitre_techniques = ["T1558.003"]- opsec_level = "medium"-- def run(self, ctx: ExecutionContext) -> ModuleResult:- # Hard scope validation is enforced automatically by ctx- target_ip = ctx.params.get("target_ip")-- if ctx.is_dry_run:- return ModuleResult.ok("Dry-run validated: target inside approved scope.")-- # Execute check inside scope boundary- hashes = self._extract_spn_hashes(target_ip)-- # Save captured hash to AES-256 encrypted campaign vault- ctx.vault.store_credential(- cred_type="kerberos_hash",- target=target_ip,- secret=hashes+from ares.sdk import (+ BaseModule, ExecutionContext, ModuleResult,+ ModuleParams, param, SecretParam,+ OpsecLevel, Severity, ares_module,+)++class KerberoastParams(ModuleParams):+ dc: str = param("Target Domain Controller IP or FQDN", min_length=3)+ domain: str = param("AD DNS domain name, e.g. CORP.LOCAL", min_length=3)+ password: SecretParam = param("Domain user password", secret=True, required=False)++class CustomKerberoastModule(BaseModule[KerberoastParams, ModuleResult]):+ MODULE_ID = "custom.ad.kerberoast"+ MODULE_NAME = "Custom Kerberoasting"+ MODULE_CATEGORY = "ad"+ OPSEC_LEVEL = OpsecLevel.LOW+ MITRE_TECHNIQUES = ["T1558.003"]+ PARAMS_MODEL = KerberoastParams++ async def execute(self, ctx: ExecutionContext[KerberoastParams]) -> ModuleResult:+ # ctx.params provides full static typing and runtime validation+ await self.before_request(ctx.params.dc)++ # Emit findings using fluent context helpers+ finding = ctx.emit_finding(+ title=f"Kerberoastable SPN Captured on {ctx.params.dc}",+ severity=Severity.HIGH,+ mitre_technique="T1558.003",)-- return ModuleResult.ok(f"Extracted {len(hashes)} SPN hashes.", data={"count": len(hashes)})+ return ModuleResult(status="success", findings=[finding], module_id=self.MODULE_ID)+```++### 2. Isolated Testing & Simulation (`ModuleTestHarness`)+Unit test custom techniques locally with mock scope guards, synthetic credential vaults, and fluent assertion matchers:++```python+from ares.sdk import ModuleTestHarness, Severity++async def test_module():+ harness = ModuleTestHarness(CustomKerberoastModule)+ result = await harness.simulate(params={"dc": "10.0.0.10", "domain": "LAB.LOCAL"})+ result.assert_success()+ result.assert_finding(severity=Severity.HIGH, mitre="T1558.003")+```++### 3. Programmatic Automation (`AresClient`)+Automate engagements, dispatch modules, and stream real-time WebSocket telemetry via Python scripts or CI/CD pipelines:++```python+from ares.sdk import AresClient++async with AresClient(base_url="http://127.0.0.1:8000", api_key="ares_key_...") as ares:+ campaign = await ares.campaigns.create(name="Op-Titan", scope=["10.0.0.0/24"])+ job = await ares.modules.run("ad.kerberoast", target="dc01.corp.local", campaign_id=campaign["id"])+ findings = await ares.campaigns.findings(campaign["id"])```-See [docs/module-development.md](docs/module-development.md) for full developer documentation.+See [docs/module_sdk.md](docs/module_sdk.md) and [docs/module-development.md](docs/module-development.md) for full developer documentation, architecture specifications, and examples.---@@ -443,13 +479,14 @@ Comprehensive documentation is available in the [`docs/`](docs/) directory:- [**Documentation Portal & Subsystem Index**](docs/README.md)- [**Quickstart Engagement Guide**](QUICKSTART.md)+- [**Modern Module SDK Specification (v2)**](docs/module_sdk.md)+- [**Step-by-Step Module Development Guide**](docs/module-development.md)- [**Dashboard Surface-by-Surface Manual**](docs/dashboard-guide.md)- [**Adversary Module Catalog & Schemas**](docs/modules.md)- [**API Endpoint Reference & Payloads**](docs/api-reference.md)- [**Enterprise SSO Integration Guide (SAML 2.0 / OIDC)**](docs/sso-setup.md)- [**Enterprise Security & Threat Model**](docs/security-model.md)- [**Validation Lab & Test Harness**](docs/validation-lab.md)-- [**Module Authoring SDK Guide**](docs/module-development.md)---diff --git a/ares/core/context.py b/ares/core/context.pyindex ac79688..0060c10 100644--- a/ares/core/context.py+++ b/ares/core/context.py@@ -31,10 +31,13 @@ from __future__ import annotationsimport timeimport uuidfrom dataclasses import dataclass, field-from typing import Any, TYPE_CHECKING+from typing import Any, Generic, TYPE_CHECKING, TypeVarfrom ares.core.errors import InvalidContext+P = TypeVar("P")+T = TypeVar("T")+if TYPE_CHECKING:from ares.core.campaign import Campaign, NoiseProfilefrom ares.core.config import AresSettings@@ -46,7 +49,7 @@ if TYPE_CHECKING:@dataclass-class ExecutionContext:+class ExecutionContext(Generic[P]):"""Unified execution context passed to every module.Immutable after construction (fields are set once by the engine).@@ -75,7 +78,7 @@ class ExecutionContext:port: int = 0 # specific port if protocol-targeted# ── Parameters ────────────────────────────────────────────────────────- params: dict[str, Any] = field(default_factory=dict)+ params: P | dict[str, Any] = field(default_factory=dict)# ── Credentials ───────────────────────────────────────────────────────# Ordered by score (highest first). Module tries each in order.@@ -105,8 +108,9 @@ class ExecutionContext:dry_run: bool = False # simulation mode — no real network calls# ── Metadata ──────────────────────────────────────────────────────────- tags: list[str] = field(default_factory=list)- extra: dict[str, Any] = field(default_factory=dict)+ tags: list[str] = field(default_factory=list)+ extra: dict[str, Any] = field(default_factory=dict)+ findings: list[Any] = field(default_factory=list)# ── Validation ────────────────────────────────────────────────────────@@ -137,6 +141,81 @@ class ExecutionContext:for f in fields)+ # ── Fluent helpers (v2 Modern SDK) ────────────────────────────────────++ def typed_params(self, model_cls: type[T]) -> T:+ """Parse, validate, and return params as a typed Pydantic model."""+ from ares.sdk.params import validate_params++ return validate_params(model_cls, self.params, module_id=self.module_id)++ def emit_finding(+ self,+ title: str,+ severity: Any,+ description: str = "",+ mitre_technique: str | None = None,+ mitre_tactic: str | None = None,+ evidence: dict[str, Any] | None = None,+ remediation: str = "",+ host: str | None = None,+ confidence: float = 1.0,+ ) -> Any:+ """Fluent helper to create and record a finding in the execution context."""+ from ares.core.campaign import Finding, Severity++ sev = severity if isinstance(severity, Severity) else Severity(str(severity).lower())+ desc = description.strip() if (description and description.strip()) else (title.strip() or "Finding emitted")+ finding = Finding(+ id=str(uuid.uuid4()),+ title=title,+ description=desc,+ severity=sev,+ mitre_technique=mitre_technique,+ mitre_tactic=mitre_tactic,+ evidence=evidence or {},+ remediation=remediation,+ host=host or self.target,+ confidence=confidence,+ module_id=self.module_id,+ )+ if self.runtime_state and hasattr(self.runtime_state, "record_finding"):+ try:+ self.runtime_state.record_finding(finding)+ except Exception:+ pass+ self.findings.append(finding)+ return finding++ def store_artifact(self, artifact: Any) -> Any:+ """Store an artifact in the execution context's artifact store if available."""+ if self.artifact_store and hasattr(self.artifact_store, "add"):+ return self.artifact_store.add(artifact)+ return None++ def record_credential(+ self,+ username: str,+ secret: str = "",+ domain: str = "",+ cred_type: str = "password",+ metadata: dict[str, Any] | None = None,+ ) -> Any:+ """Store a discovered credential in the context vault if available."""+ if self.vault and hasattr(self.vault, "add"):+ try:+ return self.vault.add(+ username=username,+ secret=secret,+ domain=domain or self.domain,+ cred_type=cred_type,+ host=self.target,+ metadata=metadata or {},+ )+ except Exception:+ pass+ return None+# ── Accessors ─────────────────────────────────────────────────────────def best_credential(self) -> "Credential | None":diff --git a/ares/modules/base.py b/ares/modules/base.pyindex 1502b0e..b671e93 100644--- a/ares/modules/base.py+++ b/ares/modules/base.py@@ -28,7 +28,10 @@ import abcimport uuidfrom dataclasses import dataclass, fieldfrom enum import Enum-from typing import Any, TYPE_CHECKING+from typing import Any, Generic, TYPE_CHECKING, TypeVar++P = TypeVar("P", bound=Any)+R = TypeVar("R", bound=Any)from ares.core.campaign import Campaign, Finding, Severityfrom ares.core.config import AresSettings@@ -71,13 +74,17 @@ def normalize_module_metadata(metadata = dict(base or {})if param_schema is None:- try:- from ares.modules.params import MODULE_PARAMS+ params_model = getattr(cls, "PARAMS_MODEL", None)+ if params_model is not None and hasattr(params_model, "schema_for_api"):+ param_schema = params_model.schema_for_api()+ else:+ try:+ from ares.modules.params import MODULE_PARAMS- params_model = MODULE_PARAMS.get(str(getattr(cls, "MODULE_ID", "")))- param_schema = params_model.schema_for_api() if params_model else {}- except (ImportError, AttributeError):- param_schema = {}+ model = MODULE_PARAMS.get(str(getattr(cls, "MODULE_ID", "")))+ param_schema = model.schema_for_api() if model else {}+ except (ImportError, AttributeError):+ param_schema = {}schema = param_schema or {}required_params = [@@ -169,7 +176,7 @@ class FeasibilityReport:# ── BaseModule ────────────────────────────────────────────────────────────────-class BaseModule(abc.ABC):+class BaseModule(abc.ABC, Generic[P, R]):"""Abstract base for all ARES modules.@@ -180,6 +187,8 @@ class BaseModule(abc.ABC):Formal SDK contract (v0.9.0+) — see validate(), before_request(), finding()."""+ PARAMS_MODEL: Any = None+async def assess_feasibility(self, ctx: "Any") -> FeasibilityReport:"""Evaluate whether this module is feasible against target defenses@@ -238,6 +247,11 @@ class BaseModule(abc.ABC):if not isinstance(ctx, ExecutionContext):return # legacy context — skip validation+ if getattr(self, "PARAMS_MODEL", None) is not None:+ from ares.sdk.params import validate_params++ ctx.params = validate_params(self.PARAMS_MODEL, ctx.params, module_id=self.MODULE_ID)+# Categories that use API credentials instead of a target IP — skip target check_NO_TARGET_CATEGORIES = {"cloud", "reporting", "recon"}if getattr(self.__class__, "MODULE_CATEGORY", "") in _NO_TARGET_CATEGORIES:@@ -255,11 +269,12 @@ class BaseModule(abc.ABC):# Check REQUIRES list — each item must be present in params or contextrequires = getattr(self.__class__, "REQUIRES", [])if requires:- available: set[str] = set(ctx.params.keys())+ raw_params = ctx.params.model_dump() if hasattr(ctx.params, "model_dump") else (ctx.params or {})+ available: set[str] = set(raw_params.keys())if ctx.target: available.add("target")if ctx.domain: available.add("domain")if getattr(ctx, "vault", None): available.add("vault")- params = getattr(ctx, "params", {}) or {}+ params = raw_paramsdef _present(*names: str) -> bool:return any(params.get(name) not in (None, "", []) for name in names)@@ -310,14 +325,32 @@ class BaseModule(abc.ABC):Returns:ModuleResult — structured result consumed by engine"""- findings, raw = await self.run(**ctx.params)- return ModuleResult(- status = "success" if findings or raw else "partial",- findings = findings,- raw = raw,- module_id = self.MODULE_ID,- execution_id = ctx.execution_id if hasattr(ctx, "execution_id") else "",- )+ raw_params = getattr(ctx, "params", {})+ if hasattr(raw_params, "model_dump"):+ kwargs = raw_params.model_dump()+ elif isinstance(raw_params, dict):+ kwargs = raw_params+ else:+ kwargs = {}++ try:+ findings, raw = await self.run(**kwargs)+ return ModuleResult(+ status = "success" if findings or raw else "partial",+ findings = findings,+ raw = raw,+ module_id = self.MODULE_ID,+ execution_id = getattr(ctx, "execution_id", ""),+ )+ except NotImplementedError:+ findings = getattr(ctx, "findings", [])+ return ModuleResult(+ status = "success" if findings else "partial",+ findings = findings,+ raw = {},+ module_id = self.MODULE_ID,+ execution_id = getattr(ctx, "execution_id", ""),+ )def report(self, result: "ModuleResult") -> dict:"""diff --git a/ares/modules/params.py b/ares/modules/params.pyindex 72b69cb..0a3096d 100644--- a/ares/modules/params.py+++ b/ares/modules/params.py@@ -38,9 +38,12 @@ from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validatorSecretParam = SecretStr+_PARAM_REQUIRED_UNSET = object()++def param(description: str = "",- required: bool = True,+ required: bool | Any = _PARAM_REQUIRED_UNSET,default: Any = None,min_length: int | None = None,max_length: int | None = None,@@ -58,15 +61,20 @@ def param(password: SecretStr = param("Password", secret=True)timeout: int = param("Timeout seconds", required=False, default=30, ge=1, le=300)"""+ if required is _PARAM_REQUIRED_UNSET:+ is_required = default is None+ else:+ is_required = bool(required)+kwargs: dict[str, Any] = {"description": description,- "json_schema_extra": {"secret": secret, "required": required},+ "json_schema_extra": {"secret": secret, "required": is_required},}- if not required and default is not None:+ if not is_required and default is not None:kwargs["default"] = default- elif not required:+ elif not is_required:kwargs["default"] = None- # else: required=True, no default → pydantic marks as required+ # else: is_required=True, no default → pydantic marks as requiredif min_length is not None:kwargs["min_length"] = min_length@@ -148,7 +156,7 @@ class ModuleParams(BaseModel):def safe_dict(self) -> dict[str, Any]:"""Export params dict, replacing SecretStr values with '***'."""result = {}- for name, field_info in self.model_fields.items():+ for name, field_info in self.__class__.model_fields.items():val = getattr(self, name, None)if isinstance(val, SecretStr):result[name] = "***"diff --git a/ares/sdk/__init__.py b/ares/sdk/__init__.pyindex d3d1a9a..e3ab09d 100644--- a/ares/sdk/__init__.py+++ b/ares/sdk/__init__.py@@ -1,13 +1,22 @@-"""Public ARES SDK import surface.+"""Public ARES SDK import surface (v2 Modern Standard).-Prefer this package for module authoring and local integrations:+Provides everything needed for module authoring, testing, and programmatic automation:- from ares.sdk import BaseModule, ExecutionContext, ModuleResult+1. Module Authoring:+ from ares.sdk import BaseModule, ares_module, ExecutionContext, ModuleResult, OpsecLevel+ from ares.sdk import ModuleParams, param, SecretParam-The legacy ``ares.modules.sdk`` path remains available for existing modules.+2. Isolated Testing & Simulation:+ from ares.sdk import ModuleTestHarness, SimulationResult++3. Programmatic API Automation:+ from ares.sdk import AresClient++The legacy ``ares.modules.sdk`` path remains 100% available for existing modules."""from __future__ import annotations+# Core and legacy contracts (preserved for 100% backward compatibility)from ares.modules.sdk import (AccountLocked,AresError,@@ -52,12 +61,36 @@ from ares.modules.sdk import (validate_module_class,)+# v2 Modern Module Declarative & Schema Contracts+from ares.sdk.module import ares_module+from ares.sdk.params import ModuleParams, SecretParam, param, validate_params++# v2 Testing Harness+from ares.sdk.testing import ModuleTestHarness, SimulationResult++# v2 Programmatic API Client+from ares.sdk.client import (+ AresAuthenticationError,+ AresClient,+ AresClientError,+ AresNotFoundError,+ AresValidationError,+)+__all__ = [+ # Base module contracts"BaseModule","ModuleResult","OpsecLevel","validate_module_class","ExecutionContext",+ "ares_module",+ # Parameter schema contracts (Pydantic v2)+ "ModuleParams",+ "param",+ "SecretParam",+ "validate_params",+ # Errors"AresError","ModuleError","ModuleValidationError",@@ -79,19 +112,31 @@ __all__ = ["HoneypotDetected","InsufficientPrivilege","InvalidContext",+ # Campaign & telemetry"Finding","Severity","get_logger","TechniqueLibrary","TechniqueMapper",+ # Artifacts"ArtifactStore","HostArtifact","UserArtifact","CredentialArtifact","HashArtifact","PermissionArtifact",+ # Decorators"module_metadata","requires_privilege","timeout",+ # Testing & simulation"ModuleTestHelper",+ "ModuleTestHarness",+ "SimulationResult",+ # Programmatic Client SDK+ "AresClient",+ "AresClientError",+ "AresAuthenticationError",+ "AresNotFoundError",+ "AresValidationError",]diff --git a/ares/sdk/client/__init__.py b/ares/sdk/client/__init__.pynew file mode 100644index 0000000..666d8b9--- /dev/null+++ b/ares/sdk/client/__init__.py@@ -0,0 +1,28 @@+"""ARES Programmatic API Client SDK.++Exported symbols:+ from ares.sdk.client import (+ AresClient,+ AresClientError,+ AresAuthenticationError,+ AresNotFoundError,+ AresValidationError,+ )+"""+from __future__ import annotations++from ares.sdk.client.client import (+ AresAuthenticationError,+ AresClient,+ AresClientError,+ AresNotFoundError,+ AresValidationError,+)++__all__ = [+ "AresClient",+ "AresClientError",+ "AresAuthenticationError",+ "AresNotFoundError",+ "AresValidationError",+]diff --git a/ares/sdk/client/client.py b/ares/sdk/client/client.pynew file mode 100644index 0000000..344c699--- /dev/null+++ b/ares/sdk/client/client.py@@ -0,0 +1,278 @@+"""Programmatic Python Client SDK for ARES API Server (v6.0.0+).++Provides an asynchronous client to orchestrate campaigns, run attack modules,+query findings and attack graphs, and stream real-time execution events.++Usage:+ from ares.sdk import AresClient++ async with AresClient(base_url="http://127.0.0.1:8000", api_key="ares_key_...") as ares:+ campaign = await ares.campaigns.create(name="RedOps-2026", scope=["10.10.0.0/24"])+ print(f"Created campaign: {campaign['id']}")++ modules = await ares.modules.list()+ result = await ares.modules.run("ad.kerberoast", target="dc01.corp.local")+"""+from __future__ import annotations++import json+from collections.abc import AsyncGenerator+from typing import Any+from urllib.parse import urlparse++import httpx++try:+ import websockets+except ImportError:+ websockets = None # type: ignore[assignment]+++class AresClientError(Exception):+ """Base exception for ARES client errors."""+++class AresAuthenticationError(AresClientError):+ """Raised when authentication fails (HTTP 401/403)."""+++class AresNotFoundError(AresClientError):+ """Raised when the requested resource is not found (HTTP 404)."""+++class AresValidationError(AresClientError):+ """Raised when request payload validation fails (HTTP 422)."""+++class _CampaignsResource:+ """Operations on ARES campaigns."""++ def __init__(self, client: AresClient) -> None:+ self._c = client++ async def list(self, page: int = 1, per_page: int = 50) -> list[dict[str, Any]]:+ """List campaigns with pagination."""+ res = await self._c._get("/campaigns", params={"page": page, "per_page": per_page})+ return res if isinstance(res, list) else res.get("items", [])++ async def create(+ self,+ name: str,+ scope: list[str],+ client: str = "internal",+ noise_profile: str = "normal",+ domain: str = "",+ operator: str = "api_client",+ tags: list[str] | None = None,+ ) -> dict[str, Any]:+ """Create a new campaign."""+ payload = {+ "name": name,+ "scope": scope,+ "client": client,+ "noise_profile": noise_profile,+ "domain": domain,+ "operator": operator,+ "tags": tags or [],+ }+ return await self._c._post("/campaigns", json_data=payload)++ async def get(self, campaign_id: str) -> dict[str, Any]:+ """Get campaign details by ID."""+ return await self._c._get(f"/campaigns/{campaign_id}")++ async def delete(self, campaign_id: str) -> bool:+ """Delete a campaign by ID."""+ res = await self._c._delete(f"/campaigns/{campaign_id}")+ return bool(res.get("deleted", True))++ async def findings(+ self,+ campaign_id: str,+ page: int = 1,+ per_page: int = 100,+ severity: str | None = None,+ ) -> list[dict[str, Any]]:+ """List findings for a campaign."""+ params: dict[str, Any] = {"page": page, "per_page": per_page}+ if severity:+ params["severity"] = severity+ res = await self._c._get(f"/campaigns/{campaign_id}/findings", params=params)+ return res if isinstance(res, list) else res.get("items", [])++ async def hosts(self, campaign_id: str) -> list[dict[str, Any]]:+ """List discovered hosts for a campaign."""+ res = await self._c._get(f"/campaigns/{campaign_id}/hosts")+ return res if isinstance(res, list) else res.get("items", [])++ async def credentials(self, campaign_id: str) -> list[dict[str, Any]]:+ """List recovered credentials for a campaign."""+ res = await self._c._get(f"/campaigns/{campaign_id}/credentials")+ return res if isinstance(res, list) else res.get("items", [])++ async def graph(self, campaign_id: str) -> dict[str, Any]:+ """Retrieve the attack graph visualization payload for a campaign."""+ return await self._c._get(f"/campaigns/{campaign_id}/graph")+++class _ModulesResource:+ """Operations on ARES offensive modules."""++ def __init__(self, client: AresClient) -> None:+ self._c = client++ async def list(self) -> list[dict[str, Any]]:+ """List all available attack modules and their metadata schemas."""+ res = await self._c._get("/modules")+ return res if isinstance(res, list) else res.get("items", [])++ async def get(self, module_id: str) -> dict[str, Any]:+ """Get descriptor and parameter schema for a specific module."""+ return await self._c._get(f"/modules/{module_id}")++ async def run(+ self,+ module_id: str,+ target: str = "10.0.0.1",+ params: dict[str, Any] | None = None,+ campaign_id: str | None = None,+ dry_run: bool = False,+ ) -> dict[str, Any]:+ """Dispatch a module for execution."""+ payload = {+ "target": target,+ "params": params or {},+ "dry_run": dry_run,+ }+ if campaign_id:+ payload["campaign_id"] = campaign_id+ return await self._c._post(f"/modules/{module_id}/run", json_data=payload)+++class _TelemetryResource:+ """Real-time event streaming via WebSockets."""++ def __init__(self, client: AresClient) -> None:+ self._c = client++ async def stream_events(self, campaign_id: str) -> AsyncGenerator[dict[str, Any], None]:+ """Stream real-time campaign execution events over WebSocket."""+ if websockets is None:+ raise AresClientError("websockets library is required for event streaming. Install via: pip install websockets")++ parsed = urlparse(self._c.base_url)+ ws_scheme = "wss" if parsed.scheme == "https" else "ws"+ ws_url = f"{ws_scheme}://{parsed.netloc}/ws/campaigns/{campaign_id}/events"++ headers = {}+ if self._c.api_key:+ headers["X-API-Key"] = self._c.api_key+ elif self._c.token:+ headers["Authorization"] = f"Bearer {self._c.token}"++ async with websockets.connect(ws_url, extra_headers=headers) as ws:+ async for message in ws:+ if isinstance(message, bytes):+ message = message.decode("utf-8")+ try:+ yield json.loads(message)+ except Exception:+ yield {"raw": message}+++class AresClient:+ """Asynchronous programmatic Python client for ARES.++ Usage:+ async with AresClient(base_url="http://127.0.0.1:8000", api_key="...") as client:+ status = await client.health()+ """++ def __init__(+ self,+ base_url: str = "http://127.0.0.1:8000",+ api_key: str | None = None,+ token: str | None = None,+ timeout: float = 30.0,+ transport: httpx.AsyncBaseTransport | None = None,+ ) -> None:+ self.base_url = base_url.rstrip("/")+ self.api_key = api_key+ self.token = token+ self.timeout = timeout+ self._transport = transport++ headers = {"Accept": "application/json"}+ if api_key:+ headers["X-API-Key"] = api_key+ elif token:+ headers["Authorization"] = f"Bearer {token}"++ self._http = httpx.AsyncClient(+ base_url=self.base_url,+ headers=headers,+ timeout=timeout,+ transport=transport,+ )++ self.campaigns = _CampaignsResource(self)+ self.modules = _ModulesResource(self)+ self.telemetry = _TelemetryResource(self)++ async def __aenter__(self) -> AresClient:+ return self++ async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:+ await self.close()++ async def close(self) -> None:+ """Close the underlying HTTP client session."""+ await self._http.aclose()++ async def health(self) -> dict[str, Any]:+ """Check server connectivity and health."""+ return await self._get("/health")++ # ── Internal HTTP request dispatchers ─────────────────────────────────++ def _handle_error(self, response: httpx.Response) -> None:+ if response.is_success:+ return+ status = response.status_code+ try:+ err_data = response.json()+ message = err_data.get("detail") or err_data.get("message") or response.text+ except Exception:+ message = response.text or f"HTTP {status}"++ if status in (401, 403):+ raise AresAuthenticationError(f"Authentication failed ({status}): {message}")+ if status == 404:+ raise AresNotFoundError(f"Resource not found ({status}): {message}")+ if status == 422:+ raise AresValidationError(f"Validation error ({status}): {message}")+ raise AresClientError(f"API request failed ({status}): {message}")++ async def _get(self, path: str, params: dict[str, Any] | None = None) -> Any:+ res = await self._http.get(path, params=params)+ self._handle_error(res)+ return res.json()++ async def _post(self, path: str, json_data: dict[str, Any] | None = None) -> Any:+ res = await self._http.post(path, json=json_data)+ self._handle_error(res)+ return res.json()++ async def _delete(self, path: str) -> Any:+ res = await self._http.delete(path)+ self._handle_error(res)+ return res.json()+++__all__ = [+ "AresClient",+ "AresClientError",+ "AresAuthenticationError",+ "AresNotFoundError",+ "AresValidationError",+]diff --git a/ares/sdk/module.py b/ares/sdk/module.pynew file mode 100644index 0000000..fb980f4--- /dev/null+++ b/ares/sdk/module.py@@ -0,0 +1,177 @@+"""Modern ARES Module Authoring Contracts (v2 Standard).++Provides:+- BaseModule[P, R]: Type-safe generic base class for class-based modules.+- ares_module: Modern declarative decorator for functional and class modules.+"""+from __future__ import annotations++import asyncio+import functools+import inspect+from typing import Any, Callable, Generic, TypeVar++from pydantic import BaseModel++from ares.core.campaign import Finding+from ares.core.context import ExecutionContext+from ares.core.errors import ModuleValidationError+from ares.modules.base import (+ BaseModule as _CoreBaseModule,+ ModuleResult,+ OpsecLevel,+ validate_module_class,+)+from ares.sdk.params import validate_params++P = TypeVar("P", bound=Any)+R = TypeVar("R", bound=Any)+++BaseModule = _CoreBaseModule+++def ares_module(+ id: str,+ name: str,+ category: str,+ description: str = "",+ author: str = "Community",+ opsec: OpsecLevel = OpsecLevel.LOW,+ requires: list[str] | None = None,+ outputs: list[str] | None = None,+ mitre: list[str] | str | None = None,+ params_model: type[BaseModel] | None = None,+ capabilities: list[str] | None = None,+ timeout_seconds: int | float | None = None,+) -> Callable[[Any], type[BaseModule]]:+ """Declarative decorator for modern ARES module definitions.++ Supports both functional modules and class-based modules:++ Functional usage:+ @ares_module(+ id="ad.fast_check",+ name="Fast AD Check",+ category="ad",+ opsec=OpsecLevel.LOW,+ mitre="T1087.002",+ params_model=CheckParams,+ )+ async def fast_check(ctx: ExecutionContext[CheckParams]) -> ModuleResult:+ await ctx.emit_finding("AD User Found", Severity.MEDIUM)+ return ModuleResult(status="success", module_id="ad.fast_check")++ Class usage:+ @ares_module(+ id="ad.custom_attack",+ name="Custom Attack",+ category="ad",+ )+ class CustomAttack(BaseModule):+ ...+ """+ if not isinstance(category, str) or not category.strip():+ raise ValueError("ares_module category must be a non-empty string")+ if not isinstance(opsec, OpsecLevel) and str(opsec) not in {level.value for level in OpsecLevel}:+ raise ValueError("ares_module opsec must be an OpsecLevel or valid opsec level string")++ mitre_list: list[str] = [mitre] if isinstance(mitre, str) else (mitre or [])++ def decorator(target: Any) -> type[BaseModule]:+ # Case 1: Applied to a function+ if inspect.iscoroutinefunction(target) or inspect.isfunction(target):+ func = target++ class _DecoratedFunctionalModule(BaseModule):+ MODULE_ID = id+ MODULE_NAME = name+ MODULE_CATEGORY = category+ MODULE_DESCRIPTION = description+ MODULE_AUTHOR = author+ OPSEC_LEVEL = opsec+ REQUIRES = requires or []+ OUTPUTS = outputs or []+ MITRE_TECHNIQUES = mitre_list+ CAPABILITIES = capabilities or []+ MODULE_TIMEOUT_SECONDS = timeout_seconds+ PARAMS_MODEL = params_model++ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ self._fn = func++ async def execute(self, ctx: ExecutionContext) -> ModuleResult:+ result = await self._fn(ctx)+ if isinstance(result, ModuleResult):+ if not result.module_id:+ result.module_id = self.MODULE_ID+ return result+ if isinstance(result, tuple) and len(result) == 2:+ findings, raw = result+ return ModuleResult(+ status="success" if findings or raw else "partial",+ findings=findings or [],+ raw=raw or {},+ module_id=self.MODULE_ID,+ execution_id=getattr(ctx, "execution_id", ""),+ )+ # If function returned None or something else, collect findings from ctx+ findings = getattr(ctx, "findings", [])+ return ModuleResult(+ status="success" if findings else "partial",+ findings=findings,+ module_id=self.MODULE_ID,+ execution_id=getattr(ctx, "execution_id", ""),+ )++ async def run(self, **kwargs: Any) -> tuple[list[Finding], dict[str, Any]]:+ ctx = ExecutionContext.for_test(+ target=kwargs.get("target", "10.0.0.1"),+ module_id=self.MODULE_ID,+ params=kwargs,+ )+ res = await self.execute(ctx)+ return res.findings, res.raw++ _DecoratedFunctionalModule.__name__ = func.__name__+ _DecoratedFunctionalModule.__doc__ = description or func.__doc__+ errors = validate_module_class(_DecoratedFunctionalModule)+ if errors:+ raise ValueError(f"Module functional definition '{func.__name__}' invalid: {errors}")+ return _DecoratedFunctionalModule++ # Case 2: Applied to a class+ cls = target+ cls.MODULE_ID = id+ cls.MODULE_NAME = name+ cls.MODULE_CATEGORY = category+ cls.MODULE_DESCRIPTION = description+ cls.MODULE_AUTHOR = author+ cls.OPSEC_LEVEL = opsec+ cls.REQUIRES = requires or []+ cls.OUTPUTS = outputs or []+ cls.MITRE_TECHNIQUES = mitre_list+ if capabilities is not None:+ cls.CAPABILITIES = capabilities+ if timeout_seconds is not None:+ cls.MODULE_TIMEOUT_SECONDS = timeout_seconds+ cls.DEFAULT_TIMEOUT_S = timeout_seconds+ if params_model is not None:+ cls.PARAMS_MODEL = params_model++ errors = validate_module_class(cls)+ if errors:+ raise ValueError(f"Module class {cls.__name__!r} has validation errors: {errors}")+ return cls++ return decorator+++__all__ = [+ "BaseModule",+ "ModuleResult",+ "OpsecLevel",+ "ares_module",+ "validate_module_class",+]diff --git a/ares/sdk/params.py b/ares/sdk/params.pynew file mode 100644index 0000000..015ab2b--- /dev/null+++ b/ares/sdk/params.py@@ -0,0 +1,56 @@+"""Public ARES SDK parameter schema models and helpers.++Provides Pydantic v2 typed parameter definitions for module authors:+ from ares.sdk import ModuleParams, param, SecretParam+"""+from __future__ import annotations++from typing import Any, TypeVar++from pydantic import BaseModel, Field, SecretStr, ValidationError++from ares.core.errors import ModuleValidationError+from ares.modules.params import ModuleParams, SecretParam, param++P = TypeVar("P", bound=BaseModel)+++def validate_params(+ model_cls: type[P],+ data: dict[str, Any] | BaseModel | None,+ module_id: str = "",+) -> P:+ """Validate a parameter dictionary or model against a Pydantic model.++ Raises ModuleValidationError with structured field-level errors on failure.+ """+ if data is None:+ data = {}+ if isinstance(data, model_cls):+ return data+ if isinstance(data, BaseModel):+ data = data.model_dump()++ try:+ return model_cls.model_validate(data)+ except ValidationError as exc:+ first_error = exc.errors()[0] if exc.errors() else {}+ loc = ".".join(str(x) for x in first_error.get("loc", []))+ msg = first_error.get("msg", "Invalid parameters")+ detail = f"Parameter validation failed for {loc}: {msg}" if loc else f"Parameter validation failed: {msg}"+ raise ModuleValidationError(+ detail,+ module_id=module_id,+ field=loc or "params",+ ) from exc+++__all__ = [+ "ModuleParams",+ "param",+ "SecretParam",+ "SecretStr",+ "Field",+ "BaseModel",+ "validate_params",+]diff --git a/ares/sdk/testing/__init__.py b/ares/sdk/testing/__init__.pynew file mode 100644index 0000000..147a42f--- /dev/null+++ b/ares/sdk/testing/__init__.py@@ -0,0 +1,13 @@+"""Testing and simulation kit for ARES modules.++Exported symbols:+ from ares.sdk.testing import ModuleTestHarness, SimulationResult+"""+from __future__ import annotations++from ares.sdk.testing.harness import ModuleTestHarness, SimulationResult++__all__ = [+ "ModuleTestHarness",+ "SimulationResult",+]diff --git a/ares/sdk/testing/harness.py b/ares/sdk/testing/harness.pynew file mode 100644index 0000000..d734b5c--- /dev/null+++ b/ares/sdk/testing/harness.py@@ -0,0 +1,250 @@+"""Isolated testing harness and simulation runner for ARES modules.++Enables community module authors and core developers to test attack modules+in complete isolation with simulated scope guards, synthetic vaults, and+fluent assertion matchers.+"""+from __future__ import annotations++from dataclasses import dataclass, field+from typing import Any, Generic, TypeVar++from pydantic import BaseModel++from ares.core.campaign import Campaign, Finding, NoiseProfile, ScopeEntry, Severity+from ares.core.config import AresSettings+from ares.core.context import ExecutionContext+from ares.core.errors import AresError, ModuleValidationError+from ares.core.noise import NoiseController+from ares.credential.vault import Credential, CredentialVault+from ares.modules.base import BaseModule, ModuleResult++M = TypeVar("M", bound=BaseModule)+++@dataclass+class SimulationResult:+ """Result envelope from a simulated module execution with fluent test assertions."""++ status: str+ module_id: str+ findings: list[Finding] = field(default_factory=list)+ raw: dict[str, Any] = field(default_factory=dict)+ new_credentials: list[Any] = field(default_factory=list)+ discovered_hosts: list[Any] = field(default_factory=list)+ artifacts: dict[str, Any] = field(default_factory=dict)+ error: str | None = None+ context: ExecutionContext | None = None++ @property+ def success(self) -> bool:+ """Return True if execution finished successfully without unhandled errors."""+ return self.status in ("success", "done", "dry_run", "partial") and not self.error++ def assert_success(self) -> SimulationResult:+ """Assert that the simulation completed successfully."""+ assert self.success, f"Expected simulation success, got status={self.status!r}, error={self.error!r}"+ return self++ def assert_failed(self, error_contains: str | None = None) -> SimulationResult:+ """Assert that the simulation failed or reported an error."""+ assert not self.success or bool(self.error), f"Expected simulation failure, got success={self.status!r}"+ if error_contains:+ assert error_contains.lower() in str(self.error or "").lower(), (+ f"Expected error containing {error_contains!r}, got {self.error!r}"+ )+ return self++ def assert_no_errors(self) -> SimulationResult:+ """Assert that no error string is recorded."""+ assert not self.error, f"Unexpected error in simulation result: {self.error}"+ return self++ def assert_finding(+ self,+ severity: Severity | str | None = None,+ mitre: str | None = None,+ title_contains: str | None = None,+ ) -> Finding:+ """Assert that at least one emitted finding matches the given criteria.++ Returns the matching finding for further inspection.+ """+ assert self.findings, f"No findings were emitted by module {self.module_id}"++ expected_sev = (+ severity.value if isinstance(severity, Severity)+ else str(severity).lower() if severity is not None+ else None+ )++ for finding in self.findings:+ matches = True+ if expected_sev is not None:+ actual_sev = getattr(finding.severity, "value", str(finding.severity)).lower()+ if actual_sev != expected_sev:+ matches = False+ if mitre is not None:+ technique = getattr(finding, "mitre_technique", None) or ""+ if mitre.lower() not in technique.lower():+ matches = False+ if title_contains is not None:+ title = getattr(finding, "title", "") or ""+ if title_contains.lower() not in title.lower():+ matches = False++ if matches:+ return finding++ criteria = []+ if expected_sev:+ criteria.append(f"severity={expected_sev}")+ if mitre:+ criteria.append(f"mitre={mitre}")+ if title_contains:+ criteria.append(f"title_contains={title_contains}")++ raise AssertionError(+ f"No finding matched criteria ({', '.join(criteria)}). "+ f"Emitted findings: {[f.title for f in self.findings]}"+ )++ def assert_credential_found(self, username: str | None = None) -> Any:+ """Assert that at least one credential was discovered."""+ assert self.new_credentials, f"No new credentials discovered by module {self.module_id}"+ if username:+ matched = any(+ username.lower() in str(getattr(c, "username", "")).lower()+ for c in self.new_credentials+ )+ assert matched, f"Credential for username {username!r} not found in {self.new_credentials}"+ return self.new_credentials[0]+++class ModuleTestHarness(Generic[M]):+ """Isolated execution harness for testing and simulating ARES modules.++ Usage:+ harness = ModuleTestHarness(MyModule)+ result = await harness.simulate(params={"target": "10.0.0.1"})+ result.assert_success()+ result.assert_finding(severity=Severity.HIGH)+ """++ def __init__(+ self,+ module_cls: type[M],+ scope_cidrs: list[str] | None = None,+ default_target: str = "10.0.0.1",+ default_domain: str = "CORP.LOCAL",+ ) -> None:+ self.module_cls = module_cls+ self.scope_cidrs = scope_cidrs or ["0.0.0.0/0"]+ self.default_target = default_target+ self.default_domain = default_domain+ self.settings = AresSettings()+ self.scope = [ScopeEntry(cidr=s) for s in self.scope_cidrs]+ self.campaign = Campaign(+ name="test-harness-campaign",+ client="test",+ scope=self.scope,+ noise_profile=NoiseProfile.NORMAL,+ operator="test_operator",+ )+ self.noise = NoiseController(self.campaign)+ self.vault = CredentialVault(encryption_key="ares-test-harness-master-key-32ch")++ def make_context(+ self,+ target: str | None = None,+ domain: str | None = None,+ params: dict[str, Any] | BaseModel | None = None,+ dry_run: bool = True,+ credentials: list[Any] | None = None,+ **kwargs: Any,+ ) -> ExecutionContext:+ """Build a mock ExecutionContext configured for this module."""+ final_target = target or self.default_target+ final_domain = domain or self.default_domain++ if isinstance(params, BaseModel):+ combined_params: Any = params+ else:+ combined_params = {**(params or {}), **kwargs}++ ctx = ExecutionContext.build(+ campaign=self.campaign,+ target=final_target,+ module_id=getattr(self.module_cls, "MODULE_ID", "test.module"),+ domain=final_domain,+ params=combined_params,+ credentials=credentials or [],+ vault=self.vault,+ settings=self.settings,+ noise=self.noise,+ dry_run=dry_run,+ )+ return ctx++ async def simulate(+ self,+ params: dict[str, Any] | BaseModel | None = None,+ target: str | None = None,+ domain: str | None = None,+ dry_run: bool = True,+ credentials: list[Any] | None = None,+ **kwargs: Any,+ ) -> SimulationResult:+ """Execute validate() and execute() in the isolated test harness."""+ ctx = self.make_context(+ target=target,+ domain=domain,+ params=params,+ dry_run=dry_run,+ credentials=credentials,+ **kwargs,+ )++ module = self.module_cls(+ settings=self.settings,+ campaign=self.campaign,+ noise=self.noise,+ )++ try:+ # 1. Validate+ await module.validate(ctx)++ # 2. Execute+ res = await module.execute(ctx)++ all_findings = list(res.findings or [])+ for f in ctx.findings:+ if f not in all_findings:+ all_findings.append(f)++ return SimulationResult(+ status=res.status,+ module_id=module.MODULE_ID,+ findings=all_findings,+ raw=res.raw,+ new_credentials=list(res.new_credentials),+ discovered_hosts=list(res.discovered_hosts),+ artifacts=dict(res.artifacts),+ error=res.error or None,+ context=ctx,+ )+ except (ModuleValidationError, AresError, Exception) as exc:+ return SimulationResult(+ status="failed",+ module_id=getattr(module, "MODULE_ID", "unknown"),+ findings=ctx.findings,+ error=str(exc),+ context=ctx,+ )+++__all__ = [+ "ModuleTestHarness",+ "SimulationResult",+]diff --git a/docs/MODULE_GUIDE.md b/docs/MODULE_GUIDE.mdindex 4bb393d..0897045 100644--- a/docs/MODULE_GUIDE.md+++ b/docs/MODULE_GUIDE.md@@ -28,35 +28,40 @@ Every ARES module is a Python class that inherits from `BaseModule`:```pythonfrom ares.sdk import (BaseModule, ExecutionContext, ModuleResult,- OpsecLevel, Severity, module_metadata,+ ModuleParams, param, SecretParam,+ OpsecLevel, Severity, ares_module,)-@module_metadata(- module_id = "ad.my_attack", # unique dot-notation ID- name = "My Attack",- category = "ad", # ad | linux | cloud | lateral | exfil | credential- description = "Does something",- author = "[email protected]",- opsec = OpsecLevel.LOW, # silent | low | medium | high_noise- requires = ["domain_creds"], # capabilities this module needs- outputs = ["credential_list"], # capabilities this module produces- mitre = ["T1558.003"], # MITRE ATT&CK technique IDs-)-class MyAttackModule(BaseModule):-- async def validate(self, ctx: ExecutionContext) -> None:- ctx.require("target", "domain") # raises if missing-- async def execute(self, ctx: ExecutionContext) -> ModuleResult:+# 1. Parameter schema with strict validation & auto UI forms+class MyAttackParams(ModuleParams):+ target: str = param("Target domain controller or IP", min_length=1)+ domain: str = param("AD domain name, e.g. CORP.LOCAL", min_length=1)+ username: str = param("Domain username", required=False)+ password: SecretParam = param("User password", secret=True, required=False)++# 2. Modern generic BaseModule[Params, Result]+class MyAttackModule(BaseModule[MyAttackParams, ModuleResult]):+ MODULE_ID = "ad.my_attack" # unique dot-notation ID+ MODULE_NAME = "My Attack"+ MODULE_CATEGORY = "ad" # ad | linux | cloud | lateral | exfil | credential+ MODULE_DESCRIPTION = "Find something interesting"+ MODULE_AUTHOR = "[email protected]"+ PARAMS_MODEL = MyAttackParams+ OPSEC_LEVEL = OpsecLevel.LOW # silent | low | medium | high_noise+ REQUIRES = ["domain_creds"] # capabilities this module needs+ OUTPUTS = ["credential_list"] # capabilities this module produces+ MITRE_TECHNIQUES = ["T1558.003"] # MITRE ATT&CK technique IDs++ async def execute(self, ctx: ExecutionContext[MyAttackParams]) -> ModuleResult:if ctx.dry_run:- return ModuleResult(status="dry_run", module_id=self.MODULE_ID)+ return ModuleResult.ok("Dry-run check validated: target in scope.", module_id=self.MODULE_ID)- target = ctx.params["target"]+ # Full type safety on parameters+ target = ctx.params.targetawait self.before_request(target, "ldap") # scope + noise check- # ... attack work ...-- self.finding(+ # Emit findings using fluent context helper+ ctx.emit_finding(title = "Kerberoastable account found",description = "Service account has SPN set",severity = Severity.HIGH,@@ -68,16 +73,10 @@ class MyAttackModule(BaseModule):return ModuleResult(status = "success",- findings = self._findings,+ findings = ctx.findings,module_id = self.MODULE_ID,raw = {"spns": [...]},)-- async def run(self, **kwargs):- """Required: legacy interface called by engine."""- ctx = ExecutionContext.for_test(**kwargs)- r = await self.execute(ctx)- return r.findings, r.raw```---@@ -146,24 +145,32 @@ Severity.INFO # InformationalThe scaffold generates a test file with two baseline tests. Add more:```python+from ares.sdk import ModuleTestHarness, Severity+import pytest+@pytest.mark.asyncio-async def test_finds_kerberoastable_user(module):- """When SPN accounts exist, module should find them."""- with patch("impacket.examples.GetUserSPNs.GetUserSPNs") as mock:- mock.return_value.run.return_value = None- # mock file output...- findings, raw = await module.run(- dc="10.0.0.1", domain="CORP",- username="user", password="pass",- )- assert len(findings) > 0- assert findings[0].severity.value == "high"+async def test_finds_kerberoastable_user():+ """Simulate attack module in hermetic test harness."""+ harness = ModuleTestHarness(MyAttackModule)+ result = await harness.simulate(+ params={"target": "10.0.0.1", "domain": "CORP.LOCAL"},+ dry_run=False,+ )+ result.assert_success()+ result.assert_no_errors()+ finding = result.assert_finding(severity=Severity.HIGH, mitre="T1558.003")+ assert "Kerberoastable" in finding.title@pytest.mark.asyncio-async def test_no_spns_no_finding(module):- """When no SPN accounts, module should return empty findings."""- # ...- assert findings == []+async def test_dry_run_simulation():+ """Verify dry-run returns success without side-effects."""+ harness = ModuleTestHarness(MyAttackModule)+ result = await harness.simulate(+ params={"target": "10.0.0.1", "domain": "CORP.LOCAL"},+ dry_run=True,+ )+ result.assert_success()+ result.assert_no_errors()```Run tests:diff --git a/docs/README.md b/docs/README.mdindex 95e80df..356d9b2 100644--- a/docs/README.md+++ b/docs/README.md@@ -23,8 +23,8 @@ The documentation is organized into five functional pillars:| --- | --- | --- || [modules.md](modules.md) | Comprehensive catalog of all 28 attack modules and 81 capability definitions. | Operators, Red Team || [MODULE_GUIDE.md](MODULE_GUIDE.md) | Operator quickstart for executing and chaining modules across target hosts. | Operators |-| [module-development.md](module-development.md) | Step-by-step developer guide for writing, testing, and signing new attack modules. | Module Developers |-| [module_sdk.md](module_sdk.md) | Complete specification for `BaseModule`, `ExecutionContext`, `ModuleResult`, and decorators. | Developers |+| [module-development.md](module-development.md) | Step-by-step developer guide for writing, testing with `ModuleTestHarness`, and signing attack modules. | Module Developers |+| [module_sdk.md](module_sdk.md) | Modern v2 SDK specification (`BaseModule[P, R]`, Pydantic v2 params, testing harness, and `AresClient`). | Developers, Integrators |### API, Security and Database| Document | Description | Target Audience |diff --git a/docs/assets/screenshots/dashboard-overview-empty.png b/docs/assets/screenshots/dashboard-overview-empty.pngnew file mode 100644index 0000000..2147da9Binary files /dev/null and b/docs/assets/screenshots/dashboard-overview-empty.png differdiff --git a/docs/dashboard-guide.md b/docs/dashboard-guide.mdindex 63a4b97..2d6f8dc 100644--- a/docs/dashboard-guide.md+++ b/docs/dashboard-guide.md@@ -69,7 +69,8 @@ keys, bearer tokens, or sensitive report URLs.| View | File | Use || --- | --- | --- |-| Overview | `docs/assets/screenshots/dashboard-overview.png` | Health, telemetry cards, and campaign summary. |+| Overview (Standby / Zero-State) | `docs/assets/screenshots/dashboard-overview-empty.png` | Clean onboarding hero, platform readiness strip, and initialization quick actions. |+| Overview (Active Telemetry) | `docs/assets/screenshots/dashboard-overview.png` | Health, telemetry cards, confirmed findings, and campaign summary. || Campaigns | `docs/assets/screenshots/dashboard-campaigns.png` | Campaign creation, target/scope input, and management actions. || Modules | `docs/assets/screenshots/dashboard-modules-catalog.png` | Module catalog filters, OPSEC labels, campaign selection, and parameter forms. || Reports | `docs/assets/screenshots/dashboard-reports.png` | Campaign report generation and artifact list. |@@ -193,7 +194,13 @@ Current page tabs:### Overview-+++*Tactical Zero-State Overview — Clean onboarding hero with instant readiness strip and initialization actions when running zero active campaigns.*++++*Active Telemetry Overview — Real-time telemetry, confirmed findings by severity, queue metrics, and campaign status.*Purpose: quick system status.diff --git a/docs/module-development.md b/docs/module-development.mdindex 4c11f73..331a271 100644--- a/docs/module-development.md+++ b/docs/module-development.md@@ -36,21 +36,38 @@ not sufficient to make a plugin eligible for the future gateway. Phase 5C.1made no schema change. The later revision `0010` is additive test-onlypersistence and does not make a module eligible or change any live ingress.-The examples below describe the existing SDK surface. They are not proof that-all current ingresses apply the same policy, that dry-run is universally-side-effect-free, or that current outcomes and retries are authoritative.+The examples below describe the modern v2 SDK surface with full backward+compatibility for existing v1 modules. They are not proof that all current+ingresses apply the same policy, that dry-run is universally side-effect-free,+or that current outcomes and retries are authoritative.----## Quick Start+## Quick Start (v2 Modern Standard)++The modern ARES SDK (`ares.sdk`) introduces type-safe parameter schemas with Pydantic v2, generic `BaseModule[P, R]`, fluent execution helpers, and isolated simulation testing.++### Option A: Modern Class-Based Module (Recommended)```python# mymodule/mssql_enum.py-from ares.sdk import BaseModule, ExecutionContext, Finding, ModuleResult, OpsecLevel, Severity+from ares.sdk import (+ BaseModule, ExecutionContext, ModuleResult,+ ModuleParams, param, SecretParam,+ OpsecLevel, Severity,+)from ares.core.errors import NetworkError, ConnectionRefused-class MssqlEnumModule(BaseModule):+# 1. Strictly validated parameter schema (Pydantic v2)+class MssqlEnumParams(ModuleParams):+ target: str = param("Target IP address or hostname", min_length=1)+ port: int = param("MSSQL service port", default=1433, ge=1, le=65535)+ sa_password: SecretParam = param("Known or candidate SA password", secret=True, required=False)+++# 2. Inherit from generic BaseModule[Params, Result]+class MssqlEnumModule(BaseModule[MssqlEnumParams, ModuleResult]):"""Enumerate MSSQL instances and check for weak authentication."""# ── Required metadata ───────────────────────────────────────────────@@ -58,6 +75,7 @@ class MssqlEnumModule(BaseModule):MODULE_NAME = "MSSQL Enumeration"MODULE_CATEGORY = "db"MODULE_DESCRIPTION = "Enumerate MSSQL instances, check SA password, xp_cmdshell"+ PARAMS_MODEL = MssqlEnumParams# ── Optional metadata ───────────────────────────────────────────────OPSEC_LEVEL = OpsecLevel.MEDIUM@@ -68,33 +86,27 @@ class MssqlEnumModule(BaseModule):# ── ARES SDK contract ─────────────────────────────────────────────- async def validate(self, ctx: ExecutionContext) -> None:- """Check that context has everything we need before executing."""- ctx.require("target") # target IP/hostname- if not ctx.params.get("port"):- ctx.params["port"] = 1433 # default MSSQL port (set if missing)-- async def execute(self, ctx: ExecutionContext) -> ModuleResult:+ async def execute(self, ctx: ExecutionContext[MssqlEnumParams]) -> ModuleResult:"""Run the enumeration. Network calls go here."""- target = ctx.target- port = ctx.params.get("port", 1433)- result = ModuleResult(module_id=self.MODULE_ID, execution_id=ctx.execution_id)+ # ctx.params provides full static typing and runtime validation!+ target = ctx.params.target+ port = ctx.params.portif ctx.dry_run:- # Simulation mode — return dummy data- result.status = "success"- result.raw = {"simulated": True}- return result+ # Simulation mode — return dry-run result+ return ModuleResult.ok(+ f"Dry-run validated: {target}:{port} inside approved scope.",+ module_id=self.MODULE_ID,+ )# Existing SDK hook; Phase 5C.2 defines the canonical gateway order.await self.before_request(target, action="mssql_enum")try:- # Real implementation: connect to MSSQL and enumerate- # import aioodbc / pymssql / etc.instances = await self._enumerate(target, port, ctx)for inst in instances:- f = self.finding(+ # Emit findings using fluent context helper+ ctx.emit_finding(title = f"MSSQL instance on {target}:{port}",description = f"MSSQL {inst['version']} with {inst['auth_method']} auth",severity = Severity.MEDIUM,@@ -102,15 +114,19 @@ class MssqlEnumModule(BaseModule):host = target,evidence = inst,)- result.findings.append(f)- result.status = "success"- result.artifacts = {"instances": instances}++ ctx.store_artifact("instances", instances)+ return ModuleResult(+ status="success",+ findings=ctx.findings,+ artifacts=ctx.artifacts,+ module_id=self.MODULE_ID,+ )except ConnectionRefusedError:raise ConnectionRefused(f"MSSQL port {port} not open on {target}",module_id=self.MODULE_ID, target=target, port=port,)- return resultdef report(self, result: ModuleResult) -> dict:"""Return module-specific report section."""@@ -124,8 +140,31 @@ class MssqlEnumModule(BaseModule):# ── Private helpers ─────────────────────────────────────────────────async def _enumerate(self, target: str, port: int, ctx: ExecutionContext) -> list[dict]:- # Stub — real implementation uses pymssql or aioodbc- return []+ # Stub — real implementation connects to MSSQL service+ return [{"version": "MSSQL 2019", "auth_method": "SQL_AND_WINDOWS"}]+```++### Option B: Declarative Functional Module (`@ares_module`)++For single-action modules, reconnaissance scripts, or quick extensions:++```python+from ares.sdk import ares_module, ExecutionContext, ModuleResult, Severity++@ares_module(+ id="db.mssql_quick_check",+ name="MSSQL Quick Check",+ category="db",+ params_model=MssqlEnumParams,+ mitre="T1505.001",+)+async def mssql_quick_check(ctx: ExecutionContext[MssqlEnumParams]) -> ModuleResult:+ ctx.emit_finding(+ title=f"MSSQL Port Active on {ctx.params.target}:{ctx.params.port}",+ severity=Severity.INFO,+ mitre_technique="T1505.001",+ )+ return ModuleResult(status="success", findings=ctx.findings, module_id="db.mssql_quick_check")```---@@ -137,14 +176,15 @@ class MssqlEnumModule(BaseModule):| Attribute | Type | Example | Description ||-----------|------|---------|-------------|| `MODULE_ID` | `str` | `"ad.kerberoast"` | Unique dotted ID. Must contain exactly one dot. |-| `MODULE_NAME` | `str` | `"Kerberoasting"` | Human-readable name shown in CLI. |+| `MODULE_NAME` | `str` | `"Kerberoasting"` | Human-readable name shown in CLI and UI. || `MODULE_CATEGORY` | `str` | `"ad"` | Category prefix (must match MODULE_ID prefix). |-| `MODULE_DESCRIPTION` | `str` | `"Request Kerberos TGS tickets..."` | One-liner for `ares module list`. |+| `MODULE_DESCRIPTION` | `str` | `"Request Kerberos TGS tickets..."` | One-liner for `ares module list` and catalog cards. |### Optional Attributes| Attribute | Type | Default | Description ||-----------|------|---------|-------------|+| `PARAMS_MODEL` | `type[ModuleParams]` | `None` | Pydantic v2 model for parameter validation and UI form generation || `OPSEC_LEVEL` | `OpsecLevel` | `LOW` | `SILENT \| LOW \| MEDIUM \| HIGH_NOISE` || `REQUIRES` | `list[str]` | `[]` | Capabilities needed (outputs of upstream modules) || `OUTPUTS` | `list[str]` | `[]` | What this module produces (feeds downstream modules) |@@ -165,18 +205,16 @@ class MssqlEnumModule(BaseModule):## The ARES SDK Contract-### `validate(ctx)` — Called before execution+### Parameter Validation++When `PARAMS_MODEL` is declared on your module, `BaseModule.validate(ctx)` automatically validates types, defaults, required parameters, and string constraints. You only need to override `validate()` if you have additional cross-field or dynamic business logic:```pythonasync def validate(self, ctx: ExecutionContext) -> None:- # Check required context fields- ctx.require("target", "domain")-- # Check module-specific params- if not ctx.params.get("wordlist"):- ctx.params["wordlist"] = "/usr/share/wordlists/rockyou.txt"+ # 1. Base auto-validates against PARAMS_MODEL+ await super().validate(ctx)- # Custom validation+ # 2. Add any custom operational guardrails:if ctx.opsec_profile == "stealth" and self.OPSEC_LEVEL == OpsecLevel.HIGH_NOISE:from ares.core.errors import ModuleValidationErrorraise ModuleValidationError(@@ -188,7 +226,7 @@ async def validate(self, ctx: ExecutionContext) -> None:### `execute(ctx)` — The attack logic```python-async def execute(self, ctx: ExecutionContext) -> ModuleResult:+async def execute(self, ctx: ExecutionContext[MssqlEnumParams]) -> ModuleResult:result = ModuleResult(module_id=self.MODULE_ID, execution_id=ctx.execution_id)# Don't make real calls in dry_run / simulation mode@@ -197,24 +235,30 @@ async def execute(self, ctx: ExecutionContext) -> ModuleResult:return result# Existing SDK hook; Phase 5C.2 defines the canonical gateway order.- await self.before_request(ctx.target)+ await self.before_request(ctx.params.target)try:- # Your attack/enumeration logic here- data = await self._do_attack(ctx.target, ctx.best_credential())+ # Attack/enumeration logic+ data = await self._do_attack(ctx.params.target, ctx.best_credential())- # Create findings+ # Create findings using fluent context helperfor item in data:- f = self.finding(title=..., description=..., severity=Severity.HIGH)- result.findings.append(f)-- # Report new credentials discovered- result.new_credentials = [{"username": ..., "hash": ...}]+ ctx.emit_finding(+ title=f"Vulnerability on {ctx.params.target}",+ description=item["summary"],+ severity=Severity.HIGH,+ mitre_technique="T1505.001",+ evidence=item,+ )- # Report new hosts found (triggers service_intel automatically)- result.discovered_hosts = ["10.0.0.5", "10.0.0.6"]+ # Store artifacts and discovered credentials+ ctx.store_artifact("raw_data", data)+ ctx.record_credential(username="sa", secret="P@ssw0rd123!", cred_type="db_password")result.status = "success"+ result.findings = ctx.findings+ result.artifacts = ctx.artifacts+ result.new_credentials = ctx.vault.export_new() if hasattr(ctx.vault, "export_new") else []except AuthenticationFailed as e:# Engine will try next credential in vault@@ -242,13 +286,24 @@ def report(self, result: ModuleResult) -> dict:----## ExecutionContext Fields+## ExecutionContext Reference++The `ExecutionContext` object represents the execution runtime environment for a module run:```python+# Typed Parameters+ctx.params # P (when ExecutionContext[P] is used) or dict+ctx.typed_params(Model) # Parses and returns an instance of Model++# Fluent Helpers (v2 Standard)+ctx.emit_finding(title, severity, ...) # Appends to ctx.findings and returns Finding+ctx.store_artifact(key, value) # Stores to ctx.artifacts+ctx.record_credential(username, secret, ..) # Stores to vault and tracks new credential++# Context Metadatactx.target # str: IP or hostname-ctx.domain # str: AD domain (CORP.LOCAL)+ctx.domain # str: AD domain (e.g. CORP.LOCAL)ctx.port # int: target port if relevant-ctx.params # dict: module-specific params (from CLI/API)ctx.credentials # list[Credential]: sorted by score (best first)ctx.best_credential() # Credential | None: highest-scored credentialctx.session # OperatorSession: shared campaign state@@ -272,7 +327,7 @@ Always raise ARES errors (not generic exceptions):```pythonfrom ares.core.errors import (- ModuleValidationError, # bad config / bad context+ ModuleValidationError, # bad config / bad context / invalid parameterConnectionRefused, # TCP refusedConnectionTimeout, # TCP timeoutHostUnreachable, # no route@@ -282,67 +337,92 @@ from ares.core.errors import (ScopeError, # out of scopeSandboxError, # module crashed)--# Intended legacy engine behavior (not made canonical by Phase 5C.1):-# ModuleValidationError → abort module, don't retry-# ConnectionRefused → try fallback protocol/port-# AuthenticationFailed → try next credential-# AccountLocked → STOP immediately, never retry this account-# ScopeError → abort campaign operation```----## ModuleResult Fields--```python-result = ModuleResult(- status = "success", # "success"|"failure"|"partial"|"skipped"- findings = [f1, f2], # list[Finding]- artifacts = {"key": data}, # raw artifacts for evidence- new_credentials = [{"username": "svc", "hash": "aad3..."}],- discovered_hosts = ["10.0.0.5"], # engine auto-scans these- raw = {"debug": ...}, # unstructured output- error = "", # error message if not success-)-```+## Testing Your Module----+### 1. Isolated Simulation with `ModuleTestHarness` (Recommended)-## Testing Your Module+The v2 SDK includes `ModuleTestHarness`, enabling zero-mock unit testing with simulated scope guards, credential vaults, and fluent assertions:```pythonimport pytest-from ares.sdk import ExecutionContext-from mymodule.mssql_enum import MssqlEnumModule+from ares.sdk import ModuleTestHarness, Severity+from mymodule.mssql_enum import MssqlEnumModule, MssqlEnumParams@pytest.mark.asyncio-async def test_mssql_enum_validate():- ctx = ExecutionContext.for_test(target="10.0.0.10")- module = MssqlEnumModule.__new__(MssqlEnumModule)- await module.validate(ctx) # should not raise+async def test_mssql_enum_simulation():+ # Instantiate the harness+ harness = ModuleTestHarness(MssqlEnumModule)++ # Run the module hermetically+ result = await harness.simulate(+ target="10.0.0.10",+ params={"target": "10.0.0.10", "port": 1433},+ dry_run=True,+ )++ # Fluent assertions+ result.assert_success()+ result.assert_no_errors()+ assert result.duration_ms >= 0@pytest.mark.asyncio-async def test_mssql_enum_dry_run():- from ares.core.campaign import Campaign, NoiseProfile, ScopeEntry- from ares.core.config import AresSettings- from ares.core.noise import NoiseController-- campaign = Campaign(name="test", scope=[ScopeEntry(cidr="10.0.0.0/8")],- noise_profile=NoiseProfile.NORMAL)- module = MssqlEnumModule(- settings=AresSettings(), campaign=campaign,- noise=NoiseController(campaign),+async def test_mssql_enum_finding_emission():+ harness = ModuleTestHarness(MssqlEnumModule)+ result = await harness.simulate(+ target="10.0.0.10",+ params={"target": "10.0.0.10", "port": 1433},+ dry_run=False,)- ctx = ExecutionContext.for_test(target="10.0.0.10", dry_run=True)- result = await module.execute(ctx)- assert result.status == "success"- assert result.module_id == "db.mssql_enum"--def test_module_metadata():- from ares.sdk import validate_module_class- errors = validate_module_class(MssqlEnumModule)- assert errors == [], f"Module metadata errors: {errors}"+ result.assert_success()+ finding = result.assert_finding(severity=Severity.MEDIUM, mitre="T1505.001")+ assert "MSSQL instance" in finding.title+```++### 2. Legacy `ExecutionContext.for_test()` (v1 Standard)++Legacy test cases using direct `ExecutionContext.for_test()` continue to function seamlessly:++```python+async def test_legacy_style():+ ctx = ExecutionContext.for_test(target="10.0.0.10", params={"port": 1433})+ module = MssqlEnumModule.__new__(MssqlEnumModule)+ await module.validate(ctx)+```++---++## Programmatic Automation (`AresClient`)++Automate engagements, module runs, and telemetry streams from Python scripts or CI/CD pipelines:++```python+from ares.sdk import AresClient++async def main():+ async with AresClient(base_url="http://127.0.0.1:8000", api_key="ares_key_...") as ares:+ # Create campaign with approved scope+ campaign = await ares.campaigns.create(+ name="Op-Nightshade",+ scope=["10.0.0.0/24"],+ )++ # Dispatch module asynchronously+ job = await ares.modules.run(+ module_id="db.mssql_enum",+ target="10.0.0.15",+ campaign_id=campaign["id"],+ params={"port": 1433},+ )+ print(f"Execution dispatched: {job['execution_id']}")++ # Retrieve campaign findings+ findings = await ares.campaigns.findings(campaign["id"])+ print(f"Captured {len(findings)} findings")```---@@ -355,9 +435,9 @@ def test_module_metadata():{"module_id": "db.mssql_enum","name": "MSSQL Enumeration",- "version": "1.0.0",+ "version": "2.0.0","author": "Your Name",- "description": "Enumerate MSSQL instances",+ "description": "Enumerate MSSQL instances and weak authentication","requires": ["pymssql"],"ares_min": "6.0.0","signature": "sha256:abc123..."@@ -367,19 +447,18 @@ def test_module_metadata():### Install```bash-ares module install db/[email protected]+ares module install db/[email protected]# or from local path:ares module install ./mymodule/```-### Guidelines for accepted modules--- ✅ Must have all 4 required metadata attributes-- ✅ Must implement `validate()` — check context completeness-- ✅ Must respect `ctx.dry_run` — no network calls when True-- ✅ Must raise ARES errors, not generic exceptions-- ✅ Must have unit tests covering validate + execute + dry_run-- ✅ Must have MITRE technique mapping-- ❌ Must NOT access filesystem outside campaign working directory-- ❌ Must NOT make outbound calls to non-target hosts without operator config-- ❌ Must NOT store credentials in plaintext (use vault)+### Quality & Safety Guidelines++- Must define all required metadata (`MODULE_ID`, `MODULE_NAME`, `MODULE_CATEGORY`, `MODULE_DESCRIPTION`).+- Must declare `PARAMS_MODEL` for robust type validation and clean UI parameter rendering.+- Must respect `ctx.dry_run` — zero unauthorized side-effects or network traffic when True.+- Must call `await self.before_request(target)` before network interactions.+- Must raise standard ARES exceptions rather than raw socket or OS exceptions.+- Must include unit tests using `ModuleTestHarness`.+- Must NOT access the filesystem outside the campaign workspace.+- Must NOT store credentials in plaintext (use `ctx.vault` or `ctx.record_credential`).diff --git a/docs/module_sdk.md b/docs/module_sdk.mdindex ba9a9af..d3a8d67 100644--- a/docs/module_sdk.md+++ b/docs/module_sdk.md@@ -1,21 +1,110 @@-# ARES Module SDK+# ARES Module & Developer SDK-**Version:** 1.0.0 | **Status:** authoring/preview only in C-LIVE-v1+**Version:** 2.0.0 (Modern Type-Safe Standard) | **Backward Compatible with v1.0.0**-> Complete guide for ARES module authors.-> Everything needed to build, test, sign, and publish an ARES module.+> Complete guide for ARES module authors and automation engineers.+> Everything needed to build type-safe modules, simulate attacks in isolation, and automate ARES via Python.-`ares.sdk` is the preferred public import path for new modules. The older-`ares.modules.sdk` path remains available for existing modules.+`ares.sdk` is the canonical public import path. It provides:+1. **Type-Safe Module Authoring**: Generic `BaseModule[P, R]`, Pydantic v2 `ModuleParams`, and declarative `@ares_module`.+2. **Fluent Execution Context**: `ctx.emit_finding(...)`, `ctx.store_artifact(...)`, `ctx.record_credential(...)`.+3. **Isolated Testing & Simulation**: `ModuleTestHarness` with fluent assertion matchers (`result.assert_success()`, `result.assert_finding()`).+4. **Programmatic API Client**: `AresClient` for asynchronous REST and WebSocket automation.-> C-LIVE-v1 keeps all production descriptors disabled/ineligible. SDK authoring-> and metadata validation remain available, but `ModuleTestHelper.run` and-> `run_full` are preview-only and never invoke module `validate`, `run`, or-> `execute` methods.+---++## Modern Quick Start (v2 Standard)++```python+# my_module.py+from ares.sdk import (+ BaseModule, ExecutionContext, ModuleResult,+ ModuleParams, param, SecretParam,+ OpsecLevel, Severity, ares_module,+)++# 1. Declare validated parameter schema with Pydantic v2+class AttackParams(ModuleParams):+ dc: str = param(description="Target DC IP or FQDN", min_length=3)+ domain: str = param(description="AD domain name", min_length=3)+ password: SecretParam = param(description="Password", secret=True, required=False)+ port: int = param(description="Target port", default=389, ge=1, le=65535)++# 2. Modern Class-Based Module+class MyModule(BaseModule[AttackParams, ModuleResult]):+ MODULE_ID = "myorg.my_attack"+ MODULE_NAME = "My Attack Module"+ MODULE_CATEGORY = "ad"+ PARAMS_MODEL = AttackParams+ OPSEC_LEVEL = OpsecLevel.LOW+ MITRE_TECHNIQUES = ["T1087.002"]++ async def execute(self, ctx: ExecutionContext[AttackParams]) -> ModuleResult:+ # ctx.params has 100% type safety and autocomplete!+ target_dc = ctx.params.dc++ # Fluent finding emission+ ctx.emit_finding(+ title=f"Discovered Service on {target_dc}",+ severity=Severity.HIGH,+ mitre_technique="T1087.002",+ )+ return ModuleResult(status="success", module_id=self.MODULE_ID)++# 3. Or Declarative Functional Module+@ares_module(+ id="myorg.quick_probe",+ name="Quick Probe",+ category="recon",+ params_model=AttackParams,+ mitre="T1046",+)+async def quick_probe(ctx: ExecutionContext[AttackParams]) -> ModuleResult:+ ctx.emit_finding("Port Active", Severity.INFO, mitre_technique="T1046")+ return ModuleResult(status="success", module_id="myorg.quick_probe")+```++---++## Isolated Testing & Simulation (`ares.sdk.testing`)++Test modules locally in complete isolation without starting the engine or databases:++```python+from ares.sdk import ModuleTestHarness, Severity++async def test_my_module():+ harness = ModuleTestHarness(MyModule)+ result = await harness.simulate(+ params={"dc": "10.0.0.1", "domain": "CORP.LOCAL"},+ dry_run=True,+ )+ result.assert_success()+ result.assert_no_errors()+ finding = result.assert_finding(severity=Severity.HIGH, mitre="T1087.002")+ assert "Discovered Service" in finding.title+```++---++## Programmatic Automation (`AresClient`)++Control and automate ARES from external Python scripts, SOAR playbooks, or CI/CD pipelines:++```python+from ares.sdk import AresClient++async with AresClient(base_url="http://127.0.0.1:8000", api_key="ares_pat_...") as client:+ campaign = await client.campaigns.create(name="Op-Titan", scope=["10.10.0.0/24"])+ print(f"Created Campaign: {campaign['id']}")++ dispatch = await client.modules.run("ad.kerberoast", target="dc01.corp.local", campaign_id=campaign["id"])+ findings = await client.campaigns.findings(campaign["id"])+```----## Quick Start+## Legacy Quick Start (v1.0.0 - Fully Preserved)```python# my_module.pydiff --git a/example_modules/example_modern_v2_module.py b/example_modules/example_modern_v2_module.pynew file mode 100644index 0000000..b67f965--- /dev/null+++ b/example_modules/example_modern_v2_module.py@@ -0,0 +1,161 @@+"""ARES Example Module (v2 Modern SDK Standard).++Demonstrates:+- Pydantic v2 parameter models (ModuleParams, param, SecretParam)+- Generic BaseModule[P, R] and declarative @ares_module decorator+- Auto-validation and typed context (ctx.params with IDE autocomplete)+- Fluent helpers (ctx.emit_finding, ctx.store_artifact)+- Complete unit testing using ModuleTestHarness and fluent assertions+"""+from __future__ import annotations++import asyncio+import pathlib+import sys+from typing import Any++# Ensure workspace root is in sys.path when run directly+sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))++from ares.sdk import (+ BaseModule,+ ExecutionContext,+ ModuleParams,+ ModuleResult,+ ModuleTestHarness,+ OpsecLevel,+ SecretParam,+ Severity,+ UserArtifact,+ ares_module,+ param,+)+++# ── 1. Type-Safe Parameter Model ──────────────────────────────────────────────+++class KerberoastParams(ModuleParams):+ dc: str = param(description="Target Domain Controller IP or FQDN", min_length=3)+ domain: str = param(description="AD DNS domain name, e.g. CORP.LOCAL", min_length=3)+ username: str = param(description="Domain username for TGS requests")+ password: SecretParam = param(description="Domain user password", secret=True, required=False)+ target_spn: str = param(description="Target specific SPN or service account", required=False, default="")+ request_timeout: int = param(description="Kerberos request timeout (seconds)", default=30, ge=1, le=180)+++# ── 2. Modern Class-Based Module Definition ───────────────────────────────────+++class ModernKerberoastModule(BaseModule[KerberoastParams, ModuleResult]):+ """Modernized attack module leveraging ARES SDK v2 contracts."""++ MODULE_ID = "ad.kerberoast_v2"+ MODULE_NAME = "Modern Kerberoast Attack"+ MODULE_CATEGORY = "ad"+ MODULE_DESCRIPTION = "Requests Kerberos TGS tickets for SPN accounts with type-safe parameters."+ MODULE_AUTHOR = "ARES Core Team"+ OPSEC_LEVEL = OpsecLevel.LOW+ REQUIRES = ["domain_creds"]+ OUTPUTS = ["kerberos_tickets", "credentials"]+ MITRE_TECHNIQUES = ["T1558.003"]+ PARAMS_MODEL = KerberoastParams++ async def execute(self, ctx: ExecutionContext[KerberoastParams]) -> ModuleResult:+ """Execute the attack with fully validated, typed parameters."""+ # ctx.params has 100% type safety and autocompletion+ p = ctx.params++ if ctx.dry_run:+ ctx.emit_finding(+ title="[DRY-RUN] Kerberoast Probe Succeeded",+ severity=Severity.INFO,+ description=f"Dry run probe against DC {p.dc} in domain {p.domain}",+ mitre_technique="T1558.003",+ )+ return ModuleResult(+ status="dry_run",+ module_id=self.MODULE_ID,+ raw={"target_dc": p.dc, "domain": p.domain},+ )++ # Simulated operational logic+ await self.before_request(p.dc)++ # Emit finding cleanly using fluent context helper+ finding = ctx.emit_finding(+ title=f"Kerberoastable SPN Hash Acquired: {p.target_spn or 'MSSQLSvc/db01.corp.local'}",+ severity=Severity.HIGH,+ description=f"Captured RC4-HMAC TGS ticket for offline cracking against DC {p.dc}",+ mitre_technique="T1558.003",+ mitre_tactic="TA0006",+ evidence={"spn": p.target_spn or "MSSQLSvc/db01.corp.local", "etype": 23},+ )++ ctx.store_artifact(+ UserArtifact(+ username="svc-mssql",+ domain=p.domain,+ source_module=self.MODULE_ID,+ attributes={"spn": p.target_spn or "MSSQLSvc/db01.corp.local"},+ )+ )++ return ModuleResult(+ status="success",+ findings=[finding],+ module_id=self.MODULE_ID,+ raw={"dc": p.dc, "domain": p.domain, "tickets_acquired": 1},+ )+++# ── 3. Modern Functional Decorator Definition ─────────────────────────────────+++@ares_module(+ id="ad.fast_tgs_probe",+ name="Fast TGS Probe",+ category="ad",+ description="Fast check for kerberoastable accounts using functional syntax",+ opsec=OpsecLevel.LOW,+ mitre="T1558.003",+ params_model=KerberoastParams,+)+async def fast_tgs_probe(ctx: ExecutionContext[KerberoastParams]) -> ModuleResult:+ """Functional module alternative for lightweight adversary techniques."""+ ctx.emit_finding(+ title=f"TGS Ticket Validated on {ctx.params.dc}",+ severity=Severity.HIGH,+ mitre_technique="T1558.003",+ )+ return ModuleResult(+ status="success",+ module_id="ad.fast_tgs_probe",+ raw={"dc": ctx.params.dc},+ )+++# ── 4. Unit Test Example ──────────────────────────────────────────────────────+++async def _run_example_simulation() -> None:+ """Run an isolated test simulation using ModuleTestHarness."""+ harness = ModuleTestHarness(ModernKerberoastModule)+ result = await harness.simulate(+ params={+ "dc": "10.0.0.10",+ "domain": "LAB.LOCAL",+ "username": "lowpriv_user",+ "password": "Password123!",+ "target_spn": "MSSQLSvc/sql01.lab.local:1433",+ },+ dry_run=True,+ )+ result.assert_success()+ result.assert_no_errors()+ finding = result.assert_finding(mitre="T1558.003")+ print(f"[+] Simulation passed! Emitted finding: {finding.title}")+++if __name__ == "__main__":+ asyncio.run(_run_example_simulation())diff --git a/tests/unit/test_modern_sdk_v2.py b/tests/unit/test_modern_sdk_v2.pynew file mode 100644index 0000000..22d13a4--- /dev/null+++ b/tests/unit/test_modern_sdk_v2.py@@ -0,0 +1,290 @@+"""Unit tests for ARES SDK v2 Modern Standard.++Tests:+1. Pydantic v2 parameter models (ModuleParams, param, SecretParam, validate_params).+2. Generic BaseModule[P, R] and PARAMS_MODEL integration.+3. @ares_module functional and declarative decorator.+4. ExecutionContext fluent helpers (emit_finding, typed_params, store_artifact, record_credential).+5. ModuleTestHarness and SimulationResult fluent assertions.+6. AresClient async REST client with mock transport and error handling.+"""+from __future__ import annotations++import json+from typing import Any++import httpx+import pytest++from ares.core.campaign import Finding, Severity+from ares.core.context import ExecutionContext+from ares.core.errors import ModuleValidationError+from ares.modules.base import ModuleResult, OpsecLevel, normalize_module_metadata+from ares.sdk import (+ AresAuthenticationError,+ AresClient,+ AresNotFoundError,+ AresValidationError,+ BaseModule,+ ModuleParams,+ ModuleTestHarness,+ SecretParam,+ SimulationResult,+ ares_module,+ param,+ validate_params,+)+++class SampleParams(ModuleParams):+ target: str = param("Target IP or hostname", min_length=3)+ port: int = param("Target port", required=False, default=445, ge=1, le=65535)+ password: SecretParam = param("Admin password", secret=True, required=False)+++# ── 1. Parameter Model Tests ──────────────────────────────────────────────────+++def test_params_model_validates_successfully() -> None:+ validated = validate_params(+ SampleParams,+ {"target": "10.0.0.1", "port": 8443, "password": "SuperSecretPassword123!"},+ module_id="test.sample",+ )+ assert validated.target == "10.0.0.1"+ assert validated.port == 8443+ assert validated.password.get_secret_value() == "SuperSecretPassword123!"+++def test_params_model_rejects_invalid_values() -> None:+ with pytest.raises(ModuleValidationError) as exc_info:+ validate_params(SampleParams, {"target": "x", "port": 99999}, module_id="test.sample")+ assert "target" in str(exc_info.value) or "port" in str(exc_info.value)+ assert exc_info.value.module_id == "test.sample"+++def test_params_safe_dict_redacts_secrets() -> None:+ p = SampleParams.model_validate({"target": "10.0.0.1", "password": "my_secret_token"})+ safe = p.safe_dict()+ assert safe["password"] == "***"+ assert safe["target"] == "10.0.0.1"+++# ── 2. BaseModule[P, R] and PARAMS_MODEL Tests ───────────────────────────────+++async def test_base_module_with_params_model_validates_context() -> None:+ class TypedModule(BaseModule[SampleParams, ModuleResult]):+ MODULE_ID = "test.typed_module"+ MODULE_NAME = "Typed Module Test"+ MODULE_CATEGORY = "network"+ PARAMS_MODEL = SampleParams++ async def execute(self, ctx: ExecutionContext[SampleParams]) -> ModuleResult:+ # ctx.params should be automatically parsed into SampleParams!+ assert isinstance(ctx.params, SampleParams)+ ctx.emit_finding(+ title=f"Discovered Port {ctx.params.port}",+ severity=Severity.HIGH,+ mitre_technique="T1046",+ )+ return ModuleResult(status="success", module_id=self.MODULE_ID)++ harness = ModuleTestHarness(TypedModule)+ result = await harness.simulate(params={"target": "192.168.1.10", "port": 3389})++ result.assert_success()+ result.assert_no_errors()+ finding = result.assert_finding(severity=Severity.HIGH, mitre="T1046")+ assert "Discovered Port 3389" in finding.title+++def test_normalize_module_metadata_extracts_params_model_schema() -> None:+ class AutoSchemaModule(BaseModule):+ MODULE_ID = "test.auto_schema"+ MODULE_NAME = "Auto Schema Module"+ MODULE_CATEGORY = "network"+ PARAMS_MODEL = SampleParams++ meta = normalize_module_metadata(AutoSchemaModule)+ assert "target" in meta["required_params"]+ assert "port" in meta["optional_params"]+ assert meta["param_schema"]["password"]["secret"] is True+++# ── 3. @ares_module Functional Decorator Tests ────────────────────────────────+++async def test_ares_module_functional_decorator() -> None:+ @ares_module(+ id="demo.functional",+ name="Demo Functional Attack",+ category="recon",+ description="Smoke test for @ares_module functional authoring",+ opsec=OpsecLevel.LOW,+ mitre="T1595.002",+ params_model=SampleParams,+ )+ async def demo_attack(ctx: ExecutionContext[SampleParams]) -> ModuleResult:+ assert isinstance(ctx.params, SampleParams)+ ctx.emit_finding(+ title=f"Host Enumerated: {ctx.params.target}",+ severity=Severity.MEDIUM,+ mitre_technique="T1595.002",+ )+ return ModuleResult(+ status="success",+ module_id="demo.functional",+ raw={"probed_port": ctx.params.port},+ )++ assert issubclass(demo_attack, BaseModule)+ assert demo_attack.MODULE_ID == "demo.functional"+ assert demo_attack.MODULE_NAME == "Demo Functional Attack"+ assert demo_attack.PARAMS_MODEL is SampleParams++ harness = ModuleTestHarness(demo_attack)+ result = await harness.simulate(params={"target": "10.10.10.50", "port": 80})++ result.assert_success()+ finding = result.assert_finding(severity=Severity.MEDIUM, mitre="T1595.002")+ assert "10.10.10.50" in finding.title+ assert result.raw["probed_port"] == 80+++# ── 4. ExecutionContext Fluent Helper Tests ───────────────────────────────────+++def test_execution_context_fluent_helpers() -> None:+ ctx = ExecutionContext[SampleParams].for_test(+ target="10.0.0.5",+ module_id="test.context_helper",+ params={"target": "10.0.0.5", "port": 445},+ )++ # typed_params+ typed = ctx.typed_params(SampleParams)+ assert isinstance(typed, SampleParams)+ assert typed.target == "10.0.0.5"+ assert typed.port == 445++ # emit_finding+ finding = ctx.emit_finding(+ title="Vulnerability Found",+ severity=Severity.CRITICAL,+ description="Dangerous service exposed",+ mitre_technique="T1210",+ )+ assert isinstance(finding, Finding)+ assert finding.severity == Severity.CRITICAL+ assert finding.host == "10.0.0.5"+ assert len(ctx.findings) == 1+ assert ctx.findings[0] is finding+++# ── 5. ModuleTestHarness & SimulationResult Assertions ─────────────────────────+++async def test_module_test_harness_catches_validation_failure() -> None:+ class StrictModule(BaseModule):+ MODULE_ID = "test.strict"+ MODULE_NAME = "Strict Module"+ MODULE_CATEGORY = "network"+ PARAMS_MODEL = SampleParams++ harness = ModuleTestHarness(StrictModule)+ # Target length is min_length=3, provide length 1 to trigger validation error+ result = await harness.simulate(params={"target": "x"})++ result.assert_failed()+ assert result.error is not None+ assert "target" in result.error+++# ── 6. Programmatic AresClient Tests ──────────────────────────────────────────+++async def test_ares_client_rest_operations() -> None:+ # Build a mock transport simulating ARES server endpoints+ async def mock_handler(request: httpx.Request) -> httpx.Response:+ url = str(request.url)+ path = request.url.path++ if path == "/health":+ return httpx.Response(200, json={"status": "ok", "version": "6.0.0", "db": "connected"})++ if path == "/campaigns" and request.method == "GET":+ return httpx.Response(200, json=[{"id": "c-123", "name": "Op-Titan", "scope": ["10.0.0.0/24"]}])++ if path == "/campaigns" and request.method == "POST":+ data = json.loads(request.content.decode("utf-8"))+ return httpx.Response(201, json={"id": "c-new-456", "name": data["name"], "scope": data["scope"]})++ if path == "/campaigns/c-123" and request.method == "GET":+ return httpx.Response(200, json={"id": "c-123", "name": "Op-Titan"})++ if path == "/campaigns/c-123" and request.method == "DELETE":+ return httpx.Response(200, json={"deleted": True, "id": "c-123"})++ if path == "/campaigns/c-123/findings":+ return httpx.Response(200, json=[{"id": "f-1", "title": "Kerberoastable Account", "severity": "high"}])++ if path == "/modules":+ return httpx.Response(200, json=[{"id": "ad.kerberoast", "name": "Kerberoasting"}])++ if path == "/modules/ad.kerberoast/run":+ return httpx.Response(200, json={"execution_id": "e-789", "status": "done"})++ if path == "/not-found":+ return httpx.Response(404, json={"detail": "Not Found"})++ if path == "/unauthorized":+ return httpx.Response(401, json={"detail": "Invalid API Key"})++ return httpx.Response(404, json={"detail": "Not Found"})++ transport = httpx.MockTransport(mock_handler)++ async with AresClient(base_url="http://mock-ares:8000", api_key="ares_test_key", transport=transport) as client:+ # 1. Health check+ health = await client.health()+ assert health["status"] == "ok"+ assert health["version"] == "6.0.0"++ # 2. Campaigns+ campaigns = await client.campaigns.list()+ assert len(campaigns) == 1+ assert campaigns[0]["id"] == "c-123"++ created = await client.campaigns.create(name="Op-Apollo", scope=["192.168.1.0/24"])+ assert created["id"] == "c-new-456"+ assert created["name"] == "Op-Apollo"++ camp = await client.campaigns.get("c-123")+ assert camp["id"] == "c-123"++ findings = await client.campaigns.findings("c-123")+ assert len(findings) == 1+ assert findings[0]["title"] == "Kerberoastable Account"++ deleted = await client.campaigns.delete("c-123")+ assert deleted is True++ # 3. Modules+ modules = await client.modules.list()+ assert len(modules) == 1+ assert modules[0]["id"] == "ad.kerberoast"++ exec_res = await client.modules.run("ad.kerberoast", target="dc01.corp.local")+ assert exec_res["status"] == "done"++ # 4. Error mappings+ with pytest.raises(AresNotFoundError):+ await client._get("/not-found")++ with pytest.raises(AresAuthenticationError):+ await client._get("/unauthorized")