Files
rust-discovery/deploy/opnsense/test_agent.py
2026-11-19 20:55:29 +01:00

81 lines
4.1 KiB
Python

"""Run from the protocol-builder venv: python test_agent.py <built agent.pyz>."""
import importlib.util
import os
from pathlib import Path
import sqlite3
import sys
import tempfile
import unittest
from unittest.mock import patch
import uuid
sys.path.insert(0,sys.argv.pop(1))
spec = importlib.util.spec_from_file_location('opn_channel', Path(__file__).with_name('agent.py'))
a = importlib.util.module_from_spec(spec)
spec.loader.exec_module(a)
class Reconnect(unittest.TestCase):
def test_piggybacked_work_requires_same_authenticated_channel_and_exact_receipt(self):
e=a.pb.Envelope(protocol_major=1,enrollment_generation=1,connection_generation=3,
agent_id=str(uuid.uuid4()),boot_id=str(uuid.uuid4()),sequence=42,message_id=str(uuid.uuid4()))
ack=a.pb.Envelope();ack.CopyFrom(e);ack.ack.message_id=e.message_id
offer=a.pb.Envelope();offer.CopyFrom(e);offer.job_offer.job_id=str(uuid.uuid4())
batch=a.pb.MessageBatch(protocol_major=1,messages=[ack,offer])
self.assertEqual(a.check_reply(batch,e,'ack'),ack)
batch.messages[1].connection_generation=2
with self.assertRaisesRegex(ValueError,'identity'): a.check_reply(batch,e,'ack')
del batch.messages[1:]
batch.messages[0].ack.message_id=str(uuid.uuid4())
with self.assertRaisesRegex(ValueError,'unconfirmed'): a.check_reply(batch,e,'ack')
def test_lost_ack_keeps_original_identity_after_restart(self):
with tempfile.TemporaryDirectory() as temp:
db = sqlite3.connect(':memory:')
db.executescript('CREATE TABLE sequence(id INTEGER PRIMARY KEY,n INTEGER);INSERT INTO sequence VALUES(1,0);'
'CREATE TABLE pending(id INTEGER PRIMARY KEY,envelope BLOB,observed INTEGER);')
cache = Path(temp)/'inventory.json'
cache.write_text('{}')
identity = {'agent_id':str(uuid.uuid4())}
instance = str(uuid.uuid4())
captures = []
generation = 0
def gateway(_ctx,path,data,media):
nonlocal generation
req = a.pb.MessageBatch.FromString(data).messages[0]
reply = a.pb.Envelope()
reply.CopyFrom(req)
kind = req.WhichOneof('payload')
if kind == 'client_hello':
generation += 1
reply.connection_generation = generation
reply.server_hello.CopyFrom(a.pb.ServerHello(connection_generation=generation,max_message_bytes=1024*1024))
else:
if kind == 'inventory_snapshot':
captures.append(req)
if len(captures)==1: raise OSError('lost ACK')
reply.ack.CopyFrom(a.pb.Ack(message_id=req.message_id))
return a.pb.MessageBatch(protocol_major=1,messages=[reply]).SerializeToString()
with patch.object(a,'context'), patch.object(a,'renew',return_value=False), \
patch.object(a,'post',gateway), patch.object(a,'Path',return_value=cache), \
patch.object(a,'usage',return_value=(a.pb.SystemUsage(),[])), \
patch.object(a.time,'clock_gettime',return_value=100), \
patch.object(a.time,'CLOCK_UPTIME',1,create=True), patch.object(a.time,'sleep',side_effect=StopIteration):
with self.assertRaises(OSError):
a.session(db,identity,str(uuid.uuid4()),instance)
self.assertIsNotNone(db.execute('SELECT 1 FROM pending').fetchone())
os.unlink(cache)
with self.assertRaises(StopIteration):
a.session(db,identity,str(uuid.uuid4()),instance)
self.assertIsNone(db.execute('SELECT 1 FROM pending').fetchone())
self.assertEqual(len(captures),2)
self.assertNotEqual(captures[0].connection_generation,captures[1].connection_generation)
captures[0].connection_generation=captures[1].connection_generation
self.assertEqual(captures[0],captures[1])
if __name__=='__main__':
unittest.main()