#!/usr/bin/env python3 """Read-only educational adaptation. Internal UniFi APIs may change.""" import collections import datetime as dt import fcntl import http.cookiejar import json import os from pathlib import Path import re import sys import urllib.request from common import atomic_json, https_url, opener, timeout_value class ReadOnlyUniFi: def __init__(self, base, site='default', cafile=None, timeout=10): p = https_url(base) if p.path not in ('', '/') or not re.fullmatch(r'[A-Za-z0-9_-]+', site): raise ValueError('Invalid controller base URL or site') self.base = base.rstrip('/') self.base_api = '/proxy/network/api/s/' + site self.logs_api = '/proxy/network/v2/api/site/' + site + '/system-log/all' self.read_paths = {self.base_api + s for s in ('/stat/device', '/stat/sta', '/stat/rogueap')} self.csrf = None self.timeout = timeout_value(timeout) self.opener = opener(cafile, http.cookiejar.CookieJar()) def request(self, method, path, payload=None): # Exact path allowlist, not a prefix; redirects and ambient proxies disabled. if not ((method == 'GET' and path in self.read_paths and payload is None) or (method == 'POST' and path in {'/api/auth/login', self.logs_api})): raise ValueError('Read-only policy refused this operation') headers = {'Content-Type': 'application/json'} if self.csrf: headers['X-CSRF-Token'] = self.csrf req = urllib.request.Request(self.base + path, method=method, headers=headers, data=json.dumps(payload).encode() if payload is not None else None) with self.opener.open(req, timeout=self.timeout) as res: self.csrf = res.headers.get('x-csrf-token') or self.csrf raw = res.read(4_000_001) if len(raw) > 4_000_000: raise ValueError('Response size limit') return json.loads(raw) def get_rows(self, suffix): data = self.request('GET', self.base_api + suffix)['data'] if not isinstance(data, list): raise ValueError('Unexpected rows schema') return data def logs(api, start_ms, end_ms, max_pages=100, page_size=100): if not (1 <= max_pages <= 100 and 1 <= page_size <= 100 and start_ms <= end_ms): raise ValueError('Invalid pagination bounds') expected = pages = None events = [] seen = set() for page in range(max_pages): data = api.request('POST', api.logs_api, { 'timestampFrom': start_ms, 'timestampTo': end_ms, 'pageNumber': page, 'pageSize': page_size, 'type': 'GENERAL'}) total, count, rows = data['total_element_count'], data['total_page_count'], data['data'] if type(total) is not int or type(count) is not int or total < 0 or count < 0: raise ValueError('Invalid pagination metadata') if not isinstance(rows, list) or len(rows) > page_size: raise ValueError('Invalid page rows') required = (total + page_size - 1) // page_size if count != required and not (total == 0 and count == 1): raise ValueError('Inconsistent page count') if count > max_pages: raise ValueError('Pagination safety limit reached') if expected is None: expected, pages = total, count if (total, count) != (expected, pages): raise ValueError('Fixed-window log total/pages changed') wanted = min(page_size, max(0, total - page * page_size)) if len(rows) != wanted: raise ValueError('Incomplete page') for row in rows: identity = row['id'] timestamp = row['timestamp'] if not isinstance(identity, (str, int)) or isinstance(identity, bool) or identity in seen: raise ValueError('Duplicate/invalid log ID') if type(timestamp) not in (int, float) or not start_ms <= timestamp <= end_ms: raise ValueError('Log timestamp outside requested window') seen.add(identity) events.append(row) if page + 1 >= count: break else: raise ValueError('Pagination safety limit reached') if len(events) != expected: raise ValueError('Incomplete logs') return events def fields(row, names): return {k: row[k] for k in names if k in row} def collect(api, now, ap_name): if not ap_name or now.tzinfo is None: raise ValueError('AP name and timezone-aware datetime required') aps = [d for d in api.get_rows('/stat/device') if d.get('type') == 'uap' and d.get('name') == ap_name] if len(aps) != 1 or aps[0].get('state') != 1: raise ValueError('Configured AP missing, duplicated or offline') clients = [x for x in api.get_rows('/stat/sta') if not x.get('is_wired')] neighbors = api.get_rows('/stat/rogueap') fresh = [x for x in neighbors if type(x.get('last_seen')) in (int, float) and 0 <= now.timestamp() - x['last_seen'] <= 3600 and x.get('radio') == 'ng'] events = logs(api, int((now - dt.timedelta(hours=24)).timestamp()*1000), int(now.timestamp()*1000)) tracked = collections.Counter(x.get('key', 'UNKNOWN') for x in events if x.get('key') in {'CLIENT_CONNECTED_WIRELESS_2', 'CLIENT_DISCONNECTED_WIRELESS_2', 'AP_CHANGED_CHANNELS'}) return {'at_utc': now.isoformat(), 'mode': 'monitor_only', 'remote_configuration_writes': 0, 'log_total': len(events), 'pagination_verified': True, 'ap': fields(aps[0], ['name', 'state', 'uptime', 'version']), 'radios_config': [fields(x, ['radio', 'channel', 'ht', 'tx_power_mode']) for x in aps[0].get('radio_table', [])], 'radios_runtime': [fields(x, ['radio', 'channel', 'cu_total', 'tx_retries_pct', 'num_sta']) for x in aps[0].get('radio_table_stats', [])], 'clients': [fields(x, ['radio', 'signal', 'satisfaction', 'wifi_tx_retries_percentage']) for x in clients], 'fresh_1h_bss_counts_by_channel': dict(collections.Counter(str(x.get('channel')) for x in fresh)), 'event_counts': dict(tracked), 'channel_coverage_validated': False, 'channel_recommendation': None, 'coverage_note': 'Passive cached observations are not a comparable all-channel RF survey.'} def main(): os.umask(0o077) env = os.environ if not env.get('UNIFI_USERNAME') or not env.get('UNIFI_PASSWORD') or not env.get('UNIFI_AP_NAME'): raise ValueError('Set UNIFI_USERNAME, UNIFI_PASSWORD and UNIFI_AP_NAME') directory = Path(env.get('RF_STATE_DIR', '~/.local/state/homelab-rf')).expanduser() directory.mkdir(parents=True, exist_ok=True, mode=0o700) if directory.is_symlink(): raise ValueError('Symlink state directory refused') directory.chmod(0o700) with (directory / '.lock').open('a') as lock: os.chmod(directory / '.lock', 0o600) try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: return api = ReadOnlyUniFi(env.get('UNIFI_URL', 'https://198.51.100.1'), env.get('UNIFI_SITE', 'default'), env.get('UNIFI_CA_FILE'), env.get('CHECK_TIMEOUT', '10')) api.request('POST', '/api/auth/login', {'username': env['UNIFI_USERNAME'], 'password': env['UNIFI_PASSWORD'], 'rememberMe': False}) atomic_json(directory, 'latest.json', collect(api, dt.datetime.now(dt.timezone.utc), env['UNIFI_AP_NAME'])) if __name__ == '__main__': try: main() except Exception as exc: print('RF monitor failed: ' + type(exc).__name__, file=sys.stderr) sys.exit(1)