Files
ucvl-home-vision/test_device_power.py

189 lines
10 KiB
Python

"""Restricted power actions: real SQLite, fake network, no hardware commands."""
import base64
import hashlib
import hmac
import json
import secrets
import time
import unittest
from unittest.mock import patch
import test_households as fixtures
import test_phone_locations as phone_fixtures
from device_power import Power
app = fixtures.app
class PowerTests(unittest.TestCase):
stop_server = fixtures.HouseholdTests.stop_server
request = fixtures.HouseholdTests.request
phone = phone_fixtures.PhoneLocationTests.phone
def setUp(self):
fixtures.HouseholdTests.setUp(self)
self.p = Power(app)
self.p.initialize()
self.device = app.INVENTORY.save(dict(name='测试电脑', deviceType='笔记本电脑', typeId='computer', siteId=self.sites[self.aid]['id']), self.owner)
self.key = self.device['id']
self.secret = secrets.token_bytes(32)
self.profile = dict(familyId=self.aid, secret=base64.b64encode(self.secret).decode(), host='100.64.0.1', relayHost='100.64.0.2', sshKey='/fixture/key', knownHosts='/fixture/hosts')
p = patch.object(self.p, 'profiles', return_value={self.key:self.profile}); p.start(); self.addCleanup(p.stop)
p = patch.object(app, 'POWER', self.p); p.start(); self.addCleanup(p.stop)
self.boot = 'b'*32
def sample(self, run):
self.p.observe(self.key, run)
def command(self, op=1, request_id=None, user=None):
return self.p.web(user or self.owner, dict(action='command', deviceId=self.key, op=op, requestId=request_id or secrets.token_hex(16), confirm=True))['power']
def agent(self, **extra):
payload = dict(deviceId=self.key, bootId=self.boot, nonce=secrets.token_hex(16), at=time.time(), ready=True, ack=None)
payload.update(extra)
raw=base64.b64encode(json.dumps(payload).encode()).decode()
envelope=dict(payload=raw,signature=hmac.new(self.secret,raw.encode(),hashlib.sha256).hexdigest())
response=self.p.agent(envelope)
self.assertTrue(hmac.compare_digest(response['signature'],hmac.new(self.secret,response['payload'].encode(),hashlib.sha256).hexdigest()))
result=json.loads(base64.b64decode(response['payload']))
self.assertEqual(result['nonce'],payload['nonce'])
return result
def grant(self, phone, control=True):
return self.p.web(self.owner, dict(action='grants',deviceId=self.key,grants=[dict(personId=phone['member']['personId'],view=True,control=control)]))
def test_unknown_and_stale_fail_closed(self):
state=self.p.read(self.owner,self.key)['power']
self.assertIsNone(state['run']); self.assertFalse(state['canStart'])
self.sample(0); self.assertTrue(self.p.read(self.owner,self.key)['power']['canStart'])
with patch('device_power.time.time',return_value=time.time()+46):
self.assertIsNone(self.p.read(self.owner,self.key)['power']['run'])
with self.assertRaises(app.Problem):self.command()
def test_online_and_maintenance_disable_shutdown(self):
self.sample(1)
self.assertFalse(self.p.read(self.owner,self.key)['power']['canShutdown'])
self.agent(); self.assertTrue(self.p.read(self.owner,self.key)['power']['canShutdown'])
self.agent(ready=False); self.assertFalse(self.p.read(self.owner,self.key)['power']['canShutdown'])
def test_start_requires_offline_and_worker_sends_once(self):
self.sample(1)
with self.assertRaises(app.Problem):self.command()
self.sample(0); self.assertEqual(self.command()['op'],1)
with patch.object(self.p,'probe',return_value=0),patch.object(self.p,'wake') as wake:
self.p.tick(); self.p.tick(); self.assertEqual(wake.call_count,1)
self.sample(1)
state=self.p.read(self.owner,self.key)['power']
self.assertEqual(state['op'],0); self.assertEqual(state['last']['status'],'succeeded')
def test_wake_failure_resets_and_hides_error_details(self):
self.sample(0); self.command()
with patch.object(self.p,'probe',return_value=0),patch.object(self.p,'wake',side_effect=OSError('secret-key-path')):
self.p.tick()
state=self.p.read(self.owner,self.key)['power']
self.assertEqual(state['op'],0); self.assertEqual(state['last']['status'],'failed')
self.assertNotIn('secret-key-path',json.dumps(state))
def test_timeout_and_restart_do_not_replay(self):
self.sample(0); self.command()
with patch('device_power.time.time',return_value=time.time()+121):
self.assertEqual(self.p.read(self.owner,self.key)['power']['op'],0)
self.sample(0); self.command()
self.p.initialize()
with patch.object(self.p,'probe',return_value=0),patch.object(self.p,'wake') as wake:
self.p.tick(); wake.assert_not_called()
self.assertEqual(self.p.read(self.owner,self.key)['power']['last']['status'],'cancelled')
def test_idempotency_and_concurrent_command(self):
self.sample(0); rid=secrets.token_hex(16)
first=self.command(request_id=rid);second=self.command(request_id=rid)
self.assertEqual(first['last']['id'],second['last']['id'])
with self.assertRaises(app.Problem):self.command()
def test_invalid_operation_and_missing_confirmation(self):
self.sample(0)
for op in (True,0,3,'1'):
with self.subTest(op=op),self.assertRaises(app.Problem):self.command(op)
with self.assertRaises(app.Problem):self.p.web(self.owner,dict(action='command',deviceId=self.key,op=1,requestId='a'*32))
def test_shutdown_delivered_once_ack_then_offline(self):
self.agent();self.sample(1);state=self.command(2);cid=state['last']['id']
self.assertEqual(self.agent()['command']['id'],cid)
self.assertIsNone(self.agent()['command'])
self.agent(ack=dict(id=cid,status='scheduled',result='accepted'))
self.sample(0)
state=self.p.read(self.owner,self.key)['power']
self.assertEqual(state['op'],0);self.assertEqual(state['last']['status'],'succeeded')
def test_shutdown_cannot_succeed_before_ack(self):
self.agent();self.command(2);self.sample(0)
self.assertEqual(self.p.read(self.owner,self.key)['power']['op'],2)
def test_agent_integer_wire_times_and_late_failure(self):
self.agent();cid=self.command(2)['last']['id'];response=self.agent()
self.assertIs(type(response['at']),int);self.assertIs(type(response['command']['expires']),int)
self.agent(ack=dict(id=cid,status='scheduled',result='accepted'))
self.agent(ack=dict(id=cid,status='failed',result='windows-veto'))
state=self.p.read(self.owner,self.key)['power']
self.assertEqual(state['op'],0);self.assertEqual(state['last']['status'],'failed')
def test_boot_change_and_failed_ack_cancel_shutdown(self):
self.agent();self.command(2)
self.agent(bootId='c'*32)
self.assertEqual(self.p.read(self.owner,self.key)['power']['op'],0)
self.agent(); state=self.command(2);self.agent()
self.agent(ack=dict(id=state['last']['id'],status='blocked',result='maintenance'))
self.assertEqual(self.p.read(self.owner,self.key)['power']['last']['status'],'failed')
def test_signature_replay_time_and_unknown_identity(self):
nonce='f'*32;self.agent(nonce=nonce)
for extra in (dict(nonce=nonce),dict(at=time.time()-61),dict(deviceId='missing'),dict(bootId='bad')):
with self.subTest(extra=extra),self.assertRaises(app.Problem):self.agent(**extra)
with self.assertRaises(app.Problem):self.p.agent(dict(payload='e30=',signature='0'*64))
def test_phone_pairing_alone_not_device_grant(self):
phone=self.phone('测试家人');self.sample(0)
result=self.p.phone(phone['token'],dict(action='catalog'))
self.assertEqual(result['devices'],[]);self.assertEqual(len(result['households']),1)
with self.assertRaises(app.Problem):self.p.phone(phone['token'],dict(action='status',deviceId=self.key))
self.grant(phone,False)
result=self.p.phone(phone['token'],dict(action='catalog'))
self.assertEqual(len(result['devices']),1);self.assertFalse(result['devices'][0]['power']['canStart'])
def test_phone_control_revocation_and_expiry(self):
phone=self.phone('测试家人');self.grant(phone);self.sample(0)
self.assertTrue(self.p.phone(phone['token'],dict(action='status',deviceId=self.key))['power']['canStart'])
self.p.web(self.owner,dict(action='grants',deviceId=self.key,grants=[]))
with self.assertRaises(app.Problem):self.p.phone(phone['token'],dict(action='status',deviceId=self.key))
self.grant(phone)
app.DB.execute('UPDATE member_location_shares SET expires=0 WHERE id=?',(phone['sid'],));app.DB.commit()
with self.assertRaises(app.Problem):self.p.phone(phone['token'],dict(action='catalog'))
def test_cross_household_and_device_move_fail_closed(self):
self.sample(0)
with self.assertRaises(app.Problem):self.p.read(self.other,self.key)
phone=self.phone('本人');self.grant(phone);self.command()
app.save_object('devices',dict(self.device,familyId=self.bid))
with self.assertRaises(app.Problem):self.p.phone(phone['token'],dict(action='status',deviceId=self.key))
with patch.object(self.p,'wake') as wake:
self.p.tick();wake.assert_not_called()
def test_grant_candidates_are_active_and_family_scoped(self):
own=self.phone('本家庭');other=self.phone('其他家庭',self.other)
rows=self.p.read(self.owner,self.key)['candidates']
self.assertIn(own['member']['personId'],[r['personId'] for r in rows])
self.assertNotIn(other['member']['personId'],[r['personId'] for r in rows])
with self.assertRaises(app.Problem):self.grant(other)
def test_readonly_web_user_cannot_grant_or_control(self):
self.sample(0);user=self.members[self.aid]
self.assertFalse(self.p.read(user,self.key)['power']['canStart'])
with self.assertRaises(app.Problem):self.command(user=user)
with self.assertRaises(app.Problem):self.p.web(user,dict(action='grants',deviceId=self.key,grants=[]))
def test_routes_and_inventory_managed_projection(self):
self.sample(0)
code,body=self.request('/api/device-power?id='+self.key)
self.assertEqual(code,200);self.assertTrue(body['power']['managed'])
self.assertTrue(app.INVENTORY.display(self.device)['powerManaged'])
self.assertNotIn(self.profile['secret'],json.dumps(body))