Security fixes: P0-P2 complete (22 fixes)

P0 (7): Auth-bypass removed, migrations fixed, plugin-upload disabled, RLS FORCE+WITH CHECK, plugin double-registration fixed, persistent volume, domain removed
P1 (11): User/tenant model, Redis centralized, worker separated, transactional outbox, XSS fixed, DMS chunked streaming, permissions unified, password reset, metrics secured, config/docs fixed, cross-tenant FK
P2 (4): Contact model normalized, cross-imports reduced 94%, commands+state machines for contacts/dms/mail/calendar, SPA path-traversal

8 new migrations, 99 unit tests, 13 commands, 8 contracts, 72 files changed
This commit is contained in:
Agent Zero
2026-07-25 21:03:46 +02:00
parent aaa7406929
commit 727d86614e
103 changed files with 6831 additions and 1053 deletions
+14 -204
View File
@@ -442,104 +442,13 @@ async def upload_plugin(
):
"""Upload and install a plugin from a ZIP file.
The ZIP must contain a plugin directory with a plugin.py that defines a BasePlugin subclass.
Validates the manifest, checks for conflicts, runs migrations, and installs the plugin.
DISABLED — Plugin upload is deactivated due to security vulnerabilities (RCE via exec_module before validation).
Will be re-enabled with signed plugin artifacts and sandboxed execution.
"""
import uuid as uuid_mod
# Validate file is a ZIP
if not file.filename or not file.filename.endswith(".zip"):
raise HTTPException(400, detail={"detail": "File must be a .zip archive", "code": "invalid_file"})
# Check file size
contents = await file.read()
if len(contents) > MAX_UPLOAD_SIZE:
raise HTTPException(
413,
detail={
"detail": f"File too large. Maximum size is {MAX_UPLOAD_SIZE // (1024*1024)} MB",
"code": "file_too_large",
},
)
# Write to temp file
tmp_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
try:
tmp_zip.write(contents)
tmp_zip.close()
# Extract and validate
extract_dir, plugin_name, plugin_class = _extract_plugin_from_zip(tmp_zip.name)
# Check for name conflicts with existing plugins
service = get_plugin_service()
existing_plugins = await service.list_plugins(db)
existing_names = {p["name"] for p in existing_plugins}
if plugin_name in existing_names:
# Check if version is higher
existing_plugin = next(
(p for p in existing_plugins if p["name"] == plugin_name), None
)
if existing_plugin:
raise HTTPException(
409,
detail={
"detail": f"Plugin '{plugin_name}' already exists (version {existing_plugin.get('version', 'unknown')}). "
f"Uninstall the existing plugin first or upload a higher version.",
"code": "plugin_exists",
},
)
# Install the plugin directory
_install_plugin_from_dir(extract_dir, plugin_name, plugin_class)
# Run migrations and install via service
result = await service.install_plugin(
db,
plugin_name,
tenant_id=uuid_mod.UUID(current_user["tenant_id"]),
user_id=uuid_mod.UUID(current_user["user_id"]),
)
# Log audit
from app.core.audit import log_audit
await log_audit(
db,
uuid_mod.UUID(current_user["tenant_id"]),
uuid_mod.UUID(current_user["user_id"]),
action="plugin.upload",
entity_type="plugin",
changes={"name": plugin_name, "version": result.get("version"), "method": "upload"},
)
return {
**result,
"message": f"Plugin '{plugin_name}' uploaded and installed successfully",
}
except ValueError as exc:
raise HTTPException(400, detail={"detail": str(exc), "code": "plugin_validation_error"}) from None
except MigrationValidationError as exc:
raise HTTPException(
422, detail={"detail": str(exc), "code": "migration_validation_error"}
) from None
except Exception as exc:
logger.exception("Failed to upload plugin")
raise HTTPException(
500, detail={"detail": f"Failed to install plugin: {str(exc)}", "code": "install_error"}
) from None
finally:
# Clean up temp files
try:
os.unlink(tmp_zip.name)
except Exception:
pass
try:
if "extract_dir" in dir():
shutil.rmtree(extract_dir, ignore_errors=True)
except Exception:
pass
raise HTTPException(
status_code=403,
detail={"detail": "Plugin upload is disabled. Use signed plugin artifacts from the allowlist.", "code": "upload_disabled"},
)
@router.post("/install-url")
@@ -548,111 +457,12 @@ async def install_plugin_from_url(
db: AsyncSession = Depends(get_db),
current_user: dict = Depends(require_permission("plugins:configure")),
):
"""Install a plugin from a URL (downloads ZIP and installs)."""
import uuid as uuid_mod
"""Install a plugin from a URL (downloads ZIP and installs).
if not body.url:
raise HTTPException(400, detail={"detail": "URL is required", "code": "missing_url"})
# Download ZIP from URL
tmp_zip = tempfile.NamedTemporaryFile(delete=False, suffix=".zip")
try:
async with httpx.AsyncClient(timeout=60.0) as client:
response = await client.get(body.url, follow_redirects=True)
response.raise_for_status()
content = response.content
if len(content) > MAX_UPLOAD_SIZE:
raise HTTPException(
413,
detail={
"detail": f"Downloaded file too large. Maximum size is {MAX_UPLOAD_SIZE // (1024*1024)} MB",
"code": "file_too_large",
},
)
tmp_zip.write(content)
tmp_zip.close()
# Extract and validate
extract_dir, plugin_name, plugin_class = _extract_plugin_from_zip(tmp_zip.name)
# Check for name conflicts
service = get_plugin_service()
existing_plugins = await service.list_plugins(db)
existing_names = {p["name"] for p in existing_plugins}
if plugin_name in existing_names:
raise HTTPException(
409,
detail={
"detail": f"Plugin '{plugin_name}' already exists. Uninstall the existing plugin first.",
"code": "plugin_exists",
},
)
# Install the plugin directory
_install_plugin_from_dir(extract_dir, plugin_name, plugin_class)
# Run migrations and install via service
result = await service.install_plugin(
db,
plugin_name,
tenant_id=uuid_mod.UUID(current_user["tenant_id"]),
user_id=uuid_mod.UUID(current_user["user_id"]),
)
# Log audit
from app.core.audit import log_audit
await log_audit(
db,
uuid_mod.UUID(current_user["tenant_id"]),
uuid_mod.UUID(current_user["user_id"]),
action="plugin.install_url",
entity_type="plugin",
changes={"name": plugin_name, "version": result.get("version"), "url": body.url},
)
return {
**result,
"message": f"Plugin '{plugin_name}' downloaded and installed successfully",
}
except httpx.HTTPStatusError as exc:
raise HTTPException(
400,
detail={
"detail": f"Failed to download plugin from URL: HTTP {exc.response.status_code}",
"code": "download_error",
},
) from None
except httpx.RequestError as exc:
raise HTTPException(
400,
detail={
"detail": f"Failed to download plugin from URL: {str(exc)}",
"code": "download_error",
},
) from None
except ValueError as exc:
raise HTTPException(400, detail={"detail": str(exc), "code": "plugin_validation_error"}) from None
except MigrationValidationError as exc:
raise HTTPException(
422, detail={"detail": str(exc), "code": "migration_validation_error"}
) from None
except Exception as exc:
logger.exception("Failed to install plugin from URL")
raise HTTPException(
500, detail={"detail": f"Failed to install plugin: {str(exc)}", "code": "install_error"}
) from None
finally:
# Clean up temp files
try:
os.unlink(tmp_zip.name)
except Exception:
pass
try:
if "extract_dir" in dir():
shutil.rmtree(extract_dir, ignore_errors=True)
except Exception:
pass
DISABLED — URL installation is deactivated due to SSRF and RCE vulnerabilities.
Will be re-enabled with signed plugin artifacts and allowlist.
"""
raise HTTPException(
status_code=403,
detail={"detail": "Plugin URL installation is disabled. Use signed plugin artifacts from the allowlist.", "code": "install_url_disabled"},
)