From f0504f802edc57610cdd0f6f3b879d63b5ff6af7 Mon Sep 17 00:00:00 2001 From: Matthew Grotke Date: Wed, 27 May 2026 15:29:23 -0400 Subject: [PATCH] Development --- .../routlin-dash/app/action_networklayout.py | 38 +++++++++---------- docker/routlin-dash/app/sanitize.py | 8 ++++ docker/routlin-dash/app/view_page.py | 25 +++++------- docker/routlin-dash/data/page_content.json | 11 +++--- routlin/config.json | 5 +++ routlin/core.py | 16 ++++---- routlin/health.py | 6 +-- routlin/validation.py | 24 +++++------- 8 files changed, 67 insertions(+), 66 deletions(-) diff --git a/docker/routlin-dash/app/action_networklayout.py b/docker/routlin-dash/app/action_networklayout.py index 56c8011..1f11d82 100644 --- a/docker/routlin-dash/app/action_networklayout.py +++ b/docker/routlin-dash/app/action_networklayout.py @@ -11,7 +11,7 @@ bp = Blueprint('action_networklayout', __name__) VIEW = '/view/view_network_layout' -_VLAN_FIELDS = ['name', 'is_vpn', 'subnet', 'subnet_mask', 'dnsmasq_log_queries', +_VLAN_FIELDS = ['name', 'vlan_id', 'is_vpn', 'subnet', 'subnet_mask', 'dnsmasq_log_queries', 'radius_default', 'mdns_reflection', 'use_blocklists'] @@ -33,6 +33,7 @@ def _hash_ok(): @require_level('administrator') def networklayout_cardaddvlan_addvlan(): name = sanitize.name(request.form.get('name', '')) + vlan_id = sanitize.vlan_id(request.form.get('vlan_id', '')) is_vpn = 'is_vpn' in request.form subnet = sanitize.ip(request.form.get('subnet', '')) subnet_mask = sanitize.subnet_mask(request.form.get('subnet_mask', '')) @@ -47,6 +48,9 @@ def networklayout_cardaddvlan_addvlan(): if not name: flash('Name is required.', 'error') return redirect(VIEW) + if vlan_id is None: + flash('VLAN ID must be an integer between 1 and 4094.', 'error') + return redirect(VIEW) if not subnet: flash('Subnet IP is required.', 'error') return redirect(VIEW) @@ -54,19 +58,14 @@ def networklayout_cardaddvlan_addvlan(): flash('Invalid subnet prefix (must be 1-30).', 'error') return redirect(VIEW) - vlan_id = validate.derive_vlan_id(subnet, subnet_mask) - if vlan_id is None: - flash('Cannot derive a valid VLAN ID (1-4094) from this subnet/prefix combination.', 'error') - return redirect(VIEW) - if not _hash_ok(): return redirect(VIEW) cfg = load_config() vlans = cfg.setdefault('vlans', []) - if any(validate.derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) == vlan_id for v in vlans): - flash(f'VLAN {vlan_id} (derived from subnet) already exists.', 'error') + if any(v.get('vlan_id') == vlan_id for v in vlans): + flash(f'VLAN ID {vlan_id} is already in use.', 'error') return redirect(VIEW) if radius_default and any(v.get('radius_default') for v in vlans): flash('Only one VLAN can be the RADIUS default.', 'error') @@ -74,6 +73,7 @@ def networklayout_cardaddvlan_addvlan(): entry = { 'name': name, + 'vlan_id': vlan_id, 'is_vpn': is_vpn, 'subnet': subnet, 'subnet_mask': subnet_mask, @@ -111,6 +111,7 @@ def networklayout_tablevlans_edit(): return redirect(VIEW) name = sanitize.name(request.form.get('name', '')) + vlan_id = sanitize.vlan_id(request.form.get('vlan_id', '')) subnet = sanitize.ip(request.form.get('subnet', '')) radius_default = 'radius_default' in request.form mdns_reflection = 'mdns_reflection' in request.form @@ -142,6 +143,9 @@ def networklayout_tablevlans_edit(): if not name: flash('Name is required.', 'error') return redirect(VIEW) + if vlan_id is None: + flash('VLAN ID must be an integer between 1 and 4094.', 'error') + return redirect(VIEW) if not subnet: flash('Subnet IP is required.', 'error') return redirect(VIEW) @@ -165,21 +169,13 @@ def networklayout_tablevlans_edit(): flash(f"Server identity IP '{_ip}' is not in the VLAN subnet ({subnet}/{final_mask}).", 'error') return redirect(VIEW) - vlan_id = validate.derive_vlan_id(subnet, final_mask) - if vlan_id is None: - flash('Cannot derive a valid VLAN ID (1-4094) from this subnet/prefix combination.', 'error') - return redirect(VIEW) - - current_id = validate.derive_vlan_id(existing.get('subnet', ''), existing.get('subnet_mask', 24)) + current_id = existing.get('vlan_id') if current_id == 1 and vlan_id != 1: - flash('VLAN 1 is the physical interface; change its subnet so the derived ID remains 1.', 'error') + flash('VLAN 1 is the physical interface and cannot change its ID.', 'error') return redirect(VIEW) - if vlan_id != current_id and any( - validate.derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) == vlan_id - for i, v in enumerate(vlans) if i != idx - ): - flash(f'VLAN {vlan_id} (derived from subnet) already exists.', 'error') + if vlan_id != current_id and any(v.get('vlan_id') == vlan_id for i, v in enumerate(vlans) if i != idx): + flash(f'VLAN ID {vlan_id} is already in use.', 'error') return redirect(VIEW) if radius_default and any(i != idx and v.get('radius_default') for i, v in enumerate(vlans)): @@ -274,6 +270,7 @@ def networklayout_tablevlans_edit(): ) ) if (name == existing.get('name', '') + and vlan_id == existing.get('vlan_id') and subnet == existing.get('subnet', '') and final_mask == existing.get('subnet_mask', 24) and dnsmasq_log_queries == bool(existing.get('dnsmasq_log_queries', False)) @@ -290,6 +287,7 @@ def networklayout_tablevlans_edit(): before = {k: existing.get(k) for k in _VLAN_FIELDS} existing.update({ 'name': name, + 'vlan_id': vlan_id, 'is_vpn': is_vpn, 'subnet': subnet, 'subnet_mask': final_mask, diff --git a/docker/routlin-dash/app/sanitize.py b/docker/routlin-dash/app/sanitize.py index 7e787d0..88b3418 100644 --- a/docker/routlin-dash/app/sanitize.py +++ b/docker/routlin-dash/app/sanitize.py @@ -223,6 +223,14 @@ _DOTTED_TO_PREFIX = { '255.255.255.248': 29, '255.255.255.252': 30, } +def vlan_id(value): + """VLAN ID integer 1-4094. Returns int or None.""" + try: + n = int(str(value).strip()) + return n if 1 <= n <= 4094 else None + except (ValueError, TypeError): + return None + def subnet_mask(value): """Subnet prefix length 1-30 (integer). Also accepts legacy dotted notation. Returns int on success, None if invalid.""" diff --git a/docker/routlin-dash/app/view_page.py b/docker/routlin-dash/app/view_page.py index 66ccd3f..7a66a13 100644 --- a/docker/routlin-dash/app/view_page.py +++ b/docker/routlin-dash/app/view_page.py @@ -158,17 +158,14 @@ def _iface_status(iface): def _resolve_iface(vlan, cfg): - """Compute interface name from is_vpn + derived vlan_id + general.lan_interface.""" + """Compute interface name from is_vpn + stored vlan_id + general.lan_interface.""" if vlan.get('is_vpn'): wg_vlans = [v for v in cfg.get('vlans', []) if v.get('is_vpn')] - wg_sorted = sorted(wg_vlans, key=lambda v: ( - validate.derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) is None, - validate.derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) or 0, - )) + wg_sorted = sorted(wg_vlans, key=lambda v: (v.get('vlan_id') is None, v.get('vlan_id') or 0)) idx = next((i for i, v in enumerate(wg_sorted) if v is vlan), 0) return f'wg{idx}' lan = cfg.get('network_interfaces', {}).get('lan_interface', 'eth0') - vid = validate.derive_vlan_id(vlan.get('subnet', ''), vlan.get('subnet_mask', 24)) or 1 + vid = vlan.get('vlan_id') or 1 return lan if vid == 1 else f'{lan}.{vid}' @@ -298,9 +295,9 @@ def _config_datasource(name): if name == 'vlans': bl_desc = {b['name']: b.get('description', b['name']) for b in cfg.get('dns_blocking', {}).get('blocklists', []) if 'name' in b} rows = [] - for v in sorted(vlans, key=lambda x: validate.derive_vlan_id(x.get('subnet', ''), x.get('subnet_mask', 24)) or 0): + for v in sorted(vlans, key=lambda x: x.get('vlan_id') or 0): row = {k: v.get(k) for k in ('name', 'subnet', 'subnet_mask', 'radius_default', 'mdns_reflection', 'is_vpn', 'dnsmasq_log_queries')} - row['vlan_id'] = validate.derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) + row['vlan_id'] = v.get('vlan_id') row['interface'] = _resolve_iface(v, cfg) row['use_blocklists'] = json.dumps([ {'n': bl, 'd': bl_desc.get(bl, bl)} for bl in v.get('use_blocklists', []) @@ -380,12 +377,11 @@ def _config_datasource(name): rows = [] _wg_sorted = sorted( [v for v in vlans if v.get('is_vpn')], - key=lambda v: (validate.derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) is None, - validate.derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) or 0) + key=lambda v: (v.get('vlan_id') is None, v.get('vlan_id') or 0) ) for i, vlan in enumerate(_wg_sorted): iface = f'wg{i}' - vlan_display = f'{iface} (VLAN {validate.derive_vlan_id(vlan.get("subnet", ""), vlan.get("subnet_mask", 24)) or "?"})' + vlan_display = f'{iface} (VLAN {vlan.get("vlan_id") or "?"})' for peer in vlan.get('peers', []): row = dict(peer) row['vlan_display'] = vlan_display @@ -794,7 +790,7 @@ def collect_tokens(): tokens['VLAN_FILTER_OPTIONS'] = filter_opts tokens['VLAN_NAMES_AS_OPTIONS'] = json.dumps([{'value': n, 'label': n} for n in vlan_names]) tokens['VPN_VLAN_COUNT'] = str(sum(1 for v in vlans if v.get('is_vpn'))) - tokens['EXISTING_VLAN_IDS_JSON'] = json.dumps([validate.derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) for v in vlans]) + tokens['EXISTING_VLAN_IDS_JSON'] = json.dumps([v.get('vlan_id') for v in vlans]) tokens['EXISTING_VLAN_NAMES_JSON'] = json.dumps([v.get('name', '') for v in vlans]) tokens['EXISTING_VLAN_INTERFACES_JSON'] = json.dumps([_resolve_iface(v, cfg) for v in vlans]) tokens['STAT_BANNED_IP_COUNT'] = str(sum(1 for b in cfg.get('banned_ips', []) if b.get('enabled', True))) @@ -825,11 +821,10 @@ def collect_tokens(): wg_vlans_list = sorted( [v for v in vlans if v.get('is_vpn')], - key=lambda v: (validate.derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) is None, - validate.derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) or 0) + key=lambda v: (v.get('vlan_id') is None, v.get('vlan_id') or 0) ) tokens['VPN_VLAN_OPTIONS'] = json.dumps([ - {'value': v.get('name', ''), 'label': f'wg{i} (VLAN {validate.derive_vlan_id(v.get("subnet", ""), v.get("subnet_mask", 24)) or "?"})'} + {'value': v.get('name', ''), 'label': f'wg{i} (VLAN {v.get("vlan_id") or "?"})'} for i, v in enumerate(wg_vlans_list) ]) wg_vlan = wg_vlans_list[0] if wg_vlans_list else {} diff --git a/docker/routlin-dash/data/page_content.json b/docker/routlin-dash/data/page_content.json index 5eee408..07ca666 100644 --- a/docker/routlin-dash/data/page_content.json +++ b/docker/routlin-dash/data/page_content.json @@ -1676,11 +1676,12 @@ { "type": "field", "label": "VLAN ID", - "name": "", - "input_type": "text", - "readonly": true, - "class": "vlan-derived-id-preview form-input-mono", - "value": "" + "name": "vlan_id", + "input_type": "number", + "min": 1, + "max": 4094, + "class": "vlan-id-input form-input-mono", + "hint": "Unique integer 1–4094. Sets the 802.1Q tag and interface name." }, { "type": "field", diff --git a/routlin/config.json b/routlin/config.json index e0ed06d..0a9768f 100644 --- a/routlin/config.json +++ b/routlin/config.json @@ -264,6 +264,7 @@ "vlans": [ { "name": "trusted", + "vlan_id": 1, "subnet": "192.168.1.0", "subnet_mask": 24, "is_vpn": false, @@ -368,6 +369,7 @@ }, { "name": "iot", + "vlan_id": 10, "subnet": "192.168.10.0", "subnet_mask": 24, "is_vpn": false, @@ -472,6 +474,7 @@ }, { "name": "guest", + "vlan_id": 20, "subnet": "192.168.20.0", "subnet_mask": 24, "is_vpn": false, @@ -534,6 +537,7 @@ }, { "name": "kids", + "vlan_id": 30, "subnet": "192.168.30.0", "subnet_mask": 24, "is_vpn": false, @@ -611,6 +615,7 @@ }, { "name": "vpn", + "vlan_id": 40, "subnet": "192.168.40.0", "subnet_mask": 24, "is_vpn": true, diff --git a/routlin/core.py b/routlin/core.py index cb287d2..09d8b72 100644 --- a/routlin/core.py +++ b/routlin/core.py @@ -99,7 +99,7 @@ from validation import ( VALID_PROTOCOLS, VALID_BLOCKLIST_FORMATS, int_range, domainname, is_wg, is_dynamic_ip, - derive_vlan_id, derive_interface, validate_config, + derive_interface, validate_config, ) PRODUCT_NAME = "routlin" @@ -210,7 +210,7 @@ def resolve_vlan_options(vlan): } def is_physical(vlan): - return derive_vlan_id(vlan.get("subnet", ""), vlan.get("subnet_mask", 24)) == 1 + return vlan.get("vlan_id") == 1 def networkd_stem(vlan): return f"10-{PRODUCT_NAME}-{vlan['name']}" @@ -329,7 +329,7 @@ def apply_networkd(data, dry_run=False, only_if_changed=False): If only_if_changed=True, write files only when content differs from disk and skip the networkd reload if nothing changed. Used by --apply mode. """ - all_vlan_ids = [derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) for v in data["vlans"] if not is_wg(v)] + all_vlan_ids = [v.get('vlan_id') for v in data["vlans"] if not is_wg(v)] managed_ifaces = [derive_interface(v, data) for v in data["vlans"]] changed = False @@ -347,7 +347,7 @@ def apply_networkd(data, dry_run=False, only_if_changed=False): if is_wg(vlan): continue iface = derive_interface(vlan, data) - vid = derive_vlan_id(vlan.get('subnet', ''), vlan.get('subnet_mask', 24)) + vid = vlan.get('vlan_id') stem = networkd_stem(vlan) if not is_physical(vlan): @@ -453,7 +453,7 @@ def build_vlan_dnsmasq_conf(vlan, data, iface): line("# Generated by core.py -- do not edit manually.") line("# Edit config.json and re-run: sudo python3 core.py --apply") - line(f"# VLAN: {name} (vlan_id={derive_vlan_id(vlan.get('subnet', ''), vlan.get('subnet_mask', 24))})") + line(f"# VLAN: {name} (vlan_id={vlan.get('vlan_id')})") line() line(f"pid-file={vlan_pid_file(vlan)}") if not is_wg(vlan): @@ -1872,7 +1872,7 @@ def build_radius_users(data): ] for vlan in data["vlans"]: - vlan_id = derive_vlan_id(vlan.get('subnet', ''), vlan.get('subnet_mask', 24)) + vlan_id = vlan.get('vlan_id') for r in vlan.get("reservations", []): if r.get("enabled") is not True: continue @@ -1888,7 +1888,7 @@ def build_radius_users(data): "", ] - default_id = derive_vlan_id(default_vlan.get('subnet', ''), default_vlan.get('subnet_mask', 24)) + default_id = default_vlan.get('vlan_id') lines += [ f"# Default -- unknown MACs land on VLAN {default_id} ({default_vlan['name']})", "DEFAULT Auth-Type := Accept", @@ -2913,7 +2913,7 @@ def cmd_apply(data, dry_run=False): print(f" Would write: {RADIUS_USERS_FILE}") print(f" {total_macs} MAC reservation(s)") if default_vlan: - print(f" DEFAULT -> VLAN {derive_vlan_id(default_vlan.get('subnet', ''), default_vlan.get('subnet_mask', 24))} ({default_vlan['name']})") + print(f" DEFAULT -> VLAN {default_vlan.get('vlan_id')} ({default_vlan['name']})") print(f" Would ensure freeradius is running") if avahi_enabled(data): print() diff --git a/routlin/health.py b/routlin/health.py index 67fde35..8e5df29 100644 --- a/routlin/health.py +++ b/routlin/health.py @@ -20,7 +20,7 @@ import sys from datetime import datetime, timezone from pathlib import Path -from validation import derive_interface, derive_vlan_id, is_wg +from validation import derive_interface, is_wg # =================================================================== # Constants (mirror core.py - no import to avoid circular dependency) @@ -295,7 +295,7 @@ def check_configurations(data): # --- VLAN sub-interfaces --- for vlan in non_wg: iface = derive_interface(vlan, data) - vid = derive_vlan_id(vlan.get("subnet", ""), vlan.get("subnet_mask", 24)) + vid = vlan.get("vlan_id") state = _iface_operstate(iface) id_ = f"iface_{vlan['name']}" name = f"interface {iface}" @@ -348,7 +348,7 @@ def check_configurations(data): # --- systemd-networkd files --- for vlan in non_wg: iface = derive_interface(vlan, data) - vid = derive_vlan_id(vlan.get("subnet", ""), vlan.get("subnet_mask", 24)) + vid = vlan.get("vlan_id") net = NETWORKD_DIR / f"10-{PRODUCT_NAME}-{vlan['name']}.network" results.append(file_ok(f"networkd_net_{vlan['name']}", f"networkd {net.name}", net)) diff --git a/routlin/validation.py b/routlin/validation.py index 3e1139b..4188648 100644 --- a/routlin/validation.py +++ b/routlin/validation.py @@ -286,16 +286,10 @@ def derive_interface(vlan, data): lan = data.get('network_interfaces', {}).get('lan_interface', 'eth0') if is_wg(vlan): wg_vlans = [v for v in data.get('vlans', []) if is_wg(v)] - wg_sorted = sorted( - wg_vlans, - key=lambda v: ( - derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) is None, - derive_vlan_id(v.get('subnet', ''), v.get('subnet_mask', 24)) or 0, - ) - ) + wg_sorted = sorted(wg_vlans, key=lambda v: (v.get('vlan_id') is None, v.get('vlan_id') or 0)) idx = next((i for i, v in enumerate(wg_sorted) if v is vlan), 0) return f'wg{idx}' - vid = derive_vlan_id(vlan.get('subnet', ''), vlan.get('subnet_mask', 24)) + vid = vlan.get('vlan_id') return lan if vid == 1 else f'{lan}.{vid}' @@ -314,12 +308,9 @@ def validate_config(data): # Pre-compute per-VLAN vlan_ids and interface names without mutating data _lan = data.get("network_interfaces", {}).get("lan_interface", "eth0") _all_vlans = data.get("vlans", []) - _derived_ids = [ - derive_vlan_id(_v.get("subnet", ""), _v.get("subnet_mask", 24)) - for _v in _all_vlans - ] + _stored_ids = [_v.get("vlan_id") for _v in _all_vlans] _wg_sorted = sorted( - [(i, _derived_ids[i]) for i, _v in enumerate(_all_vlans) if is_wg(_v)], + [(i, _stored_ids[i]) for i, _v in enumerate(_all_vlans) if is_wg(_v)], key=lambda x: (x[1] is None, x[1] or 0) ) _wg_order = {orig_i: wg_idx for wg_idx, (orig_i, _) in enumerate(_wg_sorted)} @@ -328,7 +319,7 @@ def validate_config(data): if is_wg(_vlan): vlan_ifaces.append(f"wg{_wg_order[i]}") else: - _vid = _derived_ids[i] + _vid = _stored_ids[i] vlan_ifaces.append(_lan if _vid == 1 else f"{_lan}.{_vid}") # upstream_dns block ============================================ @@ -377,10 +368,13 @@ def validate_config(data): vlan_networks = {} # iface -> IPv4Network (used for NAT section) for i, (vlan, iface) in enumerate(zip(_all_vlans, vlan_ifaces)): - vlan_id = _derived_ids[i] + vlan_id = _stored_ids[i] name = vlan.get("name", "?") label = f"vlan '{name}' (id={vlan_id})" + if vlan_id is None or not isinstance(vlan_id, int) or not (1 <= vlan_id <= 4094): + errors.append(f"vlan '{name}': vlan_id must be an integer 1–4094 (got {vlan_id!r}).") + if name in seen_names: errors.append(f"{label}: duplicate vlan name '{name}' " f"(also used by id={seen_names[name]}).")