Development

This commit is contained in:
Matthew Grotke 2026-05-27 20:56:30 -04:00
parent d8d1d46fd2
commit eed1d295dc
69 changed files with 3355 additions and 3230 deletions

View file

@ -0,0 +1,254 @@
import copy
import ipaddress
from flask import Blueprint, request, redirect, flash
from auth import require_level
from config_utils import load_config, save_config_with_snapshot, verify_config_hash
import sanitize
import validation as validate
bp = Blueprint('dhcp', __name__)
VIEW = '/view/view_dhcp'
def _row_index():
try:
return int(request.form.get('row_index', ''))
except (ValueError, TypeError):
return None
def _hash_ok():
if not verify_config_hash(request.form.get('config_hash', '')):
flash('Configuration was modified by another session. Please refresh and try again.', 'error')
return False
return True
def _flat_index_to_vlan_res(vlans, flat_idx):
pos = 0
for vi, vlan in enumerate(vlans):
for ri in range(len(vlan.get('reservations', []))):
if pos == flat_idx:
return vi, ri
pos += 1
return None, None
def _parse_ip():
raw = request.form.get('ip', '').strip()
if not raw:
return 'dynamic'
ip = validate.ip(raw)
if not ip:
flash(f'The configuration has not been saved because "{raw}" is not a valid IP address.', 'error')
return None
return ip
def _check_ip_conflicts(ip, vlan):
if ip == 'dynamic':
return None
dhcp = vlan.get('dhcp_information', {})
pool_start = dhcp.get('dynamic_pool_start')
pool_end = dhcp.get('dynamic_pool_end')
if pool_start and pool_end:
try:
if (ipaddress.IPv4Address(pool_start) <= ipaddress.IPv4Address(ip)
<= ipaddress.IPv4Address(pool_end)):
return f'{ip} falls within the dynamic pool range ({pool_start}-{pool_end}).'
except Exception:
pass
identity_ips = {s['ip'] for s in vlan.get('server_identities', []) if s.get('ip')}
if ip in identity_ips:
return f'{ip} is already assigned as a server identity IP.'
return None
@bp.route('/action/add_dhcp_reservation', methods=['POST'])
@require_level('administrator')
def add_dhcp_reservation():
vlan_name = sanitize.name(request.form.get('vlan_name', ''))
description = sanitize.text(request.form.get('description', ''))
hostname = validate.domainname(request.form.get('hostname', ''))
mac = sanitize.mac(request.form.get('mac', ''))
ip = _parse_ip()
radius_client = 'radius_client' in request.form
if ip is None:
return redirect(VIEW)
if not vlan_name:
flash('The configuration has not been saved because a VLAN is required.', 'error')
return redirect(VIEW)
if not mac:
flash('The configuration has not been saved because a MAC address is required.', 'error')
return redirect(VIEW)
if not _hash_ok():
return redirect(VIEW)
cfg = load_config()
vlans = cfg.get('vlans', [])
vlan = next((v for v in vlans if v.get('name') == vlan_name), None)
if vlan is None:
flash(f'The configuration has not been saved because VLAN "{vlan_name}" was not found.', 'error')
return redirect(VIEW)
conflict = _check_ip_conflicts(ip, vlan)
if conflict:
flash(f'The configuration has not been saved because {conflict}', 'error')
return redirect(VIEW)
entry = {
'description': description,
'hostname': hostname,
'mac': mac,
'ip': ip,
'radius_client': radius_client,
'enabled': True,
}
vlan.setdefault('reservations', []).append(entry)
errors = validate.validate_config(cfg)
if errors:
for msg in errors:
flash(msg, 'error')
return redirect(VIEW)
flash(save_config_with_snapshot(
cfg,
path=f'vlans.{vlan_name}.reservations', key=mac, operation='add',
before=None, after=entry,
description=f'Added DHCP reservation: {hostname or mac} ({ip or "dynamic"})',
), 'success')
return redirect(VIEW)
@bp.route('/action/toggle_dhcp_reservation', methods=['POST'])
@require_level('administrator')
def toggle_dhcp_reservation():
idx = _row_index()
if idx is None:
flash('Invalid request.', 'error')
return redirect(VIEW)
if not _hash_ok():
return redirect(VIEW)
cfg = load_config()
vlans = cfg.get('vlans', [])
vi, ri = _flat_index_to_vlan_res(vlans, idx)
if vi is None:
flash('Entry not found.', 'error')
return redirect(VIEW)
res = vlans[vi]['reservations'][ri]
old_enabled = res.get('enabled', True)
res['enabled'] = not old_enabled
errors = validate.validate_config(cfg)
if errors:
for msg in errors:
flash(msg, 'error')
return redirect(VIEW)
vlan_name = vlans[vi]['name']
action = 'Enabled' if not old_enabled else 'Disabled'
flash(save_config_with_snapshot(
cfg,
path=f'vlans.{vlan_name}.reservations', key=res['mac'], operation='toggle',
before={'enabled': old_enabled}, after={'enabled': not old_enabled},
description=f'{action} DHCP reservation: {res.get("hostname") or res["mac"]}',
), 'success')
return redirect(VIEW)
@bp.route('/action/edit_dhcp_reservation', methods=['POST'])
@require_level('administrator')
def edit_dhcp_reservation():
idx = _row_index()
if idx is None:
flash('Invalid request.', 'error')
return redirect(VIEW)
description = sanitize.text(request.form.get('description', ''))
hostname = validate.domainname(request.form.get('hostname', ''))
mac = sanitize.mac(request.form.get('mac', ''))
ip = _parse_ip()
radius_client = 'radius_client' in request.form
if ip is None:
return redirect(VIEW)
if not mac:
flash('The configuration has not been saved because a MAC address is required.', 'error')
return redirect(VIEW)
if not _hash_ok():
return redirect(VIEW)
cfg = load_config()
vlans = cfg.get('vlans', [])
vi, ri = _flat_index_to_vlan_res(vlans, idx)
if vi is None:
flash('Entry not found.', 'error')
return redirect(VIEW)
conflict = _check_ip_conflicts(ip, vlans[vi])
if conflict:
flash(f'The configuration has not been saved because {conflict}', 'error')
return redirect(VIEW)
res = vlans[vi]['reservations'][ri]
before = copy.deepcopy(res)
res.update({
'description': description,
'hostname': hostname,
'mac': mac,
'ip': ip,
'radius_client': radius_client,
'enabled': 'enabled' in request.form,
})
errors = validate.validate_config(cfg)
if errors:
for msg in errors:
flash(msg, 'error')
return redirect(VIEW)
vlan_name = vlans[vi]['name']
flash(save_config_with_snapshot(
cfg,
path=f'vlans.{vlan_name}.reservations', key=mac, operation='edit',
before=before, after=copy.deepcopy(res),
description=f'Edited DHCP reservation: {hostname or mac} ({ip or "dynamic"})',
), 'success')
return redirect(VIEW)
@bp.route('/action/delete_dhcp_reservation', methods=['POST'])
@require_level('administrator')
def delete_dhcp_reservation():
idx = _row_index()
if idx is None:
flash('Invalid request.', 'error')
return redirect(VIEW)
if not _hash_ok():
return redirect(VIEW)
cfg = load_config()
vlans = cfg.get('vlans', [])
vi, ri = _flat_index_to_vlan_res(vlans, idx)
if vi is None:
flash('Entry not found.', 'error')
return redirect(VIEW)
vlan_name = vlans[vi]['name']
removed = vlans[vi]['reservations'].pop(ri)
errors = validate.validate_config(cfg)
if errors:
for msg in errors:
flash(msg, 'error')
return redirect(VIEW)
flash(save_config_with_snapshot(
cfg,
path=f'vlans.{vlan_name}.reservations', key=removed['mac'], operation='delete',
before=removed, after=None,
description=f'Deleted DHCP reservation: {removed.get("hostname") or removed["mac"]}',
), 'success')
return redirect(VIEW)

View file

@ -0,0 +1,221 @@
{
"id": "view_dhcp",
"client_requirement": "client_is_viewer+",
"items": [
{
"type": "header_page_title",
"items": [
{
"type": "h1",
"text": "DHCP"
},
{
"type": "p",
"text": "Active leases, IP reservations, and VLAN authorizations."
}
]
},
{
"type": "table",
"datasource": "live:dhcp_leases",
"empty_message": "No active DHCP leases found.",
"columns": [
{
"label": "Hostname",
"field": "hostname"
},
{
"label": "IP Address",
"field": "ip_address",
"class": "col-mono"
},
{
"label": "MAC Address",
"field": "mac_address",
"class": "col-mono"
},
{
"label": "VLAN",
"field": "vlan_name"
},
{
"label": "Expires",
"field": "expires"
}
]
},
{
"type": "table",
"datasource": "config:dhcp_reservations",
"empty_message": "No DHCP reservations configured.",
"columns": [
{
"label": "Description",
"field": "description"
},
{
"label": "Hostname",
"field": "hostname",
"class": "col-mono"
},
{
"label": "MAC",
"field": "mac",
"class": "col-mono"
},
{
"label": "IP",
"field": "ip",
"class": "col-mono"
},
{
"label": "VLAN",
"field": "vlan_name"
},
{
"label": "RADIUS",
"field": "radius_client",
"render": "badge_yes_no"
},
{
"label": "Status",
"field": "enabled",
"render": "badge_enabled_disabled"
}
],
"toolbar": {
"items": [
{
"type": "select",
"name": "vlan_filter",
"value": "all",
"options": "%VLAN_FILTER_OPTIONS%",
"filter_col": "vlan_name"
}
]
},
"row_actions": [
{
"client_requirement": "client_is_administrator+",
"action": "/action/edit_dhcp_reservation",
"method": "inline_edit",
"text": "Edit",
"class": "btn-ghost btn-sm",
"fields": [
{
"col": "description",
"input_type": "text"
},
{
"col": "hostname",
"input_type": "text",
"validate": "networkname"
},
{
"col": "mac",
"input_type": "text",
"validate": "mac"
},
{
"col": "ip",
"input_type": "text"
},
{
"col": "radius_client",
"input_type": "checkbox",
"checkbox_label": "Enabled"
},
{
"col": "enabled",
"input_type": "checkbox",
"checkbox_label": "Enabled"
}
]
},
{
"client_requirement": "client_is_administrator+",
"action": "/action/delete_dhcp_reservation",
"method": "post",
"text": "Delete",
"class": "btn-danger btn-sm"
}
]
},
{
"type": "card",
"id": "add-form",
"label": "Add Reservation/Authorization",
"client_requirement": "client_is_administrator+",
"items": [
{
"type": "form",
"action": "/action/add_dhcp_reservation",
"method": "post",
"items": [
{
"type": "field",
"label": "VLAN",
"name": "vlan_name",
"input_type": "select",
"options": "%VLAN_NAMES_AS_OPTIONS%",
"hint": "VLAN this reservation belongs to."
},
{
"type": "field",
"label": "Description",
"name": "description",
"input_type": "text",
"placeholder": "e.g. NAS"
},
{
"type": "field",
"label": "Hostname",
"name": "hostname",
"input_type": "text",
"validate": "networkname",
"placeholder": "e.g. nas"
},
{
"type": "field",
"label": "MAC Address",
"name": "mac",
"input_type": "text",
"validate": "mac",
"placeholder": "e.g. aa:bb:cc:dd:ee:ff"
},
{
"type": "field",
"label": "IP Address",
"name": "ip",
"input_type": "text",
"placeholder": "e.g. 192.168.10.50",
"hint": "Leave blank to authorize device on this VLAN dynamically."
},
{
"type": "field",
"label": "RADIUS Client",
"name": "radius_client",
"input_type": "checkbox",
"hint": "This device acts as a RADIUS authenticator, verifying credentials of other devices on the network."
},
{
"type": "button_row",
"items": [
{
"type": "button_primary",
"action": "/action/add_dhcp_reservation",
"method": "post",
"text": "Add"
},
{
"type": "button_cancel",
"text": "Cancel"
}
]
}
]
}
]
}
]
}