Files

179 lines
11 KiB
Python
Raw Permalink Normal View History

"""No-login member phones: independent viewing, explicit consent and cadence."""
import http.client
import json
import time
import unittest
import test_households as fixtures
app = fixtures.app
class PhoneLocationTests(unittest.TestCase):
setUp = fixtures.HouseholdTests.setUp
stop_server = fixtures.HouseholdTests.stop_server
def phone(self, name, owner=None):
owner = owner or self.owner
member = app.MEMBERS.save(owner, dict(name=name))
code = app.LOCATIONS.manage(owner, dict(action='pair', memberId=member['id'], viewOnly=True))['code']
grant = app.LOCATIONS.pair(dict(code=code, consentProtocol=3), 'fixture')
sid = app.DB.execute('SELECT id FROM member_location_shares WHERE member_id=?', (member['id'],)).fetchone()[0]
return dict(grant, sid=sid, member=member)
def configure(self, phone, **options):
body = dict(action='configure', consent=True, receipt=phone['receipt'],
viewerIds=[], displayIds=[], phoneIds=[], intervalSeconds=300)
body.update(options)
result = app.LOCATIONS.native(phone['token'], body)
phone['receipt'] = result['receipt']
return result
def start(self, phone):
return app.LOCATIONS.native(phone['token'], dict(action='start', consent=True, receipt=phone['receipt']))
def point(self, phone):
app.LOCATIONS.native(phone['token'], dict(action='update', signal='available',
position=dict(latitude=36.61, longitude=117.1, accuracy=9, at=time.time())))
def listing(self, phone):
return app.LOCATIONS.native(phone['token'], dict(action='list'))['items']
def test_pair_only_needs_no_account_or_location(self):
phone = self.phone('妈妈')
self.assertTrue(phone['viewOnly'])
self.assertEqual(self.listing(phone), [])
self.assertFalse(any(u.get('personId') == phone['member']['personId'] for u in app.objects('users')))
with self.assertRaises(app.Problem): self.start(phone)
with self.assertRaises(app.Problem): self.point(phone)
settings = app.LOCATIONS.native(phone['token'], dict(action='settings'))
self.assertEqual(settings['intervalSeconds'], 300)
self.assertEqual(settings['phoneIds'], [])
self.assertFalse(app.LOCATIONS.latest)
def test_viewing_does_not_require_sharing_and_admin_has_no_bypass(self):
viewer, source, stranger = [self.phone(name) for name in ('儿子', '妈妈', '另一位家人')]
self.configure(source, phoneIds=[viewer['sid']])
self.start(source); self.point(source)
self.assertEqual([r['name'] for r in self.listing(viewer)], ['妈妈'])
self.assertEqual(self.listing(stranger), [])
self.assertEqual(app.LOCATIONS.listing(self.aid, user=self.root), [])
self.assertEqual(len(self.listing(source)), 1) # Can view one's own current fix.
app.LOCATIONS.native(viewer['token'], dict(action='stop'))
self.assertEqual(len(self.listing(viewer)), 1)
app.LOCATIONS.native(source['token'], dict(action='stop'))
self.assertEqual(self.listing(viewer), [])
def test_consent_receipt_interval_and_first_immediate_fix(self):
source, viewer = self.phone('本人'), self.phone('查看人')
for seconds in (10, 60, 300):
result = self.configure(source, phoneIds=[viewer['sid']], intervalSeconds=seconds)
self.assertEqual(result['intervalSeconds'], seconds)
self.assertEqual(self.start(source)['intervalSeconds'], seconds)
self.point(source) # First upload cannot hit the ten-second limit.
self.assertEqual(self.listing(viewer)[0]['status'], 'live')
app.LOCATIONS.native(source['token'], dict(action='stop'))
for seconds in (True, '60', 0, 9, 59, 301, 60.0):
with self.subTest(seconds=seconds), self.assertRaises(app.Problem):
self.configure(source, phoneIds=[viewer['sid']], intervalSeconds=seconds)
for extra in (dict(consent=False), dict(receipt='old')):
body = dict(action='configure', consent=True, receipt=source['receipt'], phoneIds=[viewer['sid']])
body.update(extra)
with self.assertRaises(app.Problem): app.LOCATIONS.native(source['token'], body)
def test_configuration_stops_old_share_until_explicit_restart(self):
source, viewer = self.phone('本人'), self.phone('查看人')
self.configure(source, phoneIds=[viewer['sid']]); self.start(source); self.point(source)
old_receipt = source['receipt']
self.configure(source, viewerIds=[self.members[self.aid]['id']], intervalSeconds=60)
self.assertNotEqual(old_receipt, source['receipt'])
self.assertEqual(self.listing(viewer), [])
self.assertNotIn(source['sid'], app.LOCATIONS.latest)
with self.assertRaises(app.Problem): self.point(source)
with self.assertRaises(app.Problem):
app.LOCATIONS.native(source['token'], dict(action='start', consent=True, receipt=old_receipt))
self.start(source); self.point(source)
self.assertEqual(self.listing(viewer), [])
self.assertEqual(len(app.LOCATIONS.listing(self.aid, user=self.members[self.aid])), 1)
def test_two_explicit_modes_and_changed_consent(self):
source,viewer=self.phone('本人'),self.phone('查看人')
result=self.configure(source,phoneIds=[viewer['sid']],sharingMode='scheduled',sampleIntervalSeconds=3600,intervalSeconds=86400)
self.assertEqual((result['sharingMode'],result['sampleIntervalSeconds'],result['intervalSeconds']),('scheduled',3600,86400))
self.start(source);self.point(source)
self.assertEqual(self.listing(viewer)[0]['sharingMode'],'scheduled')
old=source['receipt']
result=self.configure(source,phoneIds=[viewer['sid']],sharingMode='realtime',sampleIntervalSeconds=3600,intervalSeconds=86400)
self.assertNotEqual(old,result['receipt']);self.assertEqual(self.listing(viewer),[])
self.assertEqual((result['sampleIntervalSeconds'],result['intervalSeconds']),(10,10))
started=self.start(source);self.assertEqual(started['sharingMode'],'realtime')
self.assertEqual(app.LOCATIONS.native(source['token'],dict(action='settings'))['sharingMode'],'realtime')
for bad in ('continuous','',None,True,{},[]):
with self.subTest(mode=bad),self.assertRaises(app.Problem):self.configure(source,phoneIds=[viewer['sid']],sharingMode=bad)
def test_other_family_self_and_invalid_recipients_rejected(self):
source, foreign = self.phone('本人'), self.phone('乙家庭', self.other)
for options in (dict(phoneIds=[foreign['sid']]), dict(phoneIds=[source['sid']]),
dict(viewerIds=[self.other['id']]), dict(phoneIds=['missing']),
dict(phoneIds='not-a-list'), dict(phoneIds=[])):
with self.subTest(options=options), self.assertRaises(app.Problem): self.configure(source, **options)
self.assertEqual(app.LOCATIONS.listing(self.aid, phone_id=foreign['sid']), [])
settings = app.LOCATIONS.native(source['token'], dict(action='settings'))
self.assertNotIn(foreign['sid'], [p['id'] for p in settings['phones']])
def test_repaired_phone_does_not_inherit_viewer_consent(self):
source, viewer = self.phone('本人'), self.phone('查看人')
self.configure(source, phoneIds=[viewer['sid']]); self.start(source); self.point(source)
self.assertEqual(len(self.listing(viewer)), 1)
code = app.LOCATIONS.manage(self.owner, dict(action='pair', memberId=viewer['member']['id'], viewOnly=True))['code']
replacement = app.LOCATIONS.pair(dict(code=code, consentProtocol=3), 'fixture')
with self.assertRaises(app.Problem): self.listing(viewer)
self.assertEqual(self.listing(replacement), [])
def test_revoked_inactive_or_expired_viewer_cannot_read(self):
source, viewer = self.phone('本人'), self.phone('查看人')
self.configure(source, phoneIds=[viewer['sid']]); self.start(source); self.point(source)
changed = app.MEMBERS.save(self.owner, dict(viewer['member'], status='historical'))
with self.assertRaises(app.Problem): self.listing(viewer)
app.MEMBERS.save(self.owner, dict(changed, status='active'))
app.DB.execute('UPDATE member_location_shares SET expires=? WHERE id=?', (time.time()-1, viewer['sid']))
with self.assertRaises(app.Problem): self.listing(viewer)
app.LOCATIONS.native(source['token'], dict(action='revoke'))
with self.assertRaises(app.Problem): self.listing(source)
def test_old_protocol_cannot_consume_new_pair_code(self):
member = app.MEMBERS.save(self.owner, dict(name='新手机'))
code = app.LOCATIONS.manage(self.owner, dict(action='pair', memberId=member['id'], viewOnly=True))['code']
with self.assertRaises(app.Problem): app.LOCATIONS.pair(dict(code=code, consentProtocol=2), 'fixture')
grant = app.LOCATIONS.pair(dict(code=code, consentProtocol=3), 'fixture')
self.assertTrue(grant['viewOnly'])
def test_native_http_has_no_cookie_and_requires_exact_phone_token(self):
source, viewer = self.phone('本人'), self.phone('查看人')
self.configure(source, phoneIds=[viewer['sid']]); self.start(source); self.point(source)
for token, expected in ((viewer['token'], 200), ('', 401), ('invalid', 401),
(self.tokens[self.root['id']], 401)):
connection = http.client.HTTPConnection(*self.server.server_address, timeout=3)
connection.request('POST', '/api/location/update', json.dumps(dict(action='list')),
{'Authorization': 'Bearer '+token, 'Content-Type': 'application/json'})
response = connection.getresponse(); payload = json.loads(response.read()); connection.close()
self.assertEqual(response.status, expected)
if expected == 200: self.assertEqual(payload['items'][0]['name'], '本人')
raw = '\n'.join(app.DB.iterdump())
for secret in (viewer['token'], source['token'], '36.61'): self.assertNotIn(secret, raw)
def test_permission_loss_and_staleness_hide_coordinates(self):
source, viewer = self.phone('本人'), self.phone('查看人')
self.configure(source, phoneIds=[viewer['sid']]); self.start(source); self.point(source)
app.LOCATIONS.latest[source['sid']]['seen'] = 0
app.LOCATIONS.native(source['token'], dict(action='update', signal='permission_denied'))
self.assertIsNone(self.listing(viewer)[0]['position'])
app.LOCATIONS.latest[source['sid']]['seen'] = 0
self.point(source)
app.LOCATIONS.latest[source['sid']]['seen'] = time.time()-901
row = self.listing(viewer)[0]
self.assertEqual(row['status'], 'stale')
self.assertIsNone(row['position'])
if __name__ == '__main__': unittest.main()