Agent Zero AI framework
Fix backup restore allowed origins
Alessandroe6123e476ad5
diff --git a/helpers/backup.py b/helpers/backup.pyindex 38fc70a69..f97ff67af 100644--- a/helpers/backup.py+++ b/helpers/backup.py@@ -8,7 +8,7 @@ from typing import List, Dict, Any, Optionalfrom pathspec import PathSpec-from helpers import files, runtime, git+from helpers import files, runtime, git, dotenvfrom helpers.localization import Localizationfrom helpers.print_style import PrintStyle@@ -608,6 +608,9 @@ class BackupService:) -> Dict[str, Any]:"""Restore files from backup archive"""+ allowed_origins = dotenv.get_dotenv_value("ALLOWED_ORIGINS", "")+ dotenv_path = os.path.abspath(dotenv.get_dotenv_file_path())+# Save uploaded file temporarilytemp_dir = tempfile.mkdtemp()temp_file = os.path.join(temp_dir, "backup.zip")@@ -725,6 +728,11 @@ class BackupService:with zipf.open(archive_path) as source, open(target_path, 'wb') as target:shutil.copyfileobj(source, target)+ if os.path.abspath(target_path) == dotenv_path:+ dotenv.save_dotenv_value(+ "ALLOWED_ORIGINS", allowed_origins, reload_env=False+ )+restored_files.append({"archive_path": archive_path,"original_path": original_path,diff --git a/helpers/backup.py.dox.md b/helpers/backup.py.dox.mdindex 5612447ec..5cb9c24ec 100644--- a/helpers/backup.py.dox.md+++ b/helpers/backup.py.dox.md@@ -27,6 +27,7 @@- Imported dependency areas include: `datetime`, `helpers`, `helpers.localization`, `helpers.print_style`, `json`, `os`, `pathspec`, `platform`, `tempfile`, `typing`, `zipfile`.- `test_patterns(..., max_files=None)` is the unlimited scan mode. UI preview and dry-run callers may pass bounded limits, but real backup creation and restore clean-before-restore must use unlimited matching so archives and cleanup are not silently truncated.- Default backup metadata includes persistent `/usr` data but excludes Time Travel shadow history under `usr/.time_travel/**`.+- Restoring `usr/.env` preserves the destination instance's allowed origins while restoring authentication and other portable configuration from the archive.## Key Conceptsdiff --git a/helpers/dotenv.py b/helpers/dotenv.pyindex 3ce4d938f..ebb027b7a 100644--- a/helpers/dotenv.py+++ b/helpers/dotenv.py@@ -21,7 +21,7 @@ def get_dotenv_value(key: str, default: Any = None):# load_dotenv()return os.getenv(key, default)-def save_dotenv_value(key: str, value: str):+def save_dotenv_value(key: str, value: str, reload_env: bool = True):if value is None:value = ""dotenv_path = get_dotenv_file_path()@@ -40,4 +40,5 @@ def save_dotenv_value(key: str, value: str):f.seek(0)f.writelines(lines)f.truncate()- load_dotenv()+ if reload_env:+ load_dotenv()diff --git a/helpers/dotenv.py.dox.md b/helpers/dotenv.py.dox.mdindex 2e142d657..375f5d95d 100644--- a/helpers/dotenv.py.dox.md+++ b/helpers/dotenv.py.dox.md@@ -14,7 +14,7 @@- `load_dotenv()`- `get_dotenv_file_path()`- `get_dotenv_value(key: str, default: Any=...)`-- `save_dotenv_value(key: str, value: str)`+- `save_dotenv_value(key: str, value: str, reload_env: bool=...)`- Notable constants/configuration names: `KEY_AUTH_LOGIN`, `KEY_AUTH_PASSWORD`, `KEY_RFC_PASSWORD`, `KEY_ROOT_PASSWORD`.## Runtime Contracts@@ -23,6 +23,7 @@- Update this file whenever public functions, classes, persistence behavior, path/security assumptions, side effects, or cross-module contracts change.- Observed side-effect areas: filesystem reads, filesystem writes, secret handling.- Imported dependency areas include: `dotenv`, `files`, `os`, `re`, `typing`.+- `save_dotenv_value(..., reload_env=False)` updates the persisted file without changing the running process environment.## Key Conceptsdiff --git a/tests/test_backup_large_archives.py b/tests/test_backup_large_archives.pyindex e8c607655..bd2223eb9 100644--- a/tests/test_backup_large_archives.py+++ b/tests/test_backup_large_archives.py@@ -4,7 +4,9 @@ import zipfilefrom pathlib import Pathimport pytest+from dotenv import dotenv_values+from helpers import dotenvfrom helpers.backup import BackupService@@ -38,6 +40,73 @@ async def test_default_backup_patterns_exclude_time_travel_history(tmp_path):assert f"{root}/usr/.time_travel/**" in metadata["exclude_patterns"]+ ("backup_credentials", "expected_credentials"),+ [+ (+ "AUTH_LOGIN=backup\nAUTH_PASSWORD=backup-password\n",+ {"AUTH_LOGIN": "backup", "AUTH_PASSWORD": "backup-password"},+ ),+ (+ "AUTH_LOGIN=\nAUTH_PASSWORD=\n",+ {"AUTH_LOGIN": "", "AUTH_PASSWORD": ""},+ ),+ ("", {}),+ ],+ ids=("credentials", "blank-credentials", "missing-credentials"),+)+async def test_restore_preserves_destination_origin_and_restores_backup_credentials(+ tmp_path, monkeypatch, backup_credentials, expected_credentials+):+ old_root = "/old-a0"+ destination_root = tmp_path / "a0"+ destination_env = destination_root / "usr" / ".env"+ destination_env.parent.mkdir(parents=True)+ destination_env.write_text(+ "AUTH_LOGIN=current\n"+ "AUTH_PASSWORD=current-password\n"+ "ALLOWED_ORIGINS=http://current.example\n",+ encoding="utf-8",+ )+ monkeypatch.setenv("AUTH_LOGIN", "current")+ monkeypatch.setenv("AUTH_PASSWORD", "current-password")+ monkeypatch.setenv("ALLOWED_ORIGINS", "http://current.example")+ monkeypatch.setattr(dotenv, "get_dotenv_file_path", lambda: str(destination_env))+ monkeypatch.setattr(+ dotenv,+ "load_dotenv",+ lambda: pytest.fail("restore must not reload unrelated environment values"),+ )++ zip_path = tmp_path / "backup.zip"+ metadata = {+ "environment_info": {"agent_zero_root": old_root},+ "include_patterns": [f"{old_root}/usr/**"],+ "exclude_patterns": [],+ "include_hidden": True,+ }+ with zipfile.ZipFile(zip_path, "w") as archive:+ archive.writestr("metadata.json", json.dumps(metadata))+ archive.writestr(+ "old-a0/usr/.env",+ f"{backup_credentials}ALLOWED_ORIGINS=http://backup.example\n"+ "PORTABLE_SETTING=restored\n",+ )++ service = BackupService()+ service.agent_zero_root = str(destination_root)+ result = await service.restore_backup(UploadedBackup(zip_path))++ assert dotenv_values(destination_env) == {+ **expected_credentials,+ "ALLOWED_ORIGINS": "http://current.example",+ "PORTABLE_SETTING": "restored",+ }+ assert len(result["restored_files"]) == 1+ assert result["errors"] == []++@pytest.mark.asyncioasync def test_pattern_scan_can_run_without_file_limit(tmp_path):root = tmp_path / "a0"