wrolpi/wrolpi/test/test_upgrade.py
lrnselfreliance dc219e0775
Only offer an update when the remote tip is signed by the release key (#970)
check_for_update reported update_available whenever origin/<branch> was ahead, but upgrade.sh refuses an
unsigned tip (exit 5).  On master, merges land before they are re-signed, so users saw the update icon and
then an upgrade error.  The remote tip is now checked with verify_wrolpi_commit.sh (pinned fingerprint, key
from the running checkout) before an update is offered.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 08:36:02 -07:00

534 lines
22 KiB
Python

"""
Tests for the WROLPi upgrade system.
"""
import subprocess
from http import HTTPStatus
from unittest.mock import patch, MagicMock
import pytest
from wrolpi.errors import ValidationError
from wrolpi.upgrade import (
check_for_update,
get_current_branch,
get_local_commit,
get_remote_commit,
get_commits_behind,
git_fetch,
is_commit_signed,
refresh_update_status,
start_upgrade,
)
from wrolpi.test.test_common import gpg_test_key # noqa: F401 (fixture)
from wrolpi.test.test_verify_wrolpi_commit import signed_repo # noqa: F401 (fixture)
class TestGitFunctions:
"""Test git helper functions."""
def test_git_fetch_directory_not_exists(self):
"""git_fetch returns False when directory doesn't exist."""
mock_path = MagicMock()
mock_path.is_dir.return_value = False
with patch('wrolpi.upgrade.PROJECT_DIR', mock_path):
assert git_fetch() is False
def test_git_fetch_success(self):
"""git_fetch returns True on success."""
mock_result = MagicMock()
mock_result.returncode = 0
mock_path = MagicMock()
mock_path.is_dir.return_value = True
with patch('wrolpi.upgrade.PROJECT_DIR', mock_path), \
patch('subprocess.run', return_value=mock_result):
assert git_fetch() is True
def test_git_fetch_failure(self):
"""git_fetch returns False when command fails."""
mock_result = MagicMock()
mock_result.returncode = 1
mock_result.stderr = b'error message'
mock_path = MagicMock()
mock_path.is_dir.return_value = True
with patch('wrolpi.upgrade.PROJECT_DIR', mock_path), \
patch('subprocess.run', return_value=mock_result):
assert git_fetch() is False
def test_get_current_branch(self):
"""get_current_branch returns the branch name."""
mock_result = MagicMock()
mock_result.returncode = 0
mock_result.stdout = b'release\n'
mock_path = MagicMock()
mock_path.is_dir.return_value = True
with patch('wrolpi.upgrade.PROJECT_DIR', mock_path), \
patch('subprocess.run', return_value=mock_result):
assert get_current_branch() == 'release'
def test_get_current_branch_directory_not_exists(self):
"""get_current_branch returns None when directory doesn't exist."""
mock_path = MagicMock()
mock_path.is_dir.return_value = False
with patch('wrolpi.upgrade.PROJECT_DIR', mock_path):
assert get_current_branch() is None
def test_get_current_branch_detached_head(self):
"""A detached HEAD (`git branch --show-current` prints nothing) defaults to 'release'."""
mock_result = MagicMock()
mock_result.returncode = 0
mock_result.stdout = b'\n'
mock_path = MagicMock()
mock_path.is_dir.return_value = True
with patch('wrolpi.upgrade.PROJECT_DIR', mock_path), \
patch('subprocess.run', return_value=mock_result):
assert get_current_branch() == 'release'
def test_get_current_branch_command_failed(self):
"""A failing git command (e.g. not a repository) returns None."""
mock_result = MagicMock()
mock_result.returncode = 128
mock_result.stdout = b''
mock_path = MagicMock()
mock_path.is_dir.return_value = True
with patch('wrolpi.upgrade.PROJECT_DIR', mock_path), \
patch('subprocess.run', return_value=mock_result):
assert get_current_branch() is None
def test_get_current_branch_with_ambiguous_tag(self, test_directory):
"""A tag with the same name as the branch must not change the reported branch name.
`git rev-parse --abbrev-ref HEAD` reports "heads/release" when a `release` tag also
exists, which breaks the origin/{branch} comparison in check_for_update.
"""
repo = test_directory / 'repo'
repo.mkdir()
env = {'GIT_AUTHOR_NAME': 'test', 'GIT_AUTHOR_EMAIL': 'test@example.com',
'GIT_COMMITTER_NAME': 'test', 'GIT_COMMITTER_EMAIL': 'test@example.com'}
for cmd in (
['git', 'init', '--initial-branch=release'],
['git', 'commit', '--allow-empty', '-m', 'one'],
['git', 'commit', '--allow-empty', '-m', 'two'],
# Tag an old commit with the same name as the branch, like the stale
# `release` tag found on real WROLPi installs.
['git', 'tag', 'release', 'HEAD~1'],
):
subprocess.run(cmd, cwd=repo, check=True, capture_output=True, env=env)
with patch('wrolpi.upgrade.PROJECT_DIR', repo):
assert get_current_branch() == 'release'
def test_get_local_commit(self):
"""get_local_commit returns the short commit hash."""
mock_result = MagicMock()
mock_result.returncode = 0
mock_result.stdout = b'abc1234\n'
mock_path = MagicMock()
mock_path.is_dir.return_value = True
with patch('wrolpi.upgrade.PROJECT_DIR', mock_path), \
patch('subprocess.run', return_value=mock_result):
assert get_local_commit() == 'abc1234'
def test_get_remote_commit(self):
"""get_remote_commit returns the short commit hash for origin/branch."""
mock_result = MagicMock()
mock_result.returncode = 0
mock_result.stdout = b'def5678\n'
mock_path = MagicMock()
mock_path.is_dir.return_value = True
with patch('wrolpi.upgrade.PROJECT_DIR', mock_path), \
patch('subprocess.run', return_value=mock_result):
assert get_remote_commit('release') == 'def5678'
def test_get_commits_behind(self):
"""get_commits_behind returns the number of commits behind."""
mock_result = MagicMock()
mock_result.returncode = 0
mock_result.stdout = b'5\n'
mock_path = MagicMock()
mock_path.is_dir.return_value = True
with patch('wrolpi.upgrade.PROJECT_DIR', mock_path), \
patch('subprocess.run', return_value=mock_result):
assert get_commits_behind('release') == 5
class TestCheckForUpdate:
"""Test check_for_update function."""
def test_check_for_update_dockerized(self):
"""check_for_update returns no update in Docker."""
with patch('wrolpi.upgrade.DOCKERIZED', True):
result = check_for_update(fetch=False)
assert result['update_available'] is False
def test_check_for_update_directory_not_exists(self):
"""check_for_update returns no update when directory doesn't exist."""
mock_path = MagicMock()
mock_path.is_dir.return_value = False
with patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.PROJECT_DIR', mock_path):
result = check_for_update(fetch=False)
assert result['update_available'] is False
def test_check_for_update_no_update(self):
"""check_for_update returns no update when commits match."""
mock_path = MagicMock()
mock_path.is_dir.return_value = True
with patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.PROJECT_DIR', mock_path), \
patch('wrolpi.upgrade.get_current_branch', return_value='release'), \
patch('wrolpi.upgrade.git_fetch', return_value=True), \
patch('wrolpi.upgrade.get_local_commit', return_value='abc1234'), \
patch('wrolpi.upgrade.get_remote_commit', return_value='abc1234'):
result = check_for_update(fetch=True)
assert result['update_available'] is False
assert result['branch'] == 'release'
assert result['current_commit'] == 'abc1234'
assert result['latest_commit'] == 'abc1234'
def test_check_for_update_update_available(self):
"""check_for_update returns update available when commits differ."""
mock_path = MagicMock()
mock_path.is_dir.return_value = True
with patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.PROJECT_DIR', mock_path), \
patch('wrolpi.upgrade.get_current_branch', return_value='master'), \
patch('wrolpi.upgrade.git_fetch', return_value=True), \
patch('wrolpi.upgrade.get_local_commit', return_value='abc1234'), \
patch('wrolpi.upgrade.get_remote_commit', return_value='def5678'), \
patch('wrolpi.upgrade.get_commits_behind', return_value=3), \
patch('wrolpi.upgrade.is_commit_signed', return_value=True) as mock_signed:
result = check_for_update(fetch=True)
assert result['update_available'] is True
assert result['branch'] == 'master'
assert result['current_commit'] == 'abc1234'
assert result['latest_commit'] == 'def5678'
assert result['commits_behind'] == 3
mock_signed.assert_called_once_with('origin/master')
def test_check_for_update_unsigned_remote(self):
"""An update is not offered when the remote tip is not signed by the release key; upgrade.sh would refuse
it."""
mock_path = MagicMock()
mock_path.is_dir.return_value = True
with patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.PROJECT_DIR', mock_path), \
patch('wrolpi.upgrade.get_current_branch', return_value='master'), \
patch('wrolpi.upgrade.git_fetch', return_value=True), \
patch('wrolpi.upgrade.get_local_commit', return_value='abc1234'), \
patch('wrolpi.upgrade.get_remote_commit', return_value='def5678'), \
patch('wrolpi.upgrade.get_commits_behind', return_value=3), \
patch('wrolpi.upgrade.is_commit_signed', return_value=False) as mock_signed:
result = check_for_update(fetch=True)
mock_signed.assert_called_once_with('origin/master')
assert result['update_available'] is False
assert result['latest_commit'] == 'def5678'
assert result['commits_behind'] == 3
def test_is_commit_signed(signed_repo, monkeypatch):
"""is_commit_signed accepts only a commit signed by the pinned key."""
repo, key, fingerprint = signed_repo
monkeypatch.setenv('WROLPI_SIGNING_FINGERPRINT', fingerprint)
assert is_commit_signed('signed', repo=repo, key=key) is True
assert is_commit_signed('unsigned', repo=repo, key=key) is False
assert is_commit_signed('does-not-exist', repo=repo, key=key) is False
# The real WROLPi key did not sign the test commit.
monkeypatch.delenv('WROLPI_SIGNING_FINGERPRINT')
assert is_commit_signed('signed', repo=repo) is False
def test_check_for_update_skip_fetch(self):
"""check_for_update can skip fetch."""
mock_path = MagicMock()
mock_path.is_dir.return_value = True
with patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.PROJECT_DIR', mock_path), \
patch('wrolpi.upgrade.get_current_branch', return_value='release'), \
patch('wrolpi.upgrade.git_fetch') as mock_fetch, \
patch('wrolpi.upgrade.get_local_commit', return_value='abc1234'), \
patch('wrolpi.upgrade.get_remote_commit', return_value='abc1234'):
result = check_for_update(fetch=False)
mock_fetch.assert_not_called()
assert result['update_available'] is False
class TestStartUpgrade:
"""Test start_upgrade function."""
@pytest.mark.asyncio
async def test_start_upgrade_uses_current_branch(self, tmp_path):
"""start_upgrade writes branch to env file and starts systemd service."""
mock_script_path = MagicMock()
mock_script_path.is_file.return_value = True
env_file = tmp_path / 'wrolpi-upgrade.env'
with patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.UPGRADE_SCRIPT', mock_script_path), \
patch('wrolpi.upgrade.get_current_branch', return_value='master'), \
patch('wrolpi.upgrade.subprocess.Popen') as mock_popen, \
patch('wrolpi.upgrade.pathlib.Path', return_value=env_file), \
patch('wrolpi.events.Events.send_upgrade_started'):
await start_upgrade()
# Verify env file was written with correct branch
assert env_file.read_text() == 'BRANCH=master\n'
# Verify systemctl start was called
mock_popen.assert_called_once()
call_args = mock_popen.call_args[0][0]
assert call_args == ['sudo', 'systemctl', 'start', 'wrolpi-upgrade.service']
@pytest.mark.asyncio
async def test_start_upgrade_uses_release_branch(self, tmp_path):
"""start_upgrade writes release branch to env file."""
mock_script_path = MagicMock()
mock_script_path.is_file.return_value = True
env_file = tmp_path / 'wrolpi-upgrade.env'
with patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.UPGRADE_SCRIPT', mock_script_path), \
patch('wrolpi.upgrade.get_current_branch', return_value='release'), \
patch('wrolpi.upgrade.subprocess.Popen') as mock_popen, \
patch('wrolpi.upgrade.pathlib.Path', return_value=env_file), \
patch('wrolpi.events.Events.send_upgrade_started'):
await start_upgrade()
# Verify env file was written with correct branch
assert env_file.read_text() == 'BRANCH=release\n'
# Verify systemctl start was called
mock_popen.assert_called_once()
call_args = mock_popen.call_args[0][0]
assert call_args == ['sudo', 'systemctl', 'start', 'wrolpi-upgrade.service']
@pytest.mark.asyncio
async def test_start_upgrade_defaults_to_release_on_error(self, tmp_path):
"""start_upgrade defaults to release branch if current branch cannot be determined."""
mock_script_path = MagicMock()
mock_script_path.is_file.return_value = True
env_file = tmp_path / 'wrolpi-upgrade.env'
with patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.UPGRADE_SCRIPT', mock_script_path), \
patch('wrolpi.upgrade.get_current_branch', return_value=None), \
patch('wrolpi.upgrade.subprocess.Popen') as mock_popen, \
patch('wrolpi.upgrade.pathlib.Path', return_value=env_file), \
patch('wrolpi.events.Events.send_upgrade_started'):
await start_upgrade()
# Verify env file was written with default release branch
assert env_file.read_text() == 'BRANCH=release\n'
# Verify systemctl start was called
mock_popen.assert_called_once()
call_args = mock_popen.call_args[0][0]
assert call_args == ['sudo', 'systemctl', 'start', 'wrolpi-upgrade.service']
@pytest.mark.asyncio
async def test_start_upgrade_chosen_branch(self, tmp_path):
"""A branch the user chose is upgraded instead of the current branch."""
mock_script_path = MagicMock()
mock_script_path.is_file.return_value = True
env_file = tmp_path / 'wrolpi-upgrade.env'
with patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.UPGRADE_SCRIPT', mock_script_path), \
patch('wrolpi.upgrade.get_current_branch', return_value='release'), \
patch('wrolpi.upgrade.subprocess.Popen') as mock_popen, \
patch('wrolpi.upgrade.pathlib.Path', return_value=env_file), \
patch('wrolpi.events.Events.send_upgrade_started'):
await start_upgrade('feature/new-thing')
assert env_file.read_text() == 'BRANCH=feature/new-thing\n'
mock_popen.assert_called_once()
@pytest.mark.parametrize('branch', [
'master\nEVIL=1',
'-b',
'a..b',
'a b',
'foo.lock',
'foo/',
'/foo',
'a//b',
'a$b',
'x' * 256,
])
@pytest.mark.asyncio
async def test_start_upgrade_rejects_invalid_branch(self, tmp_path, branch):
"""A branch name git would refuse, or one that could escape the env file, never starts an upgrade."""
mock_script_path = MagicMock()
mock_script_path.is_file.return_value = True
env_file = tmp_path / 'wrolpi-upgrade.env'
with patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.UPGRADE_SCRIPT', mock_script_path), \
patch('wrolpi.upgrade.subprocess.Popen') as mock_popen, \
patch('wrolpi.upgrade.pathlib.Path', return_value=env_file), \
patch('wrolpi.events.Events.send_upgrade_started') as mock_event:
with pytest.raises(ValidationError):
await start_upgrade(branch)
assert not env_file.exists()
mock_popen.assert_not_called()
mock_event.assert_not_called()
@pytest.mark.asyncio
async def test_start_upgrade_skipped_in_docker(self):
"""start_upgrade does nothing in Docker environment."""
with patch('wrolpi.upgrade.DOCKERIZED', True), \
patch('wrolpi.upgrade.subprocess.Popen') as mock_popen:
await start_upgrade()
# Verify Popen was not called
mock_popen.assert_not_called()
@pytest.mark.asyncio
async def test_start_upgrade_script_not_found(self):
"""start_upgrade does nothing if upgrade script doesn't exist."""
mock_script_path = MagicMock()
mock_script_path.is_file.return_value = False
with patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.UPGRADE_SCRIPT', mock_script_path), \
patch('wrolpi.upgrade.subprocess.Popen') as mock_popen:
await start_upgrade()
# Verify Popen was not called
mock_popen.assert_not_called()
@pytest.mark.asyncio
async def test_upgrade_check_api_endpoint(async_client):
"""Test the /api/upgrade/check endpoint."""
# The endpoint is native_only, so in Docker it should return 403
# In tests, we're not in Docker, so patch the upgrade functions
with patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.check_for_update') as mock_check:
mock_check.return_value = {
'update_available': True,
'current_commit': 'abc1234',
'latest_commit': 'def5678',
'branch': 'release',
'commits_behind': 2,
}
_, response = await async_client.get('/api/upgrade/check')
# Note: This may return 403 NATIVE_ONLY in test environment
# The actual test depends on whether DOCKERIZED is True in tests
@pytest.mark.asyncio
async def test_status_endpoint_includes_git_branch(async_client):
"""Test that /api/status includes git_branch from status worker without conflict."""
from wrolpi.api_utils import api_app
# Simulate status_worker having populated git_branch in shared_ctx.status
api_app.shared_ctx.status['git_branch'] = 'release'
try:
_, response = await async_client.get('/api/status')
assert response.status == 200
data = response.json
# git_branch should be present and correct
assert data.get('git_branch') == 'release'
finally:
# Clean up
api_app.shared_ctx.status.pop('git_branch', None)
@pytest.mark.asyncio
async def test_refresh_update_status_does_not_block_event_loop():
"""`git fetch` must run off the event loop.
A synchronous fetch (up to its 60 s timeout) would stall the event loop of the process that
also runs downloads and the file worker.
"""
import asyncio
import threading
import time
seen_threads = []
def slow_check(fetch=True):
seen_threads.append(threading.current_thread())
time.sleep(0.3)
return {'update_available': True, 'commits_behind': 3, 'branch': 'master'}
ticks = 0
async def ticker():
nonlocal ticks
while True:
ticks += 1
await asyncio.sleep(0.01)
status = {}
with patch('wrolpi.upgrade.check_for_update', slow_check):
ticker_task = asyncio.ensure_future(ticker())
await refresh_update_status(status)
ticker_task.cancel()
assert seen_threads and seen_threads[0] is not threading.main_thread(), \
'check_for_update ran on the event loop thread'
assert ticks >= 10, f'event loop was starved during check_for_update (only {ticks} ticks)'
assert status['update_available'] is True and status['commits_behind'] == 3 and status['git_branch'] == 'master'
@pytest.mark.asyncio
async def test_refresh_update_status_can_skip_fetch():
"""The upgrade-check endpoint passes fetch=False unless the user forces a fetch."""
seen = []
def fake_check(fetch=True):
seen.append(fetch)
return {'update_available': False, 'branch': 'master'}
with patch('wrolpi.upgrade.check_for_update', fake_check):
await refresh_update_status({}, fetch=False)
await refresh_update_status({})
assert seen == [False, True]
@pytest.mark.asyncio
async def test_upgrade_start_api_branch(async_client):
"""The upgrade endpoint passes the chosen branch on, and refuses an invalid one."""
with patch('wrolpi.common.DOCKERIZED', False), \
patch('wrolpi.upgrade.DOCKERIZED', False), \
patch('wrolpi.upgrade.UPGRADE_SCRIPT') as mock_script_path, \
patch('wrolpi.upgrade.subprocess.Popen') as mock_popen, \
patch('wrolpi.upgrade.write_upgrade_env') as mock_write, \
patch('wrolpi.events.Events.send_upgrade_started'):
mock_script_path.is_file.return_value = True
request, response = await async_client.post('/api/upgrade/start', json={'branch': 'master'})
assert response.status_code == HTTPStatus.ACCEPTED
mock_write.assert_called_once_with('master')
mock_popen.assert_called_once()
mock_write.reset_mock()
mock_popen.reset_mock()
request, response = await async_client.post('/api/upgrade/start', json={'branch': 'master\nEVIL=1'})
assert response.status_code == HTTPStatus.BAD_REQUEST
mock_write.assert_not_called()
mock_popen.assert_not_called()
# No body upgrades the current branch, as before.
with patch('wrolpi.upgrade.get_current_branch', return_value='release'):
request, response = await async_client.post('/api/upgrade/start')
assert response.status_code == HTTPStatus.ACCEPTED
mock_write.assert_called_once_with('release')