Fix candidate build metadata and runtime safeguards
Offline project checks / check (push) Canceled after 0s

Repair kernel patch formatting and refresh kernel/camera package revisions and checksums. Integrate battery guard into generated images, correct charging controls and emergency shutdown handling, and reject invalid camera authentication configuration.

Extend recipe validation and regression coverage, and update build and installation documentation. Kernel, camera and image compilation remain pending on the build server.
This commit is contained in:
shenlei
2026-11-09 10:49:22 +09:00
parent 23989f4a18
commit 4f3fe1f94b
19 changed files with 298 additions and 100 deletions
+100 -5
View File
@@ -1,8 +1,12 @@
"""Verify battery charging guard policy and sysfs integration."""
import importlib.util
import contextlib
import io
from pathlib import Path
import subprocess
import tempfile
import unittest
from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('battery_guard', ROOT / 'scripts/phone-battery-guard.py')
@@ -43,20 +47,50 @@ class BatteryGuardTests(unittest.TestCase):
(battery / 'charging_enabled').write_text('1\n')
(charger / 'charging_enabled').write_text('1\n')
(charger / 'current_max').write_text('1500000\n')
(battery / 'charge_control_limit_max').write_text('100\n')
# Disable charging
applied = guard.set_charging(battery, charger, False)
self.assertTrue(applied)
self.assertEqual((battery / 'charging_enabled').read_text().strip(), '0')
self.assertEqual((charger / 'charging_enabled').read_text().strip(), '0')
self.assertEqual((charger / 'current_max').read_text().strip(), '0')
self.assertEqual((charger / 'current_max').read_text().strip(), '1500000')
# Enable charging
applied = guard.set_charging(battery, charger, True)
self.assertTrue(applied)
self.assertEqual((battery / 'charging_enabled').read_text().strip(), '1')
self.assertEqual((charger / 'charging_enabled').read_text().strip(), '1')
self.assertEqual((charger / 'current_max').read_text().strip(), '1500000')
self.assertEqual((battery / 'charge_control_limit_max').read_text().strip(), '100')
def test_usb_input_limits_are_never_used_as_charging_switches(self):
with tempfile.TemporaryDirectory() as temp:
charger = Path(temp)
for limit in (500000, 750000, 900000):
with self.subTest(limit=limit):
(charger / 'current_max').write_text(str(limit) + '\n')
for enable in (False, True):
self.assertFalse(guard.set_charging(None, charger, enable))
self.assertEqual((charger / 'current_max').read_text(), str(limit) + '\n')
(charger / 'charging_enabled').write_text('1\n')
for enable in (False, True):
self.assertTrue(guard.set_charging(None, charger, enable))
self.assertEqual((charger / 'current_max').read_text(), str(limit) + '\n')
(charger / 'charging_enabled').unlink()
def test_standard_charge_behaviour_switch(self):
with tempfile.TemporaryDirectory() as temp:
charger = Path(temp)
behaviour = charger / 'charge_behaviour'
for enable, selected in ((False, 'inhibit-charge'), (True, 'auto')):
behaviour.write_text('[auto] inhibit-charge force-discharge\n')
self.assertTrue(guard.set_charging(None, charger, enable))
self.assertEqual(behaviour.read_text(), selected + '\n')
def test_failed_charging_switch_reports_unavailable(self):
with tempfile.TemporaryDirectory() as temp:
supply = Path(temp)
(supply / 'charging_enabled').mkdir()
self.assertFalse(guard.set_charging(supply, None, False))
def test_thermal_protection(self):
policy = guard.BatteryPolicy(low=50, high=65, max_temp=45)
@@ -71,6 +105,20 @@ class BatteryGuardTests(unittest.TestCase):
self.assertTrue(policy.evaluate(45, temp=410))
self.assertFalse(policy.thermal_throttled)
def test_missing_temperature_keeps_thermal_cutoff_until_confirmed_cool(self):
policy = guard.BatteryPolicy()
self.assertFalse(policy.evaluate(40, temp=460))
self.assertFalse(policy.evaluate(40, temp=None))
self.assertTrue(policy.thermal_throttled)
self.assertFalse(policy.evaluate(40, temp=440))
self.assertTrue(policy.evaluate(40, temp=420))
self.assertFalse(policy.thermal_throttled)
def test_cold_sysfs_temperatures_are_also_tenths_of_a_degree(self):
policy = guard.BatteryPolicy()
for temp in (-50, 0, 100, 150):
self.assertTrue(policy.evaluate(40, temp=temp))
def test_emergency_low_battery_shutdown(self):
policy = guard.BatteryPolicy(low=50, high=65, shutdown_at=5)
# Above shutdown threshold: no shutdown
@@ -117,9 +165,56 @@ class BatteryGuardTests(unittest.TestCase):
called.append(cmd)
return None
guard.trigger_shutdown(executor=mock_executor)
with patch.object(guard.os, 'sync'):
guard.trigger_shutdown(executor=mock_executor)
self.assertEqual(len(called), 1)
self.assertTrue(any('poweroff' in part for part in called[0]))
self.assertEqual(called[0], ['/usr/sbin/poweroff'])
def test_shutdown_bypasses_display_and_falls_back_on_missing_binary(self):
called = []
def executor(cmd, **kwargs):
called.append(cmd)
self.assertEqual(kwargs, dict(check=True, timeout=10))
if len(called) == 1:
raise FileNotFoundError('missing')
with patch.object(guard.os, 'sync'):
guard.trigger_shutdown(executor=executor)
self.assertEqual(called, [['/usr/sbin/poweroff'], ['/sbin/poweroff']])
def test_shutdown_reports_failure_if_all_orderly_commands_fail(self):
def executor(cmd, **kwargs):
raise subprocess.TimeoutExpired(cmd, 10)
with patch.object(guard.os, 'sync'), patch.object(guard.shutil, 'which', return_value=None):
with self.assertRaisesRegex(RuntimeError, 'No orderly poweroff'):
guard.trigger_shutdown(executor=executor)
def test_daemon_retries_shutdown_and_waits_for_actual_init_shutdown(self):
signals = {}
sleeps = []
def sleep(interval):
sleeps.append(interval)
if len(sleeps) == 2:
signals[guard.signal.SIGTERM]()
with patch.object(guard.sys, 'argv', ['guard']), \
patch.object(guard, 'find_supply', return_value=None), \
patch.object(guard, 'get_capacity', return_value=5), \
patch.object(guard, 'get_temp', return_value=300), \
patch.object(guard, 'is_battery_discharging', return_value=True), \
patch.object(guard, 'set_charging', return_value=False), \
patch.object(guard, 'trigger_shutdown', side_effect=[RuntimeError('failed'), None]) as shutdown, \
patch.object(guard.signal, 'signal', side_effect=lambda sig, handler: signals.update({sig: handler})), \
patch.object(guard.time, 'sleep', side_effect=sleep), \
contextlib.redirect_stdout(io.StringIO()) as output, \
contextlib.redirect_stderr(io.StringIO()) as errors:
guard.main()
self.assertEqual(shutdown.call_count, 2)
self.assertIn('retrying next poll', errors.getvalue())
self.assertIn('Charging control unavailable', output.getvalue())
if __name__ == '__main__':
+33
View File
@@ -27,6 +27,39 @@ serve = module('serve')
mqtt = module('camera_mqtt')
class AuthenticationConfigTests(unittest.TestCase):
def test_optional_and_explicitly_disabled_authentication(self):
with tempfile.TemporaryDirectory() as temp:
path = Path(temp) / 'auth.json'
self.assertIsNone(serve.load_auth(path))
path.write_text(json.dumps({'enabled': False}))
self.assertIsNone(serve.load_auth(path))
path.write_text(json.dumps({'username': 'operator', 'password': 'test-password'}))
self.assertEqual(serve.load_auth(path), {'username': 'operator', 'password': 'test-password'})
def test_invalid_authentication_never_falls_back_to_anonymous(self):
with tempfile.TemporaryDirectory() as temp:
path = Path(temp) / 'auth.json'
for content in ('{broken', '[]', '{}', '{"enabled": "false"}',
'{"username": "operator"}', '{"username": "", "password": "value"}',
'{"username": 123, "password": "value"}'):
with self.subTest(content=content):
path.write_text(content)
with self.assertRaises(ValueError):
serve.load_auth(path)
path.unlink()
path.symlink_to('missing-credentials')
with self.assertRaises(ValueError):
serve.load_auth(path)
def test_unreadable_authentication_aborts_without_exposing_credentials(self):
path = Mock()
path.read_text.side_effect = PermissionError('sensitive contents')
with self.assertRaisesRegex(ValueError, 'cannot be read') as error:
serve.load_auth(path)
self.assertNotIn('sensitive', str(error.exception))
class ControlTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
+11
View File
@@ -37,6 +37,9 @@ class ImageRuntimeTests(unittest.TestCase):
self.assertEqual(runtime.audit(self.root), self.result)
self.assertEqual(self.result['screens_verified'], 2)
self.assertTrue((self.root / 'etc/runlevels/default/platina-power-chord').is_file())
self.assertTrue(self.result['battery_guard_active'])
self.assertTrue((self.root / 'etc/runlevels/default/platina-battery-guard').is_file())
self.assertTrue((self.root / 'usr/local/sbin/platina-battery-guard').is_file())
self.assertIn('dry_run=no', (self.root / runtime.CONFIG).read_text())
self.assertEqual((self.root / 'etc/platina-release').read_text(),
'Platina Linux ' + self.result['version'] + '\n')
@@ -66,6 +69,14 @@ class ImageRuntimeTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, 'symlink'):
runtime.audit(self.root)
def test_battery_guard_missing_or_disabled_is_rejected(self):
(self.root / 'etc/runlevels/default/platina-battery-guard').unlink()
with self.assertRaisesRegex(ValueError, 'symlink'):
runtime.audit(self.root)
(self.root / 'usr/local/sbin/platina-battery-guard').unlink()
with self.assertRaises(FileNotFoundError):
runtime.audit(self.root)
def test_manifest_cannot_add_unrelated_or_traversing_files(self):
path = self.root / runtime.MANIFEST
manifest = json.loads(path.read_text())
+35
View File
@@ -75,6 +75,41 @@ class ArtifactTests(unittest.TestCase):
self.verify()
class RecipeChecksTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.package = self.root / 'camera'
self.package.mkdir()
def recipe(self, name, content):
source = self.package / name
source.write_text(content)
(self.package / 'APKBUILD').write_text(
'sha512sums="\n' + workflow.digest(source, 'sha512') + ' ' + name + '\n"\n')
return source
def check(self):
workflow.recipe_checks(self.root, set(), packages=('camera',))
def test_camera_source_checksum_is_checked(self):
source = self.recipe('serve.py', 'print("original")\n')
self.check()
source.write_text('print("changed")\n')
with self.assertRaisesRegex(ValueError, 'Recipe input'):
self.check()
def test_patch_syntax_is_checked_even_with_matching_checksum(self):
self.recipe('bad.patch', '--- a/file\n+++ b/file\n@@ -1 +1,2 @@\n-old\n+new\n')
with self.assertRaisesRegex(ValueError, 'Invalid patch format'):
self.check()
def test_valid_patch_is_accepted_without_upstream_checkout(self):
self.recipe('valid.patch', '--- a/file\n+++ b/file\n@@ -1 +1 @@\n-old\n+new\n')
self.check()
class PrepareTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()