WIP: isolate durable offline settings in dashboard bridge

Add opt-in loopback SQLite outbox and native configuration overlay. Validate clocks, grants and operator origin; never queue hardware actions. Fifteen store/runtime tests pass; no stage release or installation.
This commit is contained in:
Andrei Smaliak 2026-11-15 10:52:42 +01:00
parent d2f96225cb
commit 8430b8ddda
7 changed files with 627 additions and 4 deletions

View File

@ -0,0 +1,12 @@
# Optional dashboard bridge offline editing snapshot — 2026-11-15
Backlog #1 remains WIP. An explicit OFFLINE_HMI_CONFIG enables the isolated SQLite
settings/outbox/sync module on a loopback-only bridge. Current default behavior is
retained without that setting. Hardware actions are not queued as offline edits.
Native MQTT prefix/identity are read from the registered configuration.
Verified: 15 Python store/runtime tests, including durable restart/retry, transaction
interruption, clock trust, grant scope, local-origin/operator guards and rejection of
hardware actions. See AITS docs/architecture/offline-irrigation-hmi.md for remaining
acceptance gates. This is source synchronization only: no stage version/feed update
or OS/bridge installation on physical devices.

View File

@ -104,12 +104,13 @@ class BridgeState:
class MqttBridge:
def __init__(self, mqtt_url, device_id, state):
def __init__(self, mqtt_url, device_id, state, prefix="it-screen/dev"):
self.mqtt_url = mqtt_url
self.device_id = device_id
self.state = state
self.host, self.port = parse_mqtt_url(mqtt_url)
self.state_topic = f"it-screen/dev/client/pub/component/plays/{device_id}"
self.topic_prefix = prefix
self.state_topic = f"{prefix}/client/pub/component/plays/{device_id}"
self._publish_lock = threading.Lock()
self._ready = threading.Event()
self._client = None
@ -155,7 +156,7 @@ class MqttBridge:
def publish_event(self, component_id, value, title):
if self._client is None:
raise RuntimeError("MQTT client is unavailable")
topic = f"it-screen/dev/client/sub/event/push/{component_id}"
topic = f"{self.topic_prefix}/client/sub/event/push/{component_id}"
payload = {
"action": "push",
"value": str(value),
@ -273,6 +274,7 @@ class Handler(BaseHTTPRequestHandler):
self.end_headers()
def do_GET(self):
if self.app.offline_edit and self.app.offline_edit.handle(self): return
parsed = urlparse(self.path)
if parsed.path == "/api/health":
snapshot = self.app.state.health_snapshot()
@ -303,6 +305,7 @@ class Handler(BaseHTTPRequestHandler):
self.send_json({"ok": False, "error": "Not found"}, code=404)
def do_POST(self):
if self.app.offline_edit and self.app.offline_edit.handle(self): return
parsed = urlparse(self.path)
if parsed.path != "/api/event":
self.send_json({"ok": False, "error": "Not found"}, code=404)
@ -357,7 +360,30 @@ class App:
self.mqtt_url = os.environ.get("DASHBOARD_BRIDGE_MQTT_URL", DEFAULT_MQTT_URL).strip() or DEFAULT_MQTT_URL
self.device_id = os.environ.get("DASHBOARD_BRIDGE_DEVICE_ID", "").strip() or device_id_from_hostname()
self.state = BridgeState()
self.mqtt_bridge = MqttBridge(self.mqtt_url, self.device_id, self.state)
offline_config = os.environ.get('OFFLINE_HMI_CONFIG', '').strip()
prefix = 'it-screen/dev' # Compatibility mode; new HMI never guesses this prefix.
if offline_config:
with open(offline_config) as stream: hmi_config = json.load(stream)
with open(hmi_config['native_config_path']) as stream: native_config = json.load(stream)
prefix = str(native_config['mqtt']['prefix']).strip('/')
if not prefix or len(prefix)>200 or not re.fullmatch(r'[A-Za-z0-9_./-]+',prefix): raise RuntimeError('Invalid native MQTT prefix')
self.device_id = str(native_config['username'])
self.mqtt_bridge = MqttBridge(self.mqtt_url, self.device_id, self.state, prefix)
self.offline_edit = None
offline_config = os.environ.get('OFFLINE_HMI_CONFIG', '').strip()
if offline_config:
if self.bind not in ('127.0.0.1', '::1'):
raise RuntimeError('Offline editing requires a loopback-only bridge')
from offline_edit.runtime import Runtime
def invalidate(topic, payload):
if self.mqtt_bridge._client is None or not self.mqtt_bridge.is_connected():
raise RuntimeError('Local MQTT is not connected; settings are durable but not applied')
result = self.mqtt_bridge._client.publish(topic, json.dumps(payload), qos=1, retain=False)
if result.rc != mqtt_err_success(): raise RuntimeError('Local configuration notification failed')
deadline=time.monotonic()+2.0
while not result.is_published() and time.monotonic()<deadline: time.sleep(0.02)
if not result.is_published(): raise RuntimeError('Local broker acknowledgement timed out')
self.offline_edit = Runtime(offline_config, invalidate)
self.httpd = ThreadingHTTPServer((self.bind, self.port), Handler)
self.httpd.app = self
@ -366,9 +392,11 @@ class App:
f"starting http bind={self.bind} port={self.port} device_id={self.device_id} mqtt_url={self.mqtt_url}"
)
self.mqtt_bridge.start()
if self.offline_edit: self.offline_edit.start()
try:
self.httpd.serve_forever()
finally:
if self.offline_edit: self.offline_edit.stop()
self.mqtt_bridge.stop()

View File

@ -0,0 +1 @@
"""Optional offline settings module; importing the legacy bridge does not enable it."""

View File

@ -0,0 +1,168 @@
"""Opt-in transport adapter for the existing bridge; no independent scheduler."""
import base64
import gzip
import hmac
import json
import secrets
import threading
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from .store import Store
LOCAL_HOSTS = {'localhost', '127.0.0.1', '::1'}
NATIVE_PATHS = {'/v2/device': 'native_config', '/v2/device/layout': 'native_frames'}
class Runtime:
def __init__(self, config_path, publish_invalidation):
self.config = json.loads(Path(config_path).read_text())
credentials = json.loads(Path(self.config['native_config_path']).read_text())
self.authorization = 'Basic ' + base64.b64encode((credentials['username'] + ':' + credentials['password']).encode()).decode()
self.device_id = int(credentials['id'])
self.prefix = str(credentials['mqtt']['prefix']).strip('/')
self.username = str(credentials['username'])
self.publish_invalidation = publish_invalidation
self.store = Store(self.config['database'])
Path(self.config['database']).chmod(0o600)
self.session = secrets.token_urlsafe(32)
self.stop_event = threading.Event()
self.online, self.last_error = False, 'not_connected'
self.last_invalidated = None
self.cloud_api = self._origin(self.config['cloud_api_url'])
self.native_base = self._origin(self.config['native_base_url'])
self.assets = Path(self.config['assets']).resolve()
@staticmethod
def _origin(value):
parsed = urllib.parse.urlsplit(value)
if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
raise ValueError('Configure an explicit credential-free upstream URL')
# Public transports require TLS; HTTP is limited to private deployment addresses.
if parsed.scheme == 'http':
import ipaddress
try:
if not ipaddress.ip_address(parsed.hostname).is_private: raise ValueError('Public upstream requires TLS')
except ValueError:
if parsed.hostname not in LOCAL_HOSTS: raise ValueError('Public upstream requires TLS')
return value.rstrip('/')
def _request(self, base, path, body=None):
data = json.dumps(body).encode() if body is not None else None
request = urllib.request.Request(base + path, data=data, headers={'Authorization': self.authorization, 'Content-Type': 'application/json', 'Accept': 'application/json'})
with urllib.request.urlopen(request, timeout=8) as response:
if response.status != 200: raise OSError('Unexpected API response')
reader=gzip.GzipFile(fileobj=response) if response.headers.get('Content-Encoding','').lower()=='gzip' else response
body=reader.read(4*1024*1024+1)
if len(body)>4*1024*1024: raise ValueError('Platform response exceeds the snapshot limit')
payload = json.loads(body)
return payload.get('data', payload) if isinstance(payload, dict) else payload
def synchronize(self):
try:
# Refresh grants before sending queued operations. Revoked scope never replays.
snapshot = self._request(self.cloud_api, '/offline-edit/snapshot')
self.store.ingest(snapshot)
for operation in self.store.pending():
result = self._request(self.cloud_api, '/offline-edit/operations', operation)
self.store.acknowledge(result)
self.online, self.last_error = True, ''
except (OSError, ValueError, KeyError, urllib.error.HTTPError) as error:
self.online = False
self.last_error = 'authorization_failed' if getattr(error, 'code', None) in (401, 403) else 'cloud_unavailable'
def notify_desired(self):
try: revision=self._cache('desired_revision')
except OSError: return True
if revision==self.last_invalidated: return True
try:
self.publish_invalidation(self.prefix+'/client/sub/action/'+self.username, {'action':'update','model':'config','revision':revision})
self.last_invalidated=revision
return True
except (OSError,RuntimeError):
return False # Durable settings remain visible; a later tick retries invalidation only.
def start(self):
def loop():
while not self.stop_event.is_set():
self.synchronize()
self.notify_desired()
self.stop_event.wait(10 if self.online else 15)
self.thread = threading.Thread(target=loop, name='offline-edit-sync', daemon=True)
self.thread.start()
def stop(self):
self.stop_event.set()
if hasattr(self, 'thread'): self.thread.join(timeout=9)
def _cache(self, key, value=None):
with self.store.transaction() as db:
if value is not None:
db.execute('INSERT OR REPLACE INTO metadata VALUES(?,?)', (key, json.dumps(value)))
return value
row = db.execute('SELECT value FROM metadata WHERE key=?', (key,)).fetchone()
if row is None: raise OSError('No cached native configuration')
return json.loads(row[0])
def native(self, path, query):
if path not in NATIVE_PATHS: raise PermissionError('Native route is outside the configuration scope')
name = NATIVE_PATHS[path]
try:
payload = self._request(self.native_base, path + ('?' + query if query else ''))
self._cache(name, payload)
except (OSError, ValueError):
payload = self._cache(name)
return self.store.overlay(payload) if name == 'native_frames' else payload
def _local(self, handler):
host = urllib.parse.urlsplit('http://' + handler.headers.get('Host', '')).hostname
if handler.client_address[0] not in ('127.0.0.1', '::1') or host not in LOCAL_HOSTS:
raise PermissionError('HMI is available only on the local kiosk')
def _write_allowed(self, handler):
self._local(handler)
origin = urllib.parse.urlsplit(handler.headers.get('Origin', ''))
host = urllib.parse.urlsplit('http://' + handler.headers.get('Host', ''))
if origin.scheme != 'http' or origin.netloc != host.netloc or origin.hostname not in LOCAL_HOSTS:
raise PermissionError('Foreign HMI origin')
if not hmac.compare_digest(handler.headers.get('X-HMI-Session', ''), self.session):
raise PermissionError('Local operator session required')
if handler.headers.get('Content-Type', '').split(';')[0] != 'application/json':
raise ValueError('Expected application/json')
def handle(self, handler):
parsed = urllib.parse.urlsplit(handler.path)
if not (parsed.path.startswith('/hmi') or parsed.path.startswith('/native/')): return False
try:
self._local(handler)
if parsed.path.startswith('/native/'):
if handler.command != 'GET' or not hmac.compare_digest(handler.headers.get('Authorization', ''), self.authorization):
handler.send_response(401); handler.send_header('WWW-Authenticate', 'Basic realm="IOMATEX native configuration"'); handler.end_headers(); return True
handler.send_json(self.native(parsed.path[len('/native'):], parsed.query)); return True
query = urllib.parse.parse_qs(parsed.query)
if handler.command == 'GET' and parsed.path == '/hmi/api/session':
handler.send_json({'session': self.session, 'online': self.online, 'error': self.last_error}); return True
if handler.command == 'GET' and parsed.path == '/hmi/api/component':
handler.send_json(self.store.view(int(query['id'][0]))); return True
if handler.command == 'POST' and parsed.path == '/hmi/api/settings':
self._write_allowed(handler)
size = int(handler.headers.get('Content-Length', '0'))
if not 0 < size <= 65536: raise ValueError('Settings operation is too large or empty')
value = json.loads(handler.rfile.read(size))
operation = self.store.edit(int(value['component_id']), str(value['group']), value['value'])
# Existing local MQTT subscriber + native configuration application own execution.
applied=self.notify_desired()
handler.send_json({'operation': operation, 'status': 'saved_locally', 'application_status':'notification_sent' if applied else 'pending'}); return True
if handler.command == 'GET' and parsed.path in ('/hmi', '/hmi/'):
body = (self.assets / 'index.html').read_bytes()
handler.send_response(200); handler.send_header('Content-Type', 'text/html; charset=utf-8'); handler.send_header('Cache-Control', 'no-store'); handler.send_header('Content-Length', str(len(body))); handler.end_headers(); handler.wfile.write(body); return True
handler.send_json({'error': 'not_found'}, code=404)
except PermissionError as error:
handler.send_json({'error': str(error)}, code=403)
except (ValueError, KeyError, TypeError) as error:
handler.send_json({'error': str(error)}, code=422)
except OSError:
handler.send_json({'error': 'local_configuration_unavailable'}, code=503)
return True

View File

@ -0,0 +1,206 @@
"""Durable desired settings and outbox. Never queues physical Start/Stop actions."""
import copy
import json
import math
import sqlite3
import time
import uuid
from contextlib import contextmanager
from pathlib import Path
GROUPS = {
'duration': ('duration',), 'active': ('active',),
'schedule': ('valid_from', 'valid_to', 'valid_hour_from', 'valid_hour_to', 'days_week'),
'conditions': ('triggers', 'start_condition_operator', 'per_hour'),
}
def boot_id():
try:
return Path('/proc/sys/kernel/random/boot_id').read_text().strip()
except OSError:
return None # Unknown continuity must not invent a trusted timestamp.
def validate(group, value, generator='sync'):
if group not in GROUPS or not isinstance(value, dict) or set(value) != set(GROUPS[group]):
raise ValueError('Unsupported or incomplete atomic settings group')
if group == 'duration':
number = value['duration']
if isinstance(number, bool) or not isinstance(number, (int, float)) or not math.isfinite(number) or not 3 <= number <= (3600 if generator == 'sync' else 86400):
raise ValueError('Duration exceeds the generator limit')
if group == 'active' and (type(value['active']) is not int or value['active'] not in (0, 1)):
raise ValueError('Activity must be 0 or 1')
if group == 'schedule' and any(v is not None and not isinstance(v, str) for v in value.values()):
raise ValueError('Invalid schedule value')
if group == 'conditions' and (not isinstance(value['triggers'], dict) or value['start_condition_operator'] not in ('AND', 'OR') or type(value['per_hour']) is not int or value['per_hour'] < 0):
raise ValueError('Invalid conditions')
return copy.deepcopy(value)
class Store:
def __init__(self, path, wall=time.time, monotonic=time.monotonic, boot=boot_id):
self.path, self.wall, self.monotonic, self.boot = str(path), wall, monotonic, boot
Path(self.path).parent.mkdir(parents=True, exist_ok=True)
with self.transaction() as db:
db.executescript('''
CREATE TABLE IF NOT EXISTS components(id INTEGER PRIMARY KEY, payload TEXT NOT NULL, anchor_monotonic REAL NOT NULL, anchor_wall REAL NOT NULL, boot_id TEXT);
CREATE TABLE IF NOT EXISTS outbox(id TEXT PRIMARY KEY, component_id INTEGER NOT NULL, group_name TEXT NOT NULL, payload TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', result TEXT, sequence INTEGER NOT NULL);
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY, value TEXT NOT NULL);
''')
@contextmanager
def transaction(self):
db = sqlite3.connect(self.path, timeout=10, isolation_level=None)
db.row_factory = sqlite3.Row
try:
db.execute('PRAGMA journal_mode=WAL')
db.execute('PRAGMA synchronous=FULL')
db.execute('BEGIN IMMEDIATE')
yield db
if db.in_transaction:
db.commit()
except BaseException:
if db.in_transaction:
db.rollback()
raise
finally:
db.close()
def ingest(self, snapshot):
if snapshot.get('schema_version') != 1 or not isinstance(snapshot.get('components'), list):
raise ValueError('Unsupported snapshot')
with self.transaction() as db:
device_id = int(snapshot['device_id'])
old = db.execute("SELECT value FROM metadata WHERE key='device_id'").fetchone()
if old and int(old[0]) != device_id:
raise ValueError('Device identity changed; use a separate database')
db.execute("INSERT OR REPLACE INTO metadata VALUES('device_id',?)", (str(device_id),))
ids = []
for component in snapshot['components']:
component_id = int(component['id'])
ids.append(component_id)
db.execute('INSERT OR REPLACE INTO components VALUES(?,?,?,?,?)', (component_id, json.dumps(component), self.monotonic(), self.wall(), self.boot()))
# A complete server grant snapshot is authoritative for deletions and revocations.
allowed = set(ids)
for row in db.execute('SELECT id FROM components').fetchall():
if row['id'] not in allowed:
db.execute('DELETE FROM components WHERE id=?', (row['id'],))
db.execute("UPDATE outbox SET status='scope_removed' WHERE component_id=? AND status='pending'", (row['id'],))
def _component(self, db, component_id):
row = db.execute('SELECT * FROM components WHERE id=?', (component_id,)).fetchone()
if not row:
raise PermissionError('Component is not granted')
data = json.loads(row['payload'])
# Use the advancing server anchor when OS monotonic continuity is intact.
elapsed = self.monotonic() - row['anchor_monotonic']
anchored = data['anchor']['server_time_ms'] / 1000 + elapsed
now = max(self.wall(), anchored) if row['boot_id'] == self.boot() else self.wall()
if now >= int(data['grant_expires_at']):
raise PermissionError('Editing grant expired')
return row, data
def view(self, component_id):
with self.transaction() as db:
_, data = self._component(db, component_id)
pending = db.execute("SELECT * FROM outbox WHERE component_id=? AND status IN ('pending','clock_conflict','revision_conflict') ORDER BY sequence", (component_id,)).fetchall()
data['pending'] = []
for row in pending:
op = json.loads(row['payload'])
data['groups'][row['group_name']]['value'] = op['value']
data['pending'].append({'operation_id': row['id'], 'group': row['group_name'], 'status': row['status']})
return data
def edit(self, component_id, group, value):
with self.transaction() as db:
row, component = self._component(db, component_id)
value = validate(group, value, component.get('generator_type', 'sync'))
elapsed = self.monotonic() - row['anchor_monotonic']
continuity = self.boot() is not None and row['boot_id'] == self.boot() and elapsed >= 0
wall_elapsed = self.wall() - row['anchor_wall']
trusted = continuity and abs(wall_elapsed - elapsed) <= 300
elapsed_ms = max(0, round(elapsed * 1000))
sequence = db.execute('SELECT COALESCE(MAX(sequence),0)+1 FROM outbox').fetchone()[0]
operation = {
'schema_version': 1, 'operation_id': uuid.uuid4().hex,
'device_id': int(db.execute("SELECT value FROM metadata WHERE key='device_id'").fetchone()[0]),
'component_id': component_id, 'grant_id': component['grant_id'],
'group': group, 'value': value,
'base_revision': int(component['groups'][group]['clock']['revision']),
'anchor_id': component['anchor']['id'], 'elapsed_ms': elapsed_ms,
'created_at_ms': int(component['anchor']['server_time_ms']) + elapsed_ms,
'clock_trusted': trusted,
}
# One transaction owns both the desired overlay and the retryable operation.
db.execute('INSERT INTO outbox(id,component_id,group_name,payload,sequence) VALUES(?,?,?,?,?)',
(operation['operation_id'], component_id, group, json.dumps(operation), sequence))
db.execute("INSERT OR REPLACE INTO metadata VALUES('desired_revision',?)", (json.dumps('offline-'+operation['operation_id']),))
return operation
def pending(self, limit=32):
with self.transaction() as db:
return [json.loads(r[0]) for r in db.execute("SELECT payload FROM outbox WHERE status='pending' ORDER BY sequence LIMIT ?", (min(32, max(1, limit)),))]
def acknowledge(self, result):
with self.transaction() as db:
row = db.execute('SELECT * FROM outbox WHERE id=?', (result['operation_id'],)).fetchone()
if not row:
raise ValueError('Unknown operation receipt')
op = json.loads(row['payload'])
if int(result['component_id']) != row['component_id'] or result['group'] != row['group_name']:
raise ValueError('Receipt identity mismatch')
if row['status'] != 'pending':
return # Repeated network acknowledgement is inert.
status = result['status']
if status not in ('accepted', 'superseded', 'clock_conflict', 'revision_conflict'):
raise ValueError('Unknown receipt status')
component_row = db.execute('SELECT payload FROM components WHERE id=?', (row['component_id'],)).fetchone()
if component_row and status in ('accepted', 'superseded'):
data = json.loads(component_row[0]); group = row['group_name']
canonical = result['canonical']
if int(canonical['clock']['revision']) >= int(data['groups'][group]['clock']['revision']):
data['groups'][group] = canonical
db.execute('UPDATE components SET payload=? WHERE id=?', (json.dumps(data), row['component_id']))
# ACK, canonical settings and the native fallback document are one
# durable commit. A power loss must not restore a pre-ACK duration.
cached = db.execute("SELECT value FROM metadata WHERE key='native_frames'").fetchone()
if cached:
document = json.loads(cached[0])
for layout in document.get('layouts', []):
for frame in layout.get('frames', []):
for model in frame.get('playlists', []):
for key in ('elements', 'diagnostic_elements'):
for element in model.get(key, []):
if int(element['id']) == row['component_id']:
element.update(canonical['value'])
if element.get('execution_eligibility', {}).get('eligible') is False:
element['active'] = 0
db.execute("UPDATE metadata SET value=? WHERE key='native_frames'", (json.dumps(document),))
db.execute('UPDATE outbox SET status=?,result=? WHERE id=?', (status, json.dumps(result), row['id']))
if status in ('accepted','superseded'):
db.execute("INSERT OR REPLACE INTO metadata VALUES('desired_revision',?)", (json.dumps('offline-ack-'+row['id']),))
def overlay(self, canonical):
payload = copy.deepcopy(canonical)
with self.transaction() as db:
ids = [r[0] for r in db.execute('SELECT id FROM components')]
values = {}
for component_id in ids:
try:
component = self.view(component_id)
dirty = {entry['group'] for entry in component['pending']}
values[component_id] = {k: v for name, group in component['groups'].items() if name in dirty for k, v in group['value'].items()}
except PermissionError:
continue
# No new component, runtime, model or hardware binding is invented here.
for layout in payload.get('layouts', []):
for frame in layout.get('frames', []):
for model in frame.get('playlists', []):
for key in ('elements', 'diagnostic_elements'):
for element in model.get(key, []):
if int(element['id']) in values:
element.update(values[int(element['id'])])
if element.get('execution_eligibility', {}).get('eligible') is False:
element['active'] = 0 # Never bypass the platform's unbound-output guard.
return payload

View File

@ -0,0 +1,88 @@
import io
import json
import sys
import tempfile
import time
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parents[1] / 'dashboard_bridge_core/backend'))
from offline_edit.runtime import Runtime
class Handler:
def __init__(self, path, method='GET', value=None, headers=None):
self.path, self.command = path, method
body = json.dumps(value).encode() if value is not None else b''
self.rfile = io.BytesIO(body)
self.client_address = ('127.0.0.1', 12345)
self.headers = {'Host':'127.0.0.1:8787', 'Origin':'http://127.0.0.1:8787',
'Content-Type':'application/json', 'Content-Length':str(len(body))}
self.headers.update(headers or {})
self.result, self.code = None, None
def send_json(self, value, code=200): self.result, self.code = value, code
class RuntimeTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory(); root = Path(self.tmp.name)
native = root / 'native.json'; native.write_text(json.dumps({'id':109,'username':'fixture-edge','password':'fixture-only','mqtt':{'prefix':'tenant/fixture'}}))
config = {'native_config_path':str(native),'database':str(root/'edits.sqlite3'),
'cloud_api_url':'http://127.0.0.1:8000/api','native_base_url':'http://127.0.0.1:8000','assets':str(root)}
self.config_path = root/'config.json'; self.config_path.write_text(json.dumps(config))
self.notifications=[]; self.runtime=Runtime(self.config_path,lambda *args:self.notifications.append(args))
now=int(time.time()*1000)
self.runtime.store.ingest({'schema_version':1,'device_id':109,'components':[{'id':22,'title':'Fixture','grant_id':'grant','grant_expires_at':now//1000+3600,'generator_type':'sync',
'anchor':{'id':'anchor','server_time_ms':now},'groups':{'duration':{'value':{'duration':15},'clock':{'revision':1}},'active':{'value':{'active':1},'clock':{'revision':1}}}}]})
def tearDown(self): self.tmp.cleanup()
def test_write_requires_local_host_origin_and_operator_session(self):
for headers in [{'Host':'attacker.example:8787'}, {'Origin':'http://attacker.example'}, {'X-HMI-Session':'wrong'}]:
h=Handler('/hmi/api/settings','POST',{'component_id':22,'group':'duration','value':{'duration':60}},headers)
self.runtime.handle(h); self.assertEqual(h.code,403)
self.assertEqual(self.runtime.store.pending(),[])
def test_hardware_actions_are_not_settings_or_retryable(self):
h=Handler('/hmi/api/settings','POST',{'component_id':22,'group':'start','value':{'active':1}}, {'X-HMI-Session':self.runtime.session})
self.runtime.handle(h);self.assertEqual(h.code,422);self.assertEqual(self.notifications,[])
def test_offline_native_document_uses_only_pending_overlay(self):
canonical={'layouts':[{'frames':[{'playlists':[{'elements':[{'id':22,'duration':15,'active':0}]}]}]}]}
self.runtime._cache('native_frames',canonical)
self.runtime._request=lambda *args,**kwargs: (_ for _ in ()).throw(OSError('offline'))
self.runtime.store.edit(22,'duration',{'duration':120})
result=self.runtime.native('/v2/device/layout','')
self.assertEqual(result['layouts'][0]['frames'][0]['playlists'][0]['elements'][0],{'id':22,'duration':120,'active':0})
with self.assertRaises(PermissionError):self.runtime.native('/v2/device/reboot','')
def test_durable_save_survives_broker_outage_and_notifies_on_restart(self):
self.runtime.publish_invalidation=lambda *args: (_ for _ in ()).throw(RuntimeError('broker offline'))
h=Handler('/hmi/api/settings','POST',{'component_id':22,'group':'duration','value':{'duration':120}}, {'X-HMI-Session':self.runtime.session})
self.runtime.handle(h);self.assertEqual(h.code,200);self.assertEqual(h.result['application_status'],'pending')
restarted=Runtime(self.config_path,lambda *args:self.notifications.append(args))
self.assertEqual(len(restarted.store.pending()),1)
self.assertTrue(restarted.notify_desired())
self.assertEqual(self.notifications[0][0],'tenant/fixture/client/sub/action/fixture-edge')
self.assertEqual(self.notifications[0][1]['model'],'config')
self.assertTrue(restarted.notify_desired());self.assertEqual(len(self.notifications),1)
def test_ack_and_native_fallback_commit_together(self):
document={'layouts':[{'frames':[{'playlists':[{'elements':[{'id':22,'duration':15,'active':0,'execution_eligibility':{'eligible':False}}]}]}]}]}
self.runtime._cache('native_frames',document)
operation=self.runtime.store.edit(22,'duration',{'duration':120})
self.runtime.store.acknowledge({'operation_id':operation['operation_id'],'component_id':22,'group':'duration','status':'accepted',
'canonical':{'value':{'duration':120},'clock':{'revision':2}}})
restarted=Runtime(self.config_path,lambda *args:None)
restarted._request=lambda *args: (_ for _ in ()).throw(OSError('offline'))
value=restarted.native('/v2/device/layout','')['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]
self.assertEqual(restarted.store.pending(),[])
self.assertEqual(value['duration'],120)
self.assertEqual(value['active'],0)
def test_plaintext_public_upstream_is_rejected(self):
for url in ['http://public.example','http://8.8.8.8','https://user:secret@example.test','file:///etc/passwd']:
with self.assertRaises(ValueError):Runtime._origin(url)
if __name__=='__main__':unittest.main()

View File

@ -0,0 +1,120 @@
import copy
import importlib.util
import sqlite3
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).parents[1] / 'dashboard_bridge_core/backend/offline_edit/store.py'
spec = importlib.util.spec_from_file_location('offline_store', ROOT)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
def snapshot():
groups = {'duration': {'duration': 15}, 'active': {'active': 1},
'schedule': {key: None for key in module.GROUPS['schedule']},
'conditions': {'triggers': {}, 'start_condition_operator': 'AND', 'per_hour': 0}}
return {'schema_version': 1, 'device_id': 109, 'components': [{
'id': 22, 'title': 'Fixture command, no hardware', 'grant_id': 'grant-fixture',
'grant_expires_at': 200000, 'generator_type': 'sync',
'anchor': {'id': 'anchor-fixture', 'server_time_ms': 100000000},
'groups': {name: {'value': value, 'clock': {'revision': 1}} for name, value in groups.items()}
}]}
class OfflineStoreTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.path = Path(self.tmp.name) / 'edits.sqlite3'
self.wall, self.mono, self.boot = 100000., 500., 'boot-a'
self.store = self.reopen()
self.store.ingest(snapshot())
def tearDown(self):
self.tmp.cleanup()
def reopen(self):
return module.Store(self.path, lambda: self.wall, lambda: self.mono, lambda: self.boot)
def receipt(self, operation, revision=2, status='accepted'):
return {'operation_id': operation['operation_id'], 'component_id': 22, 'group': operation['group'],
'status': status, 'canonical': {'value': operation['value'], 'clock': {'revision': revision}}}
def test_offline_commit_and_process_restart_preserve_outbox(self):
self.mono += 10; self.wall += 10
op = self.store.edit(22, 'duration', {'duration': 120})
self.assertTrue(op['clock_trusted'])
self.assertEqual(op['created_at_ms'], 100010000)
restarted = self.reopen()
self.assertEqual(restarted.pending(), [op])
self.assertEqual(restarted.view(22)['groups']['duration']['value'], {'duration': 120})
restarted.acknowledge(self.receipt(op))
restarted.acknowledge(self.receipt(op))
self.assertEqual(restarted.pending(), [])
self.assertEqual(restarted.view(22)['groups']['duration']['clock']['revision'], 2)
def test_snapshot_does_not_clobber_independent_or_newer_pending_edits(self):
first = self.store.edit(22, 'duration', {'duration': 120})
second = self.store.edit(22, 'duration', {'duration': 240})
incoming = snapshot(); incoming['components'][0]['groups']['active']['value']['active'] = 0
self.store.ingest(incoming)
self.store.acknowledge(self.receipt(first))
view = self.store.view(22)
self.assertEqual(view['groups']['duration']['value']['duration'], 240)
self.assertEqual(view['groups']['active']['value']['active'], 0)
self.assertEqual(self.store.pending(), [second])
self.store.acknowledge(self.receipt(second, 3))
self.assertEqual(self.store.view(22)['groups']['duration']['value']['duration'], 240)
def test_device_change_and_removed_scope_do_not_resurrect_operations(self):
self.store.edit(22, 'active', {'active': 0})
incoming = snapshot(); incoming['device_id'] = 999
with self.assertRaises(ValueError): self.store.ingest(incoming)
incoming = snapshot(); incoming['components'] = []
self.store.ingest(incoming)
self.assertEqual(self.store.pending(), [])
with self.assertRaises(PermissionError): self.store.view(22)
def test_clock_jump_or_reboot_is_explicitly_untrusted(self):
self.wall += 1000
op = self.store.edit(22, 'duration', {'duration': 20})
self.assertFalse(op['clock_trusted'])
self.store.acknowledge(self.receipt(op, status='clock_conflict'))
self.assertEqual(self.store.pending(), [])
self.assertEqual(self.store.view(22)['pending'][0]['status'], 'clock_conflict')
self.boot = 'boot-b'; self.mono = 1
self.assertFalse(self.reopen().edit(22, 'active', {'active': 0})['clock_trusted'])
def test_invalid_edits_cannot_enter_outbox(self):
for group, value in [('duration', {'duration': 3601}), ('active', {'active': True}),
('start', {'value': True}), ('duration', {'duration': 20, 'id': 999})]:
with self.assertRaises(ValueError): self.store.edit(22, group, value)
self.assertEqual(self.store.pending(), [])
def test_overlay_changes_only_existing_target_and_pending_group(self):
self.store.edit(22, 'duration', {'duration': 120})
canonical = {'layouts': [{'frames': [{'playlists': [{'elements': [{'id': 22, 'duration': 15, 'active': 0}, {'id': 99, 'duration': 5}]}]}]}]}
result = self.store.overlay(canonical)
items = result['layouts'][0]['frames'][0]['playlists'][0]['elements']
self.assertEqual(items, [{'id': 22, 'duration': 120, 'active': 0}, {'id': 99, 'duration': 5}])
self.assertEqual(canonical['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]['duration'], 15)
def test_interrupted_sql_write_does_not_apply_half_an_edit(self):
with sqlite3.connect(self.path) as db:
db.execute("CREATE TRIGGER fail_outbox BEFORE INSERT ON outbox BEGIN SELECT RAISE(ABORT,'fixture interruption'); END")
with self.assertRaises(sqlite3.IntegrityError): self.store.edit(22, 'duration', {'duration': 120})
self.assertEqual(self.reopen().view(22)['groups']['duration']['value']['duration'], 15)
def test_local_activity_cannot_bypass_output_eligibility(self):
self.store.edit(22, 'active', {'active': 1})
native = {'layouts': [{'frames': [{'playlists': [{'elements': [{'id': 22, 'active': 0, 'execution_eligibility': {'eligible': False, 'reason': 'command_output_unbound'}}]}]}]}]}
result = self.store.overlay(native)
self.assertEqual(result['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]['active'], 0)
def test_expired_grant_is_not_a_local_permission(self):
self.wall = 200001
with self.assertRaises(PermissionError): self.store.edit(22, 'active', {'active': 0})
if __name__ == '__main__': unittest.main()