diff --git a/README.md b/README.md index a98f801..166013f 100644 --- a/README.md +++ b/README.md @@ -572,6 +572,8 @@ than 30 minutes is ignored. for read-only checks, stored in `monitor_state.modem_checks`: - **NAT sessions** every 30 minutes, from the NAT Table page. Needs attention warns when 80% of the gateway's sessions (32,767 on a BGW320) are in use, since new connections stall once it is full. + The same read counts incoming sessions to the public IP by destination port, so the panel shows + the *busiest inbound port* (protocol, port, sessions and how many addresses they come from). - **Side-by-side latency test** (gandalf#70): the provider's "plug a device straight into the modem and see if it's slow too" test, run by Gandalf. The gateway pings 1.1.1.1 from its Troubleshoot page while, at the same moment, Gandalf times TCP handshakes to 1.1.1.1:443 through the router and to the @@ -593,10 +595,22 @@ for read-only checks, stored in `monitor_state.modem_checks`: what the tests showed while it built up, and its *Cleared* note sums up the whole episode in words that can go straight to the provider. The latest result is in the Internet line in Needs attention and on the WAN / Fiber panel. -- **Firewall drops** every 5 minutes, from the Logs page, counted per hour for a day. Most are *FLOOD - limit 50pps*: AT&T's firmware caps new incoming connections at 50 per second (visitors to hosted - services, peers), with no setting to change it. The log records at most one drop every 2 seconds and - keeps about ten minutes, so the counts are a lower bound. Shown on the panel only. +- **Firewall drops** every 5 minutes, from the Logs page, counted per hour and kept for 14 days. Most + are *FLOOD limit 50pps*: AT&T's firmware caps new incoming connections at 50 per second (visitors to + hosted services, peers), even in IP Passthrough, with no setting to change it. The log records at + most one drop every 2 seconds (about 1,800 an hour) and keeps about ten minutes, so the counts are a + lower bound. The WAN / Fiber panel charts them per hour, with the full-limit line marked. + + **When the limit stays full**, outside users, Sia and every other inbound service fail to connect or + feel slow, while everything from inside works (hairpin traffic never reaches the modem). Gandalf + raises *Modem dropping new incoming connections (flood limit)* when 2 complete hours in a row each + log 1,500 or more flood drops (the hour still filling doesn't count; an hour missing from the log + counts as quiet). It shows in Needs attention with the busiest inbound port, opens a P2 ticket after + the usual consecutive checks, and clears, with a *Cleared* note, once a complete hour logs under 500. + Between 500 and 1,500 an open alert stays as it is. Counts more than an hour old decide nothing. + The fix is upstream of the modem: blocking in nginx or on the UDM can't help, because the modem + counts connection attempts before they reach either. In November 2026 it was a crawler on the + Gitea site, fixed by turning on Cloudflare's proxy for that hostname. - **The gateway's own speed tests** (AT&T runs them from the modem), read with the NAT check; the latest down and up results are shown on the panel as a reference for what the line itself delivers. @@ -1074,7 +1088,7 @@ Take LED colors from the model's quick start guide. See the comment at the top o `recovery_notified` once the recovery note is on its ticket (column added automatically at monitor startup) - `suppression_rules`: `active=FALSE` when removed; `expires_at` checked at query time - `monitor_state`: key/value store; `interface_baseline`, `link_stats`, and `modem_stats` are JSON blobs -- `monitor_state` also holds `wan_history` (WAN outages, modem restarts), `wan_quality` (UniFi's 5 minute WAN health timeline), `modem_checks` (NAT sessions, the latest side-by-side ping and 7 days of them in `ping_history`, hourly firewall drops and the gateway's speed test results) and `unifi_log_cursor` (how far the UniFi log has been read) +- `monitor_state` also holds `wan_history` (WAN outages, modem restarts), `wan_quality` (UniFi's 5 minute WAN health timeline), `modem_checks` (NAT sessions, the latest side-by-side ping and 7 days of them in `ping_history`, hourly firewall drops for 14 days, the busiest inbound ports and the gateway's speed test results) and `unifi_log_cursor` (how far the UniFi log has been read) - Database sessions run in UTC (`db.py`), whatever the server's time zone - `modem_samples`: optical readings per poll, kept 90 days; created automatically at monitor startup - `cutsheet_items`, `cutsheet_cables`, `cutsheet_port_labels`, `cutsheet_history`: cutsheet records and diff --git a/attention.py b/attention.py index b157e02..2537350 100644 --- a/attention.py +++ b/attention.py @@ -144,8 +144,28 @@ def _modem_ping_note(checks: Optional[dict], now: float) -> str: return f"Modem's own ping {when}: {theirs}{ours_txt}, {verdict}. " -def _modem_checks(checks: Optional[dict]) -> List[dict]: - out = [] +_FLOOD_STALE_S = 3600 + + +def _inbound_flood(checks: Optional[dict], now: float) -> List[dict]: + """The modem's flood limit full for hours: new incoming connections are being dropped.""" + fw = (checks or {}).get('firewall') or {} + if not fw.get('hours') or now - (fw.get('checked_at') or 0) > _FLOOD_STALE_S: + return [] + sat = modem.flood_saturation(fw['hours']) + if sat is None: + return [] + detail = (f'Its flood limit (50 new connections a second) has been full for {sat["hours"]} hours. ' + 'Outside users, Sia and other inbound services may fail to connect or feel slow. ') + busiest = modem.inbound_text(((checks or {}).get('nat') or {}).get('inbound'), top=1) + if busiest: + detail += f'Busiest inbound port: {busiest}.' + return [_entry('broken', 'warn', 'Modem is dropping new incoming connections', '#modem-section', + detail.strip())] + + +def _modem_checks(checks: Optional[dict], now: Optional[float] = None) -> List[dict]: + out = _inbound_flood(checks, time.time() if now is None else now) nat = (checks or {}).get('nat') or {} if nat.get('available') and nat.get('in_use', 0) / nat['available'] >= _NAT_FULL: pct = round(100 * nat['in_use'] / nat['available']) @@ -225,7 +245,7 @@ def build(events: List[dict], power: List[dict], cutsheet_view: Optional[dict], Entry: {group, severity: bad|warn|info, text, href, detail}. """ now = time.time() if now is None else now - entries = (_wan(wan_quality, now, modem_checks) + _modem_checks(modem_checks) + entries = (_wan(wan_quality, now, modem_checks) + _modem_checks(modem_checks, now) + _smart_power(modem_restart) + _alerts(events) + _rebooting(events) + _power(power)) if cutsheet_view is not None: entries += _cutsheet(cutsheet_view) diff --git a/modem.py b/modem.py index cd3eb3c..4f43c1e 100644 --- a/modem.py +++ b/modem.py @@ -28,7 +28,7 @@ import html import logging import re import time -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from typing import Dict, List, Optional import requests @@ -576,6 +576,94 @@ def firewall_kind(reason: str) -> str: return 'flood' if 'flood' in reason else 'invalid' if 'invalid' in reason else 'other' +# The gateway drops new incoming connections over a fixed limit (50 a second) and logs at +# most one drop every 2 seconds: about 1,800 an hour when the limit stays full. +FIREWALL_LOG_CEILING = 1800 +FLOOD_SATURATED_PER_HOUR = 1500 # logged flood drops in an hour that count as "full" +FLOOD_SATURATED_HOURS = 2 # full hours in a row before raising it +FLOOD_CLEAR_PER_HOUR = 500 # an hour under this ends it + + +def _hour(key: str) -> Optional[datetime]: + try: + return datetime.strptime(key, '%Y-%m-%dT%H') + except (TypeError, ValueError): + return None + + +def _complete_hours(hours: dict) -> List[tuple]: + """[(hour key, flood count)] for each hour before the newest (which is still filling), + oldest first, with hours missing from the log filled in as 0.""" + keys = sorted(k for k in hours if _hour(k)) + if len(keys) < 2: + return [] + out = [] + start, end = _hour(keys[0]), _hour(keys[-1]) + t = start + while t < end: + key = t.strftime('%Y-%m-%dT%H') + out.append((key, int((hours.get(key) or {}).get('flood') or 0))) + t += timedelta(hours=1) + return out + + +def flood_saturation(hours: dict, per_hour: int = FLOOD_SATURATED_PER_HOUR, + need: int = FLOOD_SATURATED_HOURS) -> Optional[dict]: + """The gateway's flood limit has been full for the last `need` complete hours or more. + + hours: the monitor's per-hour firewall counts ({'YYYY-MM-DDTHH': {'flood': n, ...}}, + gateway local time). Returns {'hours': run length, 'counts': [n, ...] newest last, + 'since': first hour key of the run} or None. + """ + complete = _complete_hours(hours) + run = 0 + for _, n in reversed(complete): + if n < per_hour: + break + run += 1 + if run < max(need, 1): + return None + tail = complete[-run:] + return {'hours': run, 'counts': [n for _, n in tail], 'since': tail[0][0]} + + +def flood_cleared(hours: dict, clear: int = FLOOD_CLEAR_PER_HOUR) -> bool: + """The last complete hour had few enough flood drops that new connections get through.""" + complete = _complete_hours(hours) + return bool(complete) and complete[-1][1] < clear + + +def parse_inbound_ports(page: str, wan_ip: str, top: int = 5) -> List[dict]: + """The busiest destination ports of incoming sessions to wan_ip in the NAT table page: + [{'proto', 'port', 'sessions', 'sources'}], busiest first. Shows what an inbound + flood is aimed at.""" + if not wan_ip: + return [] + sessions: Dict[tuple, int] = {} + sources: Dict[tuple, set] = {} + for row in re.findall(r']*>(.*?)', page, re.I | re.S): + cells = [_TAG_RE.sub('', c).strip() for c in _CELL_RE.findall(row)] + # IP family, protocol, number, lifetime, TCP state, source, source port, destination, + # destination port, then the same four after NAT + if (len(cells) < 9 or cells[0] != 'ipv4' or cells[1] not in ('tcp', 'udp') + or cells[7] != wan_ip or not cells[8].isdigit()): + continue + key = (cells[1], cells[8]) + sessions[key] = sessions.get(key, 0) + 1 + sources.setdefault(key, set()).add(cells[5]) + ranked = sorted(sessions, key=lambda k: (-sessions[k], k))[:top] + return [{'proto': p, 'port': port, 'sessions': sessions[(p, port)], 'sources': len(sources[(p, port)])} + for p, port in ranked] + + +def inbound_text(inbound: Optional[List[dict]], top: int = 3) -> str: + """'TCP 443: 1,268 sessions from 1,250 addresses; ...' for the busiest inbound ports.""" + def n(count: int, word: str) -> str: + return f'{count:,} {word}' + ('' if count == 1 else ('es' if word.endswith('s') else 's')) + return '; '.join(f'{(p.get("proto") or "").upper()} {p.get("port")}: {n(p.get("sessions", 0), "session")} ' + f'from {n(p.get("sources", 0), "address")}' for p in (inbound or [])[:top]) + + def parse_speed_tests(page: str) -> List[dict]: """The gateway's own speed test history, newest first: {'at' (as the page shows it), 'direction', 'mbps', 'latency_ms', 'ok'}.""" @@ -644,11 +732,15 @@ class ModemAdmin: raise ModemDataInvalid(f'{path} returned HTTP {resp.status_code} after logging in') return resp.text - def nat_sessions(self) -> Dict[str, int]: + def nat_sessions(self, wan_ip: str = '') -> dict: + """{'in_use', 'available'}, plus 'inbound' (parse_inbound_ports) when wan_ip is known.""" # The page lists every session too, so it can be large (hundreds of KB) - counts = parse_nat_summary(self._page(_NAT_PAGE, timeout=max(self.timeout, 30))) + page = self._page(_NAT_PAGE, timeout=max(self.timeout, 30)) + counts = parse_nat_summary(page) if counts is None: raise ModemDataInvalid('NAT table page has no session counts') + if wan_ip: + counts['inbound'] = parse_inbound_ports(page, wan_ip) return counts def firewall_log(self) -> List[dict]: diff --git a/monitor.py b/monitor.py index 5ea6b2d..02ec67d 100644 --- a/monitor.py +++ b/monitor.py @@ -2429,7 +2429,7 @@ class NetworkMonitor: _NAT_EVERY_S = 1800 # NAT sessions and the gateway's speed test history _FIREWALL_EVERY_S = 300 # the firewall log only holds about ten minutes - _FIREWALL_HOURS = 24 + _FIREWALL_HOURS = 14 * 24 # two weeks, so the start of a flood is still on record _PING_SLOW_EVERY_S = 120 # while the internet is slow: every check (gandalf#70 evidence) _PING_HEALTHY_EVERY_S = 1800 # otherwise now and then, to learn the line's normal latency _CHECKS_ERROR_WAIT_S = 600 # after a failed login or read, leave the gateway alone this long @@ -2478,7 +2478,7 @@ class NetworkMonitor: return # failed recently: don't keep knocking on the gateway try: if due_nat: - checks['nat'] = dict(admin.nat_sessions(), at=now) + checks['nat'] = dict(admin.nat_sessions(self._modem_wan_ip()), at=now) checks['speed'] = self._latest_speed_tests(admin.speed_tests(), now) if due_fw: checks['firewall'] = self._count_firewall_drops(checks.get('firewall'), admin.firewall_log(), now) @@ -2497,6 +2497,53 @@ class NetworkMonitor: 'login': isinstance(e, modem_api.ModemLoginFailed)} db.set_state('modem_checks', checks) + @staticmethod + def _modem_wan_ip() -> str: + """The modem's public IPv4 address from its last poll, or ''.""" + try: + raw = db.get_state('modem_stats') + stats = (json.loads(raw) if isinstance(raw, str) else raw) or {} + except (ValueError, AttributeError): + return '' + return stats.get('wan_ip') or '' + + _FLOOD_STALE_S = 3600 # firewall counts older than this are too old to judge by + + def _process_inbound_flood(self, suppressions: list) -> None: + """Alert when the modem's flood limit stays full: it drops new incoming connections + over 50 a second before they reach the router, so outside users, Sia and other + inbound services fail to connect or feel slow. Clears once an hour is quiet again.""" + raw = db.get_state('modem_checks') + try: + checks = (json.loads(raw) if isinstance(raw, str) else raw) or {} + except (ValueError, AttributeError): + return + fw = checks.get('firewall') or {} + if not fw.get('hours') or time.time() - (fw.get('checked_at') or 0) > self._FLOOD_STALE_S: + return # nothing fresh to judge by: leave any open alert as it is + sat = modem_api.flood_saturation(fw['hours']) + if sat is None: + if modem_api.flood_cleared(fw['hours']): + db.resolve_event('inbound_flood', self.modem_name, '') + return + counts = ', '.join(f'{n:,}' for n in sat['counts'][-6:]) + description = ( + f'The modem has been dropping new incoming connections over its built-in flood limit ' + f'(50 a second) for {sat["hours"]} hours in a row (since {sat["since"].replace("T", " ")}:00, ' + f'modem time). Logged drops per hour: {counts}. The log keeps at most one drop every 2 ' + f'seconds, about {modem_api.FIREWALL_LOG_CEILING:,} an hour, so the real number is higher.\n\n' + f'Outside users, Sia and other inbound services may fail to connect or feel slow. ' + f'Connections from inside the network are not affected.') + busiest = modem_api.inbound_text((checks.get('nat') or {}).get('inbound')) + if busiest: + description += f'\n\nBusiest inbound ports in the modem\'s session table: {busiest}.' + advice = ('Find what the busiest port serves and stop the traffic before it reaches the ' + 'connection, for example Cloudflare\'s proxy in front of a crawled site. Blocking in ' + 'nginx or on the UDM does not help: the modem counts connection attempts before ' + 'they reach either.') + self._modem_event(suppressions, 'inbound_flood', 'warning', '', description, + 'Modem dropping new incoming connections (flood limit)', '2', advice) + @staticmethod def _ping_evidence(start: float, end: float) -> Optional[dict]: """modem.episode_evidence over the saved side-by-side pings, or None.""" @@ -2777,6 +2824,12 @@ class NetworkMonitor: self._collect_modem_checks() except Exception as e: logger.error(f'Modem checks failed: {e}', exc_info=True) + try: + if self.modem: + with self._wan_batch(): + self._process_inbound_flood(suppressions) + except Exception as e: + logger.error(f'Inbound flood check failed: {e}', exc_info=True) # Note on the tickets of anything that cleared this cycle (or failed to post before) try: diff --git a/static/app.js b/static/app.js index 2ba5f1f..79ee10b 100644 --- a/static/app.js +++ b/static/app.js @@ -400,12 +400,18 @@ function _modemChecks(c) { } const fw = c.firewall && c.firewall.hours; if (fw && Object.keys(fw).length) { - const sum = k => Object.values(fw).reduce((n, h) => n + (h[k] || 0), 0); + const day = Object.keys(fw).sort().slice(-24).map(k => fw[k]); + const sum = k => day.reduce((n, h) => n + (h[k] || 0), 0); const flood = sum('flood'), invalid = sum('invalid'), total = flood + invalid + sum('other'); - out += _modemStat('Firewall drops', `${total.toLocaleString()} in ${Object.keys(fw).length} h`, '', + out += _modemStat('Firewall drops', `${total.toLocaleString()} in ${day.length} h`, '', `${flood.toLocaleString()} incoming over the flood limit, ${invalid.toLocaleString()} invalid; ` + 'at least (the log keeps 1 per 2 s)'); } + const busiest = c.nat && (c.nat.inbound || [])[0]; + if (busiest) { + out += _modemStat('Busiest inbound port', `${String(busiest.proto).toUpperCase()} ${busiest.port}`, + '', `${busiest.sessions.toLocaleString()} sessions from ${busiest.sources.toLocaleString()} addresses, ${ago(c.nat.at)}`); + } const sp = c.speed; if (sp && sp.down && sp.up) { out += _modemStat('AT&T speed test', `↓ ${Math.round(sp.down.mbps)} ↑ ${Math.round(sp.up.mbps)} Mbps`, '', @@ -472,6 +478,41 @@ function _modemQuality(q) { `; } +// Flood limit: the modem drops new incoming connections over 50 a second and logs at most +// one every 2 s (about 1,800 an hour). Hours near that ceiling mean the limit was full. +const _FLOOD_FULL = 1500, _FLOOD_CEILING = 1800; + +function _modemFloodChart(c) { + const hours = c && c.firewall && c.firewall.hours; + const keys = hours ? Object.keys(hours).sort() : []; + if (keys.length < 2) return ''; + const counts = keys.map(k => hours[k].flood || 0); + let run = 0; + for (let i = counts.length - 2; i >= 0 && counts[i] >= _FLOOD_FULL; i--) run += 1; // the newest hour is still filling + const peak = Math.max(...counts); + const summary = run >= 2 ? `full for the last ${run} hours` : (peak >= _FLOOD_FULL ? `full at times, peak ${peak.toLocaleString()} an hour` + : `peak ${peak.toLocaleString()} an hour`); + const w = 1000 / keys.length; + const bars = counts.map((n, i) => { + const h = Math.min(n, _FLOOD_CEILING) / _FLOOD_CEILING * 40; + const tip = `${keys[i].replace('T', ' ')}:00 modem time: ${n.toLocaleString()} dropped`; + return `${lt.escHtml(tip)}`; + }).join(''); + const line = (40 - _FLOOD_FULL / _FLOOD_CEILING * 40).toFixed(2); + return ` +
+
New incoming connections dropped by the modem's flood limit, per hour + ${lt.escHtml(summary)}
+ ${bars} + +
${lt.escHtml(keys[0].replace('T', ' '))}:00 + limit full (outside connections fail) + now
+
`; +} + // A restart from the Restart modem button: in progress, or finished in the last hour function _modemRestartNote(r) { if (!r || !r.at) return ''; @@ -553,6 +594,7 @@ function updateModem(data) {
Modem status unavailable: ${lt.escHtml(data.error || 'unknown error')} Last attempt ${lt.escHtml(data.updated || '-')}
${_modemQuality(data.wan_quality)} + ${_modemFloodChart(data.modem_checks)} ${_modemChart(data.history)}`; return; } diff --git a/static/style.css b/static/style.css index ca4e354..6fd7e49 100644 --- a/static/style.css +++ b/static/style.css @@ -861,6 +861,11 @@ .wq-key.wq-latency { background: var(--accent-amber); } .wq-key.wq-loss { background: var(--accent-red); } .wq-key.wq-down { background: var(--text-primary, #fff); } +.modem-flood svg { height: 40px; } +.fl-ok { fill: var(--accent-green-dim, rgba(0, 255, 0, .25)); } +.fl-full { fill: var(--accent-amber); } +.fl-limit { stroke: var(--text-muted); stroke-width: 1; stroke-dasharray: 6 4; vector-effect: non-scaling-stroke; } +.wq-key.fl-key-full { background: var(--accent-amber); } .modem-updated { padding: 0 12px 10px; } /* ── Device search (home page) ────────────────────────────────────── */ diff --git a/tests/test_attention.py b/tests/test_attention.py index 6144e5a..5730a0c 100644 --- a/tests/test_attention.py +++ b/tests/test_attention.py @@ -195,6 +195,24 @@ class TestModemChecks: out = self._broken({'nat': {'in_use': 2858, 'available': 32767}}) assert out == {'broken': [], 'tidy': []} + def _flood(self, counts, checked_ago=60, inbound=None): + hours = {f'2026-11-27T{10 + i:02d}': {'flood': n, 'invalid': 0, 'other': 0} for i, n in enumerate(counts)} + checks = {'firewall': {'hours': hours, 'checked_at': NOW - checked_ago}} + if inbound: + checks['nat'] = {'in_use': 1, 'available': 32767, 'inbound': inbound} + return self._broken(checks)['broken'] + + def test_flood_limit_full(self): + [e] = self._flood([1730, 1745, 1750, 20], + inbound=[{'proto': 'tcp', 'port': '443', 'sessions': 1268, 'sources': 1250}]) + assert e['text'] == 'Modem is dropping new incoming connections' and e['severity'] == 'warn' + assert 'full for 3 hours' in e['detail'] + assert e['detail'].endswith('Busiest inbound port: TCP 443: 1,268 sessions from 1,250 addresses.') + + def test_flood_limit_quiet_or_stale_says_nothing(self): + assert self._flood([1730, 300, 20]) == [] + assert self._flood([1730, 1745, 1750, 20], checked_ago=7200) == [] + def test_login_failure_is_housekeeping(self): [e] = self._broken({'error': {'login': True, 'message': 'refused', 'at': NOW}})['tidy'] assert e['text'].startswith('Modem login failed') diff --git a/tests/test_modem.py b/tests/test_modem.py index 2ba2011..16d02d3 100644 --- a/tests/test_modem.py +++ b/tests/test_modem.py @@ -1,6 +1,7 @@ """Tests for modem.py parsing. Fixtures copy the BGW320-505 (fw 6.35.8) markup with sanitized values.""" import os import sys +from datetime import datetime, timedelta from unittest.mock import MagicMock import pytest @@ -687,3 +688,76 @@ class TestSideBySidePing: assert 'A laptop plugged straight into a modem LAN port' in modem.episode_evidence(gw, 0, 9)['text'] clear = [{'at': 1, 'modem_ms': 14, 'verdict': 'clear'}] assert 'all were normal' in modem.episode_evidence(clear, 0, 9)['text'] + + +NAT_ROWS = (NAT_PAGE + '' + + ''.join(f'' + f'' + f'' + for i, (src, dst, port) in enumerate([ + ('198.51.100.1', '203.0.113.9', '443'), ('198.51.100.2', '203.0.113.9', '443'), + ('198.51.100.2', '203.0.113.9', '443'), ('198.51.100.3', '203.0.113.9', '25565'), + ('203.0.113.9', '192.0.2.1', '443')])) + + '' + '' + '' + + '' + '' + '
IP Family
ipv4tcp628700ESTABLISHED{src}5{i:04d}{dst}{port}x1{dst}{port}*
ipv4icmp120198.51.100.5 203.0.113.9 x1203.0.113.9 *
ipv4udp1720198.51.100.41203.0.113.99984x1203.0.113.99984*
') + + +class TestInboundPorts: + def test_busiest_ports_of_sessions_to_the_wan_ip(self): + assert modem.parse_inbound_ports(NAT_ROWS, '203.0.113.9') == [ + {'proto': 'tcp', 'port': '443', 'sessions': 3, 'sources': 2}, + {'proto': 'tcp', 'port': '25565', 'sessions': 1, 'sources': 1}, + {'proto': 'udp', 'port': '9984', 'sessions': 1, 'sources': 1}, + ] + + def test_outbound_sessions_and_no_wan_ip_are_ignored(self): + assert modem.parse_inbound_ports(NAT_ROWS, '') == [] + assert modem.parse_inbound_ports(NAT_ROWS, '192.0.2.1') == [ + {'proto': 'tcp', 'port': '443', 'sessions': 1, 'sources': 1}] + + def test_summary_counts_still_read(self): + assert modem.parse_nat_summary(NAT_ROWS) == {'in_use': 2858, 'available': 32767} + + def test_text(self): + assert modem.inbound_text([{'proto': 'tcp', 'port': '443', 'sessions': 1268, 'sources': 1250}]) == ( + 'TCP 443: 1,268 sessions from 1,250 addresses') + assert modem.inbound_text(None) == '' + assert modem.inbound_text([{'proto': 'tcp', 'port': '22', 'sessions': 1, 'sources': 1}]) == ( + 'TCP 22: 1 session from 1 address') + + +def _fw(counts, start='2026-11-27T10'): + """Per-hour firewall counts from consecutive flood totals, oldest first.""" + t0 = datetime.strptime(start, '%Y-%m-%dT%H') + return {(t0 + timedelta(hours=i)).strftime('%Y-%m-%dT%H'): {'flood': n, 'invalid': 0, 'other': 0} + for i, n in enumerate(counts)} + + +class TestFloodSaturation: + def test_two_full_hours_in_a_row(self): + # The newest hour (40) is still filling, so it doesn't count either way + sat = modem.flood_saturation(_fw([100, 1700, 1750, 40])) + assert sat == {'hours': 2, 'counts': [1700, 1750], 'since': '2026-11-27T11'} + + def test_one_full_hour_is_not_enough(self): + assert modem.flood_saturation(_fw([100, 1200, 1750, 1750])) is None + + def test_the_run_counts_back_from_the_newest_complete_hour(self): + sat = modem.flood_saturation(_fw([1700, 1700, 1700, 200, 1600, 1650, 1700, 900])) + assert sat['hours'] == 3 and sat['since'] == '2026-11-27T14' + + def test_a_missing_hour_counts_as_quiet(self): + hours = _fw([1700, 1700, 1700, 10]) + del hours['2026-11-27T12'] + assert modem.flood_saturation(hours) is None + assert modem.flood_cleared(hours) is True + + def test_cleared_needs_a_quiet_complete_hour(self): + assert modem.flood_cleared(_fw([1700, 400, 1800])) is True + assert modem.flood_cleared(_fw([1700, 900, 0])) is False + assert modem.flood_cleared(_fw([5])) is False + assert modem.flood_cleared({}) is False diff --git a/tests/test_monitor.py b/tests/test_monitor.py index 8d0747b..0ee4191 100644 --- a/tests/test_monitor.py +++ b/tests/test_monitor.py @@ -3,7 +3,7 @@ import json import os import sys import time -from datetime import timedelta +from datetime import datetime, timedelta from unittest.mock import MagicMock, patch import pytest @@ -1507,11 +1507,25 @@ class TestModemExtrasCollection: out = mon._count_firewall_drops(prev, [self._row('2026-11-19T18:20:00.0')], 1.0) assert out['gap'] is True - def test_keeps_a_day(self, mon): - prev = {'hours': {f'2026-11-18T{h:02d}': {'flood': 1, 'invalid': 0, 'other': 0} for h in range(24)}, - 'last': '2026-11-18T23:59:59.0'} + def test_keeps_two_weeks(self, mon): + t0 = datetime(2026, 11, 5, 0) + keys = [(t0 + timedelta(hours=h)).strftime('%Y-%m-%dT%H') for h in range(14 * 24)] + prev = {'hours': {k: {'flood': 1, 'invalid': 0, 'other': 0} for k in keys}, 'last': keys[-1] + ':59:59.0'} out = mon._count_firewall_drops(prev, [self._row('2026-11-19T00:00:01.0')], 1.0) - assert len(out['hours']) == 24 and '2026-11-18T00' not in out['hours'] + assert len(out['hours']) == 14 * 24 and keys[0] not in out['hours'] and '2026-11-19T00' in out['hours'] + + def test_nat_read_names_the_wan_ip(self, mon, db): + admin = MagicMock() + admin.nat_sessions.return_value = {'in_use': 1, 'available': 10, 'inbound': []} + admin.speed_tests.return_value = [] + admin.firewall_log.return_value = [] + admin.ping.return_value = {'sent': 5, 'received': 5, 'loss_pct': 0, 'avg_ms': 14.0, 'target': '1.1.1.1'} + mon.modem_admin = admin + state = {'modem_stats': json.dumps({'wan_ip': '203.0.113.9'})} + db.get_state.side_effect = lambda k, d=None: state.get(k, d) + with patch.object(monitor, 'tcp_rtt_ms', return_value=14.0): + mon._collect_modem_checks() + admin.nat_sessions.assert_called_once_with('203.0.113.9') def test_latest_speed_tests(self, mon): tests = [{'direction': 'upstream', 'mbps': 1242.8, 'at': 'b'}, @@ -1535,6 +1549,50 @@ class TestModemExtrasCollection: assert 'speed' in saved and admin.firewall_log.called +class TestInboundFlood: + NOW = 1_000_000.0 + + def _hours(self, counts): + t0 = datetime(2026, 11, 27, 10) + return {(t0 + timedelta(hours=i)).strftime('%Y-%m-%dT%H'): {'flood': n, 'invalid': 0, 'other': 0} + for i, n in enumerate(counts)} + + def _run(self, mon, db, counts, checked_ago=60, inbound=None): + checks = {'firewall': {'hours': self._hours(counts), 'checked_at': self.NOW - checked_ago}} + if inbound is not None: + checks['nat'] = {'in_use': 1, 'available': 10, 'inbound': inbound, 'at': self.NOW} + db.get_state.side_effect = lambda k, d=None: json.dumps(checks) if k == 'modem_checks' else d + db.resolve_event.reset_mock() + with patch.object(monitor.time, 'time', return_value=self.NOW), \ + patch.object(mon, '_modem_event') as event: + mon._process_inbound_flood([]) + return event + + def test_full_for_two_hours_raises_an_alert_naming_the_busiest_port(self, mon, db): + event = self._run(mon, db, [100, 1730, 1745, 300], + inbound=[{'proto': 'tcp', 'port': '443', 'sessions': 1268, 'sources': 1250}]) + args = event.call_args.args + assert args[1:4] == ('inbound_flood', 'warning', '') + assert 'for 2 hours in a row (since 2026-11-27 11:00, modem time)' in args[4] + assert 'Logged drops per hour: 1,730, 1,745' in args[4] + assert 'TCP 443: 1,268 sessions from 1,250 addresses' in args[4] + assert args[5] == 'Modem dropping new incoming connections (flood limit)' + assert 'Cloudflare' in args[7] and not db.resolve_event.called + + def test_a_quiet_hour_clears_it(self, mon, db): + event = self._run(mon, db, [1730, 1745, 200, 10]) + assert not event.called + db.resolve_event.assert_called_once_with('inbound_flood', mon.modem_name, '') + + def test_in_between_leaves_it_as_it_is(self, mon, db): + event = self._run(mon, db, [1730, 1745, 900, 10]) + assert not event.called and not db.resolve_event.called + + def test_stale_counts_decide_nothing(self, mon, db): + event = self._run(mon, db, [1730, 1745, 1750, 10], checked_ago=7200) + assert not event.called and not db.resolve_event.called + + class TestFinishModemRestart: NOW = 1_000_000.0