"""Run from the protocol-builder venv: python test_agent.py .""" 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]) def test_broken_worker_pauses_scripts_but_keeps_heartbeat(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);') worker = Path(temp)/'worker' # Same effect as a loader failure: exits before printing "ready". worker.write_text('#!/bin/sh\nexit 1\n') worker.chmod(0o755) binding = Path(temp)/'binding.json' binding.write_text('{}') seen = [] def gateway(_ctx,path,data,media): req = a.pb.MessageBatch.FromString(data).messages[0] reply = a.pb.Envelope() reply.CopyFrom(req) kind = req.WhichOneof('payload') seen.append((kind, list(req.client_hello.capabilities))) if kind == 'client_hello': reply.connection_generation = len(seen) reply.server_hello.CopyFrom(a.pb.ServerHello(connection_generation=len(seen),max_message_bytes=1024*1024)) else: 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,'WORKER',worker), patch.object(a,'BINDING',binding), \ patch.object(a,'worker_paused_until',0.0), \ 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): identity = {'agent_id':str(uuid.uuid4()),'asset_id':str(uuid.uuid4())} with self.assertRaisesRegex(ValueError,'telemetry continues'): a.session(db,identity,str(uuid.uuid4()),str(uuid.uuid4())) with self.assertRaises(StopIteration): a.session(db,identity,str(uuid.uuid4()),str(uuid.uuid4())) self.assertEqual([k for k,_ in seen],['client_hello','client_hello','heartbeat']) self.assertIn('run_script',seen[0][1]) self.assertEqual(seen[1][1],['heartbeat/1','opnsense.base/1']) if __name__=='__main__': unittest.main()