Files
RouterOS/RouterOSAssistant/Features/Wizard/Steps/Setup/SetupViewModel.swift
T
KayandClaude Sonnet 5 fc3b2ca039 M8: Netzwerk-Isolation live verifiziert (manuell + über den Wizard)
Isolation zuerst manuell per SSH nachgebaut (ether5), danach über den
App-Wizard (Experte-Modus, ether4), um die eigentliche Abnahme-
Bedingung ("kompletter Wizard-Durchlauf") zu erfüllen. Dabei drei
App-Bugs gefunden und gefixt:

- Bug 22: neues LAN-/VLAN-Interface wurde nie der defconf-Interface-
  Liste "LAN" hinzugefügt, wodurch DNS-Anfragen an den Router selbst
  blockiert blieben (Werks-Firewall droppt Input von allem außerhalb
  dieser Liste).
- Bug 23: ein voller Wizard-Durchlauf gegen einen bereits konfigurierten
  Router brach am ersten nicht-idempotenten Add-Befehl ab
  (/ip address, /ip pool, /ip dhcp-server, /ip dhcp-server network).
- Bug 24: ein als eigenes isoliertes Netz konfiguriertes Interface
  blieb Bridge-"Slave" (Werks-Bridging), wodurch RouterOS die
  generierten Isolationsregeln selbst als ungültig verwarf.

Alle drei in DhcpServerCommandBuilder/SetupViewModel gefixt, 52 Unit-
Tests grün, Isolation+DNS+Internet am echten Gerät bestätigt. M8 auf
live verifiziert gesetzt. Nebenbei zwei veraltete Doku-Stellen zum
Gitea-Remote korrigiert.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YDmUd93KxsYGr2kLTotWnG
2026-09-15 10:28:09 +02:00

289 lines
12 KiB
Swift

import Foundation
enum SetupStep: Int, CaseIterable {
case mode
case wan
case lan
case vlan
case wifi
case firewall
case review
}
/// Simple restricts the wizard to basic setup (single LAN, fixed firewall baseline, no VLANs,
/// no per-port DHCP/isolation) for users who just want a working router. Expert exposes every
/// RouterOS feature the wizard supports.
enum SetupMode {
case simple
case expert
}
@MainActor
final class SetupViewModel: ObservableObject {
@Published var step: SetupStep = .mode
@Published var mode: SetupMode = .simple
@Published var wanConfig = WanConfig(interfaceName: "ether1")
@Published var lanConfigs: [LanDhcpConfig] = [LanDhcpConfig()]
@Published private(set) var vlanSectionEnabled = false
@Published var vlans: [VlanEntry] = []
@Published var wifiNetworks: [WifiNetworkConfig] = []
@Published private(set) var unsupportedWifiInterfaces: [NetworkInterface] = []
@Published private(set) var firewallSectionEnabled = false
@Published private(set) var existingFirewallRuleCounts: FirewallRuleCounts?
@Published private(set) var isLoadingFirewallRuleCounts = false
@Published private(set) var firewallRuleCountsError: String?
@Published private(set) var isApplying = false
@Published private(set) var applyLog: [String] = []
@Published private(set) var applyError: String?
@Published private(set) var didApplySuccessfully = false
private let connectionService: ConnectionService
private let backupService: BackupService
init(connectionService: ConnectionService, backupService: BackupService = BackupService()) {
self.connectionService = connectionService
self.backupService = backupService
prepareDefaults(from: connectionService.interfaces)
}
var plannedCommands: [RouterOSCommand] {
wanConfig.buildCommands()
+ lanConfigs.flatMap { $0.buildCommands() }
+ vlans.flatMap { $0.buildCommands() }
+ wifiNetworks.flatMap { $0.buildCommands() }
+ (firewallSectionEnabled
? FirewallConfig(wanInterface: wanConfig.interfaceName, networks: networkSegments).buildCommands()
: [])
}
/// All configured LAN + VLAN networks, for the firewall isolation rules.
private var networkSegments: [FirewallConfig.NetworkSegment] {
lanConfigs.map { FirewallConfig.NetworkSegment(interfaceName: $0.interfaceName, isolated: $0.isolated) }
+ vlans.map { FirewallConfig.NetworkSegment(interfaceName: $0.interfaceName, isolated: $0.isolated) }
}
/// Interface names of networks marked isolated, for display on the Firewall step.
var isolatedNetworkNames: [String] {
networkSegments.filter(\.isolated).map(\.interfaceName)
}
func setFirewallSectionEnabled(_ enabled: Bool) {
firewallSectionEnabled = enabled
if enabled {
loadExistingFirewallRuleCounts()
} else {
existingFirewallRuleCounts = nil
firewallRuleCountsError = nil
}
}
func loadExistingFirewallRuleCounts() {
guard firewallSectionEnabled, existingFirewallRuleCounts == nil, !isLoadingFirewallRuleCounts else { return }
isLoadingFirewallRuleCounts = true
firewallRuleCountsError = nil
Task {
do {
existingFirewallRuleCounts = try await connectionService.fetchFirewallRuleCounts()
} catch {
firewallRuleCountsError = error.localizedDescription
}
isLoadingFirewallRuleCounts = false
}
}
func setVlanSectionEnabled(_ enabled: Bool) {
vlanSectionEnabled = enabled
if !enabled { vlans = [] }
}
func addVlan() {
let usedIDs = Set(vlans.map(\.vlanID))
var nextID = 20
while usedIDs.contains(nextID) { nextID += 1 }
vlans.append(VlanEntry(vlanID: nextID, parentInterface: lanConfigs.first?.interfaceName ?? "bridge"))
}
func removeVlan(_ id: VlanEntry.ID) {
vlans.removeAll { $0.id == id }
}
func addLan() {
let usedNames = Set([wanConfig.interfaceName] + lanConfigs.map(\.interfaceName))
let nextInterface = connectionService.interfaces.first { !usedNames.contains($0.name) }
lanConfigs.append(LanDhcpConfig(interfaceName: nextInterface?.name ?? "bridge"))
}
func removeLan(_ id: LanDhcpConfig.ID) {
guard lanConfigs.count > 1 else { return }
lanConfigs.removeAll { $0.id == id }
}
/// Replaces the placeholder WAN/LAN interface names ("ether1"/"bridge") with real ones
/// from the connected device, whenever the current value isn't actually one of its
/// interfaces — otherwise the Picker selections don't match any of their tags.
func prepareDefaults(from interfaces: [NetworkInterface]) {
guard !interfaces.isEmpty else { return }
let names = Set(interfaces.map(\.name))
if !names.contains(wanConfig.interfaceName) {
if let firstEthernet = interfaces.first(where: { $0.type.lowercased().contains("ether") }) {
wanConfig.interfaceName = firstEthernet.name
} else {
wanConfig.interfaceName = interfaces[0].name
}
}
if !lanConfigs.isEmpty, !names.contains(lanConfigs[0].interfaceName) {
if let bridge = interfaces.first(where: { $0.type.lowercased().contains("bridge") }) {
lanConfigs[0].interfaceName = bridge.name
} else if let fallback = interfaces.first(where: { $0.name != wanConfig.interfaceName }) {
lanConfigs[0].interfaceName = fallback.name
} else {
lanConfigs[0].interfaceName = interfaces[0].name
}
}
if wifiNetworks.isEmpty {
let legacyWireless = interfaces.filter { $0.type.lowercased() == "wlan" }
wifiNetworks = legacyWireless.map { WifiNetworkConfig(interfaceName: $0.name) }
}
unsupportedWifiInterfaces = interfaces.filter { $0.type.lowercased() == "wifi" }
}
func goNext() {
switch step {
case .mode:
if mode == .simple { applySimpleModeConstraints() }
step = .wan
case .wan:
step = .lan
case .lan:
step = (mode == .expert) ? .vlan : .wifi
case .vlan:
step = .wifi
case .wifi:
step = .firewall
case .firewall:
step = .review
case .review:
break
}
}
func goBack() {
switch step {
case .mode:
break
case .wan:
step = .mode
case .lan:
step = .wan
case .vlan:
step = .lan
case .wifi:
step = (mode == .expert) ? .vlan : .lan
case .firewall:
step = .wifi
case .review:
step = .firewall
}
}
/// Simple mode allows only one LAN network, no isolation, no VLANs, and a fixed firewall
/// baseline — strip anything an earlier Expert-mode choice may have left configured.
private func applySimpleModeConstraints() {
vlanSectionEnabled = false
vlans = []
if lanConfigs.count > 1 { lanConfigs = Array(lanConfigs.prefix(1)) }
if !lanConfigs.isEmpty { lanConfigs[0].isolated = false }
setFirewallSectionEnabled(true)
}
func apply(credentials: RouterOSCredentials) {
isApplying = true
applyError = nil
applyLog = []
didApplySuccessfully = false
Task {
do {
applyLog.append("Sichere aktuelle Konfiguration…")
_ = try await backupService.createBackup(for: credentials)
for command in plannedCommands {
applyLog.append(command.summary)
try await applyIdempotently(command)
}
didApplySuccessfully = true
} catch {
applyError = error.localizedDescription
}
isApplying = false
}
}
/// Menus where a duplicate `.add` should instead reconfigure the existing entry in place —
/// re-running any wizard step against an already-configured router hits this on every menu
/// that enforces uniqueness (dhcp-client/pppoe-client: one per interface, live-confirmed
/// "failure: dhcp-client on that interface already exists"; pool/dhcp-server: one per name;
/// dhcp-server network: one per address). The value is which field of the (deterministic,
/// app-generated) arguments identifies the existing entry to match on for the `.set` retry.
/// "/ip address" is deliberately not here — an interface can legitimately hold several
/// addresses, so matching a `.set` by "interface" alone could reconfigure the wrong one;
/// see `duplicateTolerantMenuPaths` below for how that menu is handled instead.
private static let retryAsSetMenuPaths: [String: String] = [
"/ip dhcp-client": "interface",
"/interface pppoe-client": "interface",
"/ip pool": "name",
"/ip dhcp-server": "name",
"/ip dhcp-server network": "address"
]
/// Menus where a duplicate `.add` means the desired state already holds, with nothing
/// meaningful left to update — "/interface list"/"/interface list member" (fixed,
/// hardcoded arguments; list membership is binary, no ".set" equivalent) and "/ip address"
/// (the address string itself is the app's only identifying argument here — if RouterOS
/// already has that exact address on that exact interface, this add's whole job is already
/// done, and matching a `.set` by "interface" would risk touching a different address on a
/// multi-address interface instead, per the note above).
private static let duplicateTolerantMenuPaths: Set<String> = ["/interface list", "/interface list member", "/ip address"]
/// Menus where a `.remove` finding no match means the desired state already holds — used for
/// `DhcpServerCommandBuilder`'s unconditional "detach this interface from any bridge" step,
/// which runs even for interfaces that were never bridged (the common case). SSH's
/// `remove [find ...]` is already a silent no-op there; REST's `findItemID` throws
/// "not found" instead (see `RestTransport.apply`), so that specific failure needs to be
/// swallowed here to keep both transports behaving the same way.
private static let missingTolerantRemoveMenuPaths: Set<String> = ["/interface bridge port"]
private func applyIdempotently(_ command: RouterOSCommand) async throws {
do {
try await connectionService.apply(command)
} catch {
if case .remove = command.operation, Self.missingTolerantRemoveMenuPaths.contains(command.menuPath) {
return
}
guard case .add = command.operation else { throw error }
if Self.duplicateTolerantMenuPaths.contains(command.menuPath) {
return
}
guard let matchField = Self.retryAsSetMenuPaths[command.menuPath],
let matchValue = command.arguments[matchField] else {
throw error
}
let retryCommand = RouterOSCommand.set(
menuPath: command.menuPath,
restPath: command.restPath,
matchField: matchField,
matchValue: matchValue,
arguments: command.arguments,
summary: command.summary
)
try await connectionService.apply(retryCommand)
}
}
}