Skip to content

armgit / ARES

Public Imported from GitHub
0

ARES - authorized red-team engagement automation with dashboard, campaign scope, module orchestration, OPSEC controls, encrypted vault, and reporting.

feat(updater): expand ares upgrade into full-system platform update engine

Mafifrizib28ec213c186
diff --git a/README.md b/README.md
index 812dc3e..b821a6b 100644
--- a/README.md
+++ b/README.md
@@ -522,9 +522,11 @@ ARES includes a built-in Nuclei-style update engine. Operators do not need to `g
ares update --module <id> # Install a specific new module
ares update --dry-run # Preview new modules without modifying disk
```
-- **In-Place Upgrades (Existing Modules, Web UI, Full Platform)**:
+- **In-Place Upgrades (System Core, Database Schema, Modules, Web UI)**:
```powershell
- ares upgrade --all # Upgrade full platform (modules + Web UI + engine)
+ ares upgrade # Full-system upgrade (Core platform + DB migrations + Modules + UI)
+ ares upgrade --system # Upgrade core framework engine and apply database schema migrations
+ ares upgrade --check # Check commit delta and available updates without modifying disk
ares upgrade --ui # Upgrade Frontend Web UI dashboard bundle
ares upgrade --modules # Upgrade installed modules to latest revisions
ares upgrade --dry-run # Preview upgrades without modifying disk
diff --git a/ares/cli/typer_main.py b/ares/cli/typer_main.py
index 61a40a0..8e524e4 100644
--- a/ares/cli/typer_main.py
+++ b/ares/cli/typer_main.py
@@ -2379,26 +2379,59 @@ def update_cmd(
@app.command("upgrade")
def upgrade_cmd(
- all: bool = typer.Option(False, "--all", "-a", help="Upgrade full platform (modules + Web UI + engine)"),
+ all: bool = typer.Option(False, "--all", "-a", help="Upgrade full platform (core engine + DB migrations + modules + Web UI)"),
+ system: bool = typer.Option(False, "--system", "--core", help="Upgrade core framework engine and apply database schema migrations"),
ui: bool = typer.Option(False, "--ui", help="Upgrade Frontend Web UI Dashboard bundle"),
modules: bool = typer.Option(False, "--modules", help="Upgrade existing attack modules to latest versions"),
module: Optional[str] = typer.Option(None, "--module", "-m", help="Specific installed module ID to upgrade"),
+ check: bool = typer.Option(False, "--check", "-c", help="Check for available system and module updates without modifying disk"),
dry_run: bool = typer.Option(False, "--dry-run", help="Preview upgrades without modifying disk"),
repo: str = typer.Option("Mafifrizi/ARES", "--repo", help="Official GitHub repository (owner/repo)"),
branch: str = typer.Option("main", "--branch", help="Git branch to synchronize against"),
) -> None:
"""
- Upgrade existing ARES modules, Web UI dashboard, or the entire platform.
+ Upgrade ARES core platform system, database schemas, attack modules, or Web UI dashboard.
- Ensures zero data loss: Databases, credentials, and custom configurations are preserved.
+ Ensures zero data loss: Databases, credentials, and custom configurations are strictly preserved.
"""
from ares.core.updater import PlatformUpdateManager
+ mgr = PlatformUpdateManager(github_repo=repo, branch=branch)
+
+ # ── 1. Check mode ──────────────────────────────────────────────────────────
+ if check:
+ with console.status("[cyan]Checking remote repository for system updates...[/cyan]"):
+ try:
+ chk = mgr.check_system_update()
+ except Exception as exc:
+ console.print(f"[red][-] Failed checking for updates: {exc}[/red]")
+ raise typer.Exit(1)
+
+ console.print(Panel.fit(
+ f"[bold cyan]ARES Platform System Status[/bold cyan]\n\n"
+ f" [cyan]Current Version:[/] {chk.get('version')} (Branch: [green]{chk.get('branch')}[/green])\n"
+ f" [cyan]Local Commit:[/] {chk.get('local_commit')}\n"
+ f" [cyan]Remote Commit:[/] {chk.get('remote_commit')}\n"
+ f" [cyan]Remote Date:[/] {chk.get('commit_date', 'unknown')}\n"
+ f" [cyan]Latest Change:[/] {chk.get('commit_message', 'none')}\n\n"
+ f" [cyan]Core System:[/] {'[yellow]Update Available[/yellow]' if chk.get('system_update_available') else '[green]Up to date[/green]'}\n"
+ f" [cyan]Attack Modules:[/] {chk.get('new_modules_count', 0)} new, {chk.get('upgradable_modules_count', 0)} upgradable\n"
+ f" [cyan]Web UI Bundle:[/] {'[green]Available[/green]' if chk.get('ui_available') else '[dim]Not indexed[/dim]'}",
+ title="ares upgrade --check",
+ border_style="cyan",
+ box=box.ROUNDED,
+ ))
+ if chk.get("system_update_available") or chk.get("new_modules_count", 0) > 0:
+ console.print("\n[yellow][*] Run [bold]ares upgrade[/bold] to apply the latest system updates.[/yellow]")
+ else:
+ console.print("\n[green][+] System is fully up to date with official release.[/green]")
+ return
+
# Default to --all if no specific scope is selected
- if not all and not ui and not modules and not module:
+ if not all and not system and not ui and not modules and not module:
all = True
- action_label = "Full Platform" if all else ("Web UI Dashboard" if ui and not modules else "Attack Modules")
+ action_label = "Full Platform System" if all else ("Core Engine & DB" if system else ("Web UI Dashboard" if ui and not modules else "Attack Modules"))
console.print(Panel.fit(
"[bold cyan]ARES Platform Upgrade Engine[/bold cyan]\n"
@@ -2406,25 +2439,73 @@ def upgrade_cmd(
border_style="cyan",
))
- mgr = PlatformUpdateManager(github_repo=repo, branch=branch)
-
+ # ── 2. Full Platform System Upgrade ────────────────────────────────────────
if all:
- with console.status("[cyan]Upgrading complete platform (modules, Web UI, hot-reload)...[/cyan]"):
+ with console.status("[cyan]Executing full-system platform upgrade (Core, DB, Modules, UI)...[/cyan]"):
res = mgr.upgrade_all(dry_run=dry_run)
+
if dry_run:
console.print("[yellow][*] Dry-run simulation completed. No files modified.[/yellow]")
return
- console.print("[green][+] Full platform upgrade completed successfully.[/green]")
- console.print(f" - Modules updated: [cyan]{res.get('modules_upgraded', 0)}[/cyan]")
- console.print(f" - New modules added: [cyan]{res.get('modules_added', 0)}[/cyan]")
- console.print(f" - Web UI status: [cyan]{res.get('ui_status', 'ok')}[/cyan]")
+
+ sys_res = res.get("system", {})
+ console.print("\n[bold green][+] Platform System Upgrade Completed[/bold green]\n")
+
+ # System Core
+ sys_status = sys_res.get("status", "ok")
+ if sys_status == "ok":
+ console.print(f" [green]*[/green] Core Framework: [bold green]Updated[/bold green] ({sys_res.get('system', {}).get('message', 'Synchronized')})")
+ elif sys_status == "up_to_date":
+ console.print(" [green]*[/green] Core Framework: [dim]Already up to date[/dim]")
+ elif sys_status == "dirty_tree":
+ console.print(f" [yellow]![/yellow] Core Framework: [yellow]Skipped (working tree has modified files)[/yellow]")
+ else:
+ console.print(f" [yellow]![/yellow] Core Framework: {sys_res.get('system', {}).get('message', 'Checked')}")
+
+ # Database Schema
+ db_res = sys_res.get("database", {})
+ if db_res.get("applied"):
+ console.print(" [green]*[/green] Database Schema: [bold green]Migrated (head)[/bold green]")
+ else:
+ console.print(f" [green]*[/green] Database Schema: [dim]{db_res.get('message', 'Verified')}[/dim]")
+
+ # Attack Modules & UI
+ console.print(f" [green]*[/green] Attack Modules: [cyan]{res.get('modules_upgraded', 0)} updated[/cyan], [cyan]{res.get('modules_added', 0)} new added[/cyan]")
+ console.print(f" [green]*[/green] Web UI Dashboard: [cyan]{res.get('ui_status', 'ok')}[/cyan]")
+
+ # Server reload
srv = res.get("server_reload", {})
if srv.get("connected"):
- console.print(f" - Live Server Hot-Reload: [green]Connected ({srv.get('module_count')} modules active)[/green]")
+ console.print(f" [green]*[/green] Live Server Hot-Reload: [green]Connected ({srv.get('module_count')} modules active)[/green]")
else:
- console.print(" - Live Server: [dim]Offline (changes will apply on next start)[/dim]")
+ console.print(" [green]*[/green] Live Server: [dim]Offline (changes will apply on next start)[/dim]")
+
+ # Post-upgrade diagnostics
+ diag = res.get("diagnostics", {})
+ if diag.get("healthy"):
+ console.print("\n[bold green][+] Post-Upgrade System Diagnostics: HEALTHY (All checks passed)[/bold green]")
+ for c in diag.get("checks", []):
+ console.print(f" [green]OK[/green] {c.get('subsystem')}: [dim]{c.get('detail')}[/dim]")
+ return
+
+ # ── 3. System Core Only Upgrade ────────────────────────────────────────────
+ if system:
+ with console.status("[cyan]Upgrading core framework engine and applying database migrations...[/cyan]"):
+ res = mgr.upgrade_system(dry_run=dry_run)
+ diag = mgr.run_post_upgrade_diagnostics() if not dry_run else {"healthy": True}
+
+ if dry_run:
+ console.print("[yellow][*] Dry-run simulation completed. No files modified.[/yellow]")
+ return
+
+ console.print(f"[green][+] Core engine upgrade: {res.get('status')}[/green]")
+ console.print(f" - Details: {res.get('system', {}).get('message', 'Complete')}")
+ console.print(f" - Database: {res.get('database', {}).get('message', 'Complete')}")
+ if diag.get("healthy"):
+ console.print("[green][+] Post-upgrade health: PASS[/green]")
return
+ # ── 4. Web UI Dashboard Only Upgrade ───────────────────────────────────────
if ui:
with console.status("[cyan]Upgrading Frontend Web UI Dashboard bundle...[/cyan]"):
try:
@@ -2440,6 +2521,7 @@ def upgrade_cmd(
if not modules and not module:
return
+ # ── 5. Attack Modules Only Upgrade ─────────────────────────────────────────
if modules or module:
with console.status("[cyan]Checking and upgrading attack modules...[/cyan]"):
try:
diff --git a/ares/core/updater.py b/ares/core/updater.py
index 8723dea..12c3f78 100644
--- a/ares/core/updater.py
+++ b/ares/core/updater.py
@@ -648,29 +648,408 @@ class PlatformUpdateManager:
"target_dir": str(self.frontend_dist_dir),
}
+ def check_system_update(self) -> dict[str, Any]:
+ """
+ Inspect remote GitHub repository and compare against local system state.
+ Returns commit hash deltas, release metadata, and module update counts.
+ """
+ local_commit = "unknown"
+ current_branch = self.branch
+ git_dir = self.project_root / ".git"
+ if git_dir.exists() and shutil.which("git"):
+ try:
+ proc = subprocess.run(
+ ["git", "rev-parse", "HEAD"],
+ cwd=str(self.project_root),
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if proc.returncode == 0:
+ local_commit = proc.stdout.strip()
+
+ b_proc = subprocess.run(
+ ["git", "rev-parse", "--abbrev-ref", "HEAD"],
+ cwd=str(self.project_root),
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if b_proc.returncode == 0:
+ current_branch = b_proc.stdout.strip()
+ except Exception:
+ pass
+
+ api_url = f"https://api.github.com/repos/{self.github_repo}/commits/{self.branch}"
+ remote_sha = "unknown"
+ commit_msg = ""
+ commit_date = ""
+ commit_author = ""
+ try:
+ raw = self._http_get(api_url)
+ data = json.loads(raw.decode("utf-8"))
+ remote_sha = data.get("sha", "")
+ commit_obj = data.get("commit", {})
+ commit_msg = commit_obj.get("message", "").split("\n")[0]
+ commit_author = commit_obj.get("author", {}).get("name", "")
+ commit_date = commit_obj.get("author", {}).get("date", "")
+ except Exception as exc:
+ logger.debug("Failed fetching remote commit details", error=str(exc))
+
+ modules_check = self.check_updates()
+
+ try:
+ from ares.__version__ import __version__
+ except Exception:
+ __version__ = "6.0.0"
+
+ is_behind = (
+ local_commit != "unknown"
+ and remote_sha != "unknown"
+ and not remote_sha.startswith(local_commit[:7])
+ and not local_commit.startswith(remote_sha[:7])
+ )
+
+ return {
+ "status": "ok",
+ "version": __version__,
+ "branch": current_branch,
+ "local_commit": local_commit[:7] if local_commit != "unknown" else "unknown",
+ "remote_commit": remote_sha[:7] if remote_sha != "unknown" else "unknown",
+ "commit_message": commit_msg,
+ "commit_author": commit_author,
+ "commit_date": commit_date,
+ "system_update_available": is_behind,
+ "new_modules_count": len(modules_check.new_modules),
+ "upgradable_modules_count": len(modules_check.upgradable_modules),
+ "ui_available": modules_check.ui_available,
+ }
+
+ def upgrade_system_git(self, dry_run: bool = False) -> dict[str, Any]:
+ """
+ Perform git-native system upgrade.
+ Fast-forwards HEAD to origin/{branch} if clean.
+ Strictly preserves uncommitted changes.
+ """
+ git_dir = self.project_root / ".git"
+ if not git_dir.exists() or not shutil.which("git"):
+ return {
+ "status": "not_applicable",
+ "method": "git",
+ "message": "Project is not a Git repository or git binary is unavailable.",
+ }
+
+ # Check working tree cleanliness for tracked files
+ status_proc = subprocess.run(
+ ["git", "status", "--porcelain", "-uno"],
+ cwd=str(self.project_root),
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if status_proc.returncode != 0:
+ raise UpdateExecutionError(f"git status failed: {status_proc.stderr.strip()}")
+
+ dirty_tracked = [line.strip() for line in status_proc.stdout.splitlines() if line.strip()]
+ if dirty_tracked:
+ return {
+ "status": "dirty_tree",
+ "method": "git",
+ "message": f"Working tree has {len(dirty_tracked)} modified tracked file(s). Commit or stash before upgrading core engine.",
+ "dirty_files": dirty_tracked,
+ }
+
+ # Fetch latest commits from remote
+ fetch_proc = subprocess.run(
+ ["git", "fetch", "origin", self.branch],
+ cwd=str(self.project_root),
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=30,
+ )
+ if fetch_proc.returncode != 0:
+ raise UpdateExecutionError(f"git fetch failed: {fetch_proc.stderr.strip()}")
+
+ # Check commit distance
+ rev_proc = subprocess.run(
+ ["git", "rev-list", f"HEAD..origin/{self.branch}", "--count"],
+ cwd=str(self.project_root),
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ behind_count = 0
+ if rev_proc.returncode == 0:
+ try:
+ behind_count = int(rev_proc.stdout.strip())
+ except ValueError:
+ pass
+
+ if behind_count == 0:
+ return {
+ "status": "up_to_date",
+ "method": "git",
+ "message": f"System core engine is already up to date with origin/{self.branch}.",
+ "commits_pulled": 0,
+ }
+
+ if dry_run:
+ return {
+ "status": "dry_run",
+ "method": "git",
+ "message": f"[dry-run] Would fast-forward pull {behind_count} commit(s) from origin/{self.branch}.",
+ "commits_available": behind_count,
+ }
+
+ pull_proc = subprocess.run(
+ ["git", "pull", "--ff-only", "origin", self.branch],
+ cwd=str(self.project_root),
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=60,
+ )
+ if pull_proc.returncode != 0:
+ return {
+ "status": "failed",
+ "method": "git",
+ "message": f"git pull --ff-only failed: {pull_proc.stderr.strip()}",
+ "error": pull_proc.stderr.strip(),
+ }
+
+ return {
+ "status": "ok",
+ "method": "git",
+ "message": f"Successfully pulled {behind_count} commit(s) from origin/{self.branch}.",
+ "commits_pulled": behind_count,
+ }
+
+ def upgrade_system_api(self, dry_run: bool = False) -> dict[str, Any]:
+ """
+ API-synchronized system upgrade fallback for standalone non-git installations.
+ Fetches core framework packages via GitHub API with AST pre-flight verification and atomic replacement.
+ """
+ if dry_run:
+ return {
+ "status": "dry_run",
+ "method": "api",
+ "message": "[dry-run] Would synchronize core framework files from GitHub API.",
+ }
+
+ tree = self.fetch_remote_tree()
+ core_prefixes = (
+ "ares/core/",
+ "ares/api/",
+ "ares/cli/",
+ "ares/sdk/",
+ "ares/db/",
+ "ares/mcp/",
+ "alembic.ini",
+ "migrations/",
+ )
+ core_files = [
+ t for t in tree
+ if t.get("type") == "blob" and any(str(t.get("path", "")).startswith(p) for p in core_prefixes)
+ ]
+
+ updated_count = 0
+ errors: list[str] = []
+
+ for entry in core_files:
+ remote_path = entry.get("path", "")
+ try:
+ safe_target = secure_resolve_path(self.project_root, remote_path)
+ raw_url = f"https://raw.githubusercontent.com/{self.github_repo}/{self.branch}/{remote_path}"
+ data = self._http_get(raw_url)
+
+ if remote_path.endswith(".py"):
+ try:
+ ast.parse(data.decode("utf-8", errors="replace"))
+ except SyntaxError as exc:
+ raise SecurityViolationError(f"AST syntax validation failed for '{remote_path}': {exc}")
+
+ atomic_write_file(safe_target, data, is_binary=True)
+ updated_count += 1
+ except Exception as exc:
+ errors.append(f"Failed syncing '{remote_path}': {exc}")
+
+ return {
+ "status": "ok" if not errors else "partial",
+ "method": "api",
+ "updated_files": updated_count,
+ "errors": errors,
+ "message": f"Synchronized {updated_count} core framework file(s).",
+ }
+
+ def apply_database_migrations(self, dry_run: bool = False) -> dict[str, Any]:
+ """
+ Run Alembic database schema migrations to update local database structures to 'head'.
+ Non-destructive: User findings, targets, campaigns, and tokens are strictly preserved.
+ """
+ if dry_run:
+ return {
+ "status": "dry_run",
+ "message": "[dry-run] Would check and apply database schema migrations to head via Alembic.",
+ }
+
+ alembic_ini = self.project_root / "alembic.ini"
+ if not alembic_ini.exists():
+ return {
+ "status": "skipped",
+ "message": "alembic.ini not found in project root; schema migration skipped.",
+ }
+
+ try:
+ from alembic import command as alembic_cmd
+ from alembic.config import Config as AlembicConfig
+
+ alembic_cfg = AlembicConfig(str(alembic_ini))
+ alembic_cmd.upgrade(alembic_cfg, "head")
+ logger.info("Alembic database migrations applied successfully")
+ return {
+ "status": "ok",
+ "applied": True,
+ "message": "Database schema migrations applied successfully (head).",
+ }
+ except Exception as exc:
+ try:
+ cmd = [sys.executable, "-m", "alembic", "upgrade", "head"]
+ proc = subprocess.run(
+ cmd,
+ cwd=str(self.project_root),
+ capture_output=True,
+ text=True,
+ timeout=30,
+ check=False,
+ )
+ if proc.returncode == 0:
+ return {
+ "status": "ok",
+ "applied": True,
+ "message": "Database schema migrations applied successfully via CLI (head).",
+ }
+ return {
+ "status": "warning",
+ "applied": False,
+ "message": f"Database migration returned code {proc.returncode}: {proc.stderr.strip()}",
+ }
+ except Exception as sub_exc:
+ logger.warning("Database migration attempt encountered an issue", error=str(sub_exc))
+ return {
+ "status": "warning",
+ "applied": False,
+ "message": f"Database migration note: {str(exc)}",
+ }
+
+ def upgrade_system(self, dry_run: bool = False) -> dict[str, Any]:
+ """
+ Full core platform upgrade:
+ 1. Upgrades core framework files (Git-native or API sync)
+ 2. Applies pending database schema migrations
+ """
+ git_dir = self.project_root / ".git"
+ if git_dir.exists() and shutil.which("git"):
+ system_res = self.upgrade_system_git(dry_run=dry_run)
+ if system_res.get("status") in ("ok", "up_to_date", "dry_run", "dirty_tree"):
+ db_res = self.apply_database_migrations(dry_run=dry_run)
+ return {
+ "status": system_res.get("status"),
+ "method": "git",
+ "system": system_res,
+ "database": db_res,
+ }
+
+ # Fallback to API sync
+ system_res = self.upgrade_system_api(dry_run=dry_run)
+ db_res = self.apply_database_migrations(dry_run=dry_run)
+ return {
+ "status": system_res.get("status"),
+ "method": "api",
+ "system": system_res,
+ "database": db_res,
+ }
+
+ def run_post_upgrade_diagnostics(self) -> dict[str, Any]:
+ """
+ Post-upgrade health verification.
+ Validates core subsystems, attack module loading, and database connectivity.
+ """
+ checks: list[dict[str, Any]] = []
+
+ # 1. Core Framework imports
+ try:
+ import ares.core
+ import ares.api.server
+ import ares.mcp
+ checks.append({"subsystem": "Core Platform Engine", "status": "PASS", "detail": "Core, API, and MCP imported cleanly"})
+ except Exception as exc:
+ checks.append({"subsystem": "Core Platform Engine", "status": "FAIL", "detail": str(exc)})
+
+ # 2. Module catalog
+ try:
+ local_mods = self.get_local_modules()
+ count = len(local_mods)
+ checks.append({"subsystem": "Attack Modules", "status": "PASS" if count > 0 else "WARN", "detail": f"{count} modules discovered and validated"})
+ except Exception as exc:
+ checks.append({"subsystem": "Attack Modules", "status": "FAIL", "detail": str(exc)})
+
+ # 3. Database
+ db_path = self.project_root / "ares.db"
+ if db_path.exists():
+ checks.append({"subsystem": "Database Storage", "status": "PASS", "detail": f"ares.db online ({db_path.stat().st_size} bytes)"})
+ else:
+ checks.append({"subsystem": "Database Storage", "status": "PASS", "detail": "Clean state (will initialize on first start)"})
+
+ # 4. Web UI Dashboard
+ dist_index = self.frontend_dist_dir / "index.html"
+ if dist_index.exists():
+ checks.append({"subsystem": "Web UI Dashboard", "status": "PASS", "detail": "Distribution bundle verified"})
+ else:
+ checks.append({"subsystem": "Web UI Dashboard", "status": "INFO", "detail": "Source mode (build via 'npm run build' or 'ares upgrade --ui')"})
+
+ all_ok = all(c["status"] == "PASS" for c in checks if c["status"] != "INFO")
+ return {
+ "healthy": all_ok,
+ "checks": checks,
+ }
+
def upgrade_all(self, dry_run: bool = False) -> dict[str, Any]:
"""
- ares upgrade --all: Comprehensive platform upgrade.
- Updates existing modules, adds any newly released modules, and updates Web UI.
+ ares upgrade --all: Comprehensive full-system platform upgrade.
+ 1. Core Framework Engine (Git fast-forward or API sync)
+ 2. Database Schema Migrations (Alembic upgrade head)
+ 3. Attack Modules (patch existing + install new)
+ 4. Frontend Web UI Dashboard bundle
+ 5. Running API server hot-reload
+ 6. Post-upgrade diagnostics verification
"""
- # 1. Patch existing modules
+ # 1. Upgrade core system engine and database
+ system_res = self.upgrade_system(dry_run=dry_run)
+
+ # 2. Patch existing modules
modules_res = self.upgrade_modules(dry_run=dry_run)
- # 2. Add any new modules
+ # 3. Add any new modules
additive_res = self.update_modules(dry_run=dry_run)
- # 3. Upgrade Web UI
+ # 4. Upgrade Web UI
ui_res = self.upgrade_ui(dry_run=dry_run)
- # 4. Notify running server
+ # 5. Notify running server
reload_res = self.notify_running_server_reload() if not dry_run else {"status": "dry_run"}
+ # 6. Run post-upgrade diagnostics
+ diag_res = self.run_post_upgrade_diagnostics() if not dry_run else {"healthy": True, "dry_run": True}
+
return {
"status": "ok",
+ "system": system_res,
"modules_upgraded": modules_res.get("upgraded_count", 0),
"modules_added": additive_res.get("installed_count", 0),
"ui_status": ui_res.get("status"),
"server_reload": reload_res,
+ "diagnostics": diag_res,
"dry_run": dry_run,
}
diff --git a/docs/dashboard-guide.md b/docs/dashboard-guide.md
index b81e126..f6d0f7c 100644
--- a/docs/dashboard-guide.md
+++ b/docs/dashboard-guide.md
@@ -606,7 +606,7 @@ Use it for:
| Module says target is not in scope | Selected campaign has no matching scope CIDR. | Create or select a campaign whose scope includes the target, such as `127.0.0.1/32` for local testing. |
| Telemetry looks empty after restart | Telemetry is an in-memory runtime snapshot. | Run modules in the current API process, or use Reports/Campaigns for durable history. |
| PDF generation fails | No PDF backend or browser fallback is available. | Run `ares doctor --pdf-smoke` from normal non-Administrator PowerShell to check WeasyPrint, native GTK/Pango libraries, `ARES_PDF_BROWSER`, browser profile writability, and report output writability; install the PDF extra/native libraries or set `ARES_PDF_BROWSER` to Edge/Chrome/Chromium. |
-| New modules or UI updates released | Operator needs new capabilities without re-cloning repo. | Run `ares update` to add new modules, or `ares upgrade --all` to upgrade modules and the Web UI seamlessly with zero user data loss. |
+| New modules or UI updates released | Operator needs new capabilities without re-cloning repo. | Run `ares update` to add new modules, or `ares upgrade` to upgrade the full system (core engine, database schemas, modules, Web UI) with zero user data loss. |
## Cross-Platform Notes
The core API, dashboard, database migrations, SDK imports, and unit suite are designed to run on Windows, Linux, and macOS. Package metadata allows Python 3.10-3.12, but the tested release path for the dashboard, Windows PDF browser fallback, and Windows AD/Impacket lab modules is Python 3.12.x. Optional module dependencies can vary by operating system. Use `ares doctor` on each host to see which optional integrations are available before running modules that need AD, cloud, container, PDF, or native password-cracking tooling.
diff --git a/tests/unit/test_cli_update_upgrade.py b/tests/unit/test_cli_update_upgrade.py
index 2a06aae..81b9349 100644
--- a/tests/unit/test_cli_update_upgrade.py
+++ b/tests/unit/test_cli_update_upgrade.py
@@ -30,8 +30,10 @@ def test_cli_upgrade_help():
result = runner.invoke(app, ["upgrade", "--help"], env={"NO_COLOR": "1"})
assert result.exit_code == 0
out = _clean(result.stdout)
- assert "Upgrade existing ARES modules, Web UI dashboard, or the entire platform" in out
+ assert "Upgrade ARES core platform system, database schemas" in out
assert "--all" in out
+ assert "--system" in out
+ assert "--check" in out
assert "--ui" in out
assert "--modules" in out
assert "--dry-run" in out
@@ -99,3 +101,75 @@ def test_cli_upgrade_ui_dry_run():
assert result.exit_code == 0
out = _clean(result.stdout)
assert "Would build or synchronize" in out
+
+
+def test_cli_upgrade_check():
+ fake_chk = {
+ "status": "ok",
+ "version": "6.0.0",
+ "branch": "main",
+ "local_commit": "fa91f1a",
+ "remote_commit": "fa91f1a",
+ "commit_date": "2026-09-20T00:00:00Z",
+ "commit_message": "feat: full platform upgrade",
+ "system_update_available": False,
+ "new_modules_count": 0,
+ "upgradable_modules_count": 0,
+ "ui_available": True,
+ }
+ with patch("ares.core.updater.PlatformUpdateManager.check_system_update", return_value=fake_chk):
+ result = runner.invoke(app, ["upgrade", "--check"], env={"NO_COLOR": "1"})
+ assert result.exit_code == 0
+ out = _clean(result.stdout)
+ assert "ARES Platform System Status" in out
+ assert "6.0.0" in out
+ assert "Up to date" in out
+
+
+def test_cli_upgrade_system_dry_run():
+ fake_sys = {
+ "status": "dry_run",
+ "system": {"message": "[dry-run] Would pull 1 commit"},
+ "database": {"message": "[dry-run] Would apply migrations"},
+ }
+ with patch("ares.core.updater.PlatformUpdateManager.upgrade_system", return_value=fake_sys):
+ result = runner.invoke(app, ["upgrade", "--system", "--dry-run"], env={"NO_COLOR": "1"})
+ assert result.exit_code == 0
+ out = _clean(result.stdout)
+ assert "Core Engine & DB" in out
+ assert "Dry-run simulation completed" in out
+
+
+def test_cli_upgrade_full_system_execution():
+ fake_all = {
+ "status": "ok",
+ "system": {
+ "status": "ok",
+ "system": {"message": "pulled 2 commits"},
+ "database": {"applied": True, "message": "Head migrated"},
+ },
+ "modules_upgraded": 3,
+ "modules_added": 1,
+ "ui_status": "ok",
+ "server_reload": {"connected": True, "module_count": 64},
+ "diagnostics": {
+ "healthy": True,
+ "checks": [
+ {"subsystem": "Core Framework", "detail": "Clean"},
+ {"subsystem": "Database Storage", "detail": "Online"},
+ ],
+ },
+ "dry_run": False,
+ }
+ with patch("ares.core.updater.PlatformUpdateManager.upgrade_all", return_value=fake_all):
+ result = runner.invoke(app, ["upgrade", "--all"], env={"NO_COLOR": "1"})
+ assert result.exit_code == 0
+ out = _clean(result.stdout)
+ assert "Platform System Upgrade Completed" in out
+ assert "Core Framework: Updated" in out
+ assert "Database Schema: Migrated (head)" in out
+ assert "3 updated" in out
+ assert "1 new added" in out
+ assert "Live Server Hot-Reload: Connected" in out
+ assert "Post-Upgrade System Diagnostics: HEALTHY" in out
+
diff --git a/tests/unit/test_updater.py b/tests/unit/test_updater.py
index ca1ebfc..72dbfa0 100644
--- a/tests/unit/test_updater.py
+++ b/tests/unit/test_updater.py
@@ -13,6 +13,7 @@ Validates multi-layered security protections:
import ast
import os
import shutil
+import sys
import tempfile
from pathlib import Path
from unittest.mock import MagicMock, patch
@@ -233,11 +234,88 @@ def test_upgrade_ui_dry_run():
# ── 7. POST /modules/reload API Endpoint ──────────────────────────────────────
def test_post_modules_reload_loopback():
- with TestClient(app, base_url="http://localhost") as client:
- resp = client.post("/modules/reload")
- assert resp.status_code == 200
- data = resp.json()
- assert data.get("status") == "ok"
- assert data.get("reloaded") is True
- assert "module_count" in data
- assert data["module_count"] >= 1
+ saved_modules = dict(sys.modules)
+ try:
+ with TestClient(app, base_url="http://localhost") as client:
+ resp = client.post("/modules/reload")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data.get("status") == "ok"
+ assert data.get("reloaded") is True
+ assert "module_count" in data
+ assert data["module_count"] >= 1
+ finally:
+ sys.modules.clear()
+ sys.modules.update(saved_modules)
+
+
+# ── 8. Platform System Upgrade & Diagnostics ──────────────────────────────────
+
+def test_check_system_update_logic():
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ root = Path(tmp_dir)
+ mgr = PlatformUpdateManager(project_root=root)
+ with patch.object(mgr, "_http_get", return_value=b'{"sha":"abc1234567","commit":{"message":"feat: new release","author":{"name":"ARES","date":"2026-09-20"}}}'):
+ with patch.object(mgr, "check_updates", return_value=UpdateCheckResult()):
+ res = mgr.check_system_update()
+ assert res["status"] == "ok"
+ assert res["remote_commit"] == "abc1234"
+ assert res["commit_message"] == "feat: new release"
+ assert "system_update_available" in res
+
+
+def test_upgrade_system_git_dirty_tree():
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ root = Path(tmp_dir)
+ (root / ".git").mkdir()
+ mgr = PlatformUpdateManager(project_root=root)
+
+ dirty_output = MagicMock(returncode=0, stdout=" M ares/core/test.py\n")
+ with patch("subprocess.run", return_value=dirty_output):
+ res = mgr.upgrade_system_git(dry_run=False)
+ assert res["status"] == "dirty_tree"
+ assert "modified tracked file" in res["message"]
+
+
+def test_apply_database_migrations_dry_run():
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ root = Path(tmp_dir)
+ mgr = PlatformUpdateManager(project_root=root)
+ res = mgr.apply_database_migrations(dry_run=True)
+ assert res["status"] == "dry_run"
+ assert "[dry-run]" in res["message"]
+
+
+def test_run_post_upgrade_diagnostics():
+ mgr = PlatformUpdateManager()
+ res = mgr.run_post_upgrade_diagnostics()
+ assert res["healthy"] is True
+ assert len(res["checks"]) >= 3
+ subsystems = [c["subsystem"] for c in res["checks"]]
+ assert "Core Platform Engine" in subsystems
+ assert "Attack Modules" in subsystems
+
+
+def test_upgrade_all_full_system_workflow():
+ with tempfile.TemporaryDirectory() as tmp_dir:
+ root = Path(tmp_dir)
+ mgr = PlatformUpdateManager(project_root=root)
+
+ fake_sys = {"status": "ok", "system": {"message": "pulled 1 commit"}, "database": {"applied": True}}
+ fake_mods = {"status": "ok", "upgraded_count": 2, "upgraded_modules": ["mod1", "mod2"]}
+ fake_add = {"status": "ok", "installed_count": 1, "installed_modules": ["newmod"]}
+ fake_ui = {"status": "ok", "message": "UI synced"}
+
+ with patch.object(mgr, "upgrade_system", return_value=fake_sys):
+ with patch.object(mgr, "upgrade_modules", return_value=fake_mods):
+ with patch.object(mgr, "update_modules", return_value=fake_add):
+ with patch.object(mgr, "upgrade_ui", return_value=fake_ui):
+ with patch.object(mgr, "notify_running_server_reload", return_value={"connected": True, "module_count": 64}):
+ res = mgr.upgrade_all(dry_run=False)
+ assert res["status"] == "ok"
+ assert res["modules_upgraded"] == 2
+ assert res["modules_added"] == 1
+ assert res["system"]["status"] == "ok"
+ assert res["server_reload"]["connected"] is True
+ assert "diagnostics" in res
+