SPB Git

Repository Public License

NetworkLabView.swift 22.1 KB 380 lines swift

1// ORIX Secure2// File: App/Sources/Features/Network/NetworkLabView.swift3// Description: Network Lab: the live connection as iOS reports it, findings about proxy / VPN indicator / Wi-Fi security, probes4//              against a host the user chooses (DNS, TCP latency, certificate), a local-network service scan, and the change log.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDesign9import ORIXNetworkLab10import ORIXSecureModel11import SwiftUI1213struct NetworkLabView: View {14    @Environment(AppModel.self) private var model15    @State private var host = "apple.com"16    @State private var saved = false17    @State private var showCertificate: X509Certificate?18    @FocusState private var focused: Bool1920    private var network: NetworkController { model.network }2122    var body: some View {23        ScreenScroll {24            connectionCard25            if !network.findings.isEmpty {26                ORIXSectionHeader("Connection findings")27                FindingList(findings: network.findings.prioritized())28            }29            wifiSection30            probeSection31            localNetworkSection32            changesSection33            LimitsCard(title: "What a network test from an app cannot see", items: [34                String(localized: "The traffic of other apps, and what happens to your traffic beyond the first hop."),35                String(localized: "The router's configuration, its firmware and the full list of devices connected to it."),36                String(localized: "Whether the Wi-Fi uses WPA2 or WPA3: iOS only says open, WEP, personal or enterprise."),37                String(localized: "Which DNS resolver answered (system, encrypted DNS profile or VPN)."),38            ])39        }40        .navigationTitle("Network Lab")41        .toolbar {42            ToolbarItemGroup(placement: .topBarTrailing) {43                Button {44                    if let report = network.report() { saved = model.store.save(report); ORIXHaptics.success() }45                } label: { Label("Save Report", systemImage: saved ? "checkmark" : "square.and.arrow.down") }46                    .disabled(network.input == nil)47                    .accessibilityIdentifier("network.save")48                Button { Task { await network.assess(); saved = false } } label: { Label("Refresh", systemImage: "arrow.clockwise") }49                    .accessibilityIdentifier("network.refresh")50            }51        }52        .task {53            network.startMonitoring()54            if network.input == nil { await network.assess() }55        }56        .sheet(item: $showCertificate) { CertificateView(certificate: $0) }57        .accessibilityIdentifier("network")58    }5960    // MARK: Connection6162    private var connectionCard: some View {63        VStack(alignment: .leading, spacing: ORIX.Space.sm) {64            if let snapshot = network.snapshot {65                HStack(spacing: ORIX.Space.sm) {66                    Image(systemName: snapshot.status == .satisfied ? (snapshot.isOnWiFi ? "wifi" : (snapshot.isOnCellular ? "antenna.radiowaves.left.and.right" : "network")) : "wifi.slash")67                        .font(.system(size: 28)).foregroundStyle(snapshot.status == .satisfied ? ORIXAccent.secure.primary : ORIX.Palette.textTertiary)68                        .frame(width: 44).accessibilityHidden(true)69                    VStack(alignment: .leading, spacing: 2) {70                        Text(verbatim: snapshot.status.title).font(.orixTitle).foregroundStyle(ORIX.Palette.textPrimary)71                        Text(verbatim: snapshot.interfaceKinds.map(\.title).joined(separator: " · ")).font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)72                    }73                }74                .accessibilityElement(children: .combine)75                FlowChips {76                    ORIXChip(Text(snapshot.supportsIPv4 ? "IPv4" : "No IPv4"), systemName: snapshot.supportsIPv4 ? "checkmark" : "minus")77                    ORIXChip(Text(snapshot.supportsIPv6 ? "IPv6" : "No IPv6"), systemName: snapshot.supportsIPv6 ? "checkmark" : "minus")78                    ORIXChip(Text(snapshot.supportsDNS ? "DNS reported" : "DNS not reported"), systemName: snapshot.supportsDNS ? "checkmark" : "minus")79                    if snapshot.isExpensive { ORIXChip(Text("Metered"), systemName: "dollarsign.circle") }80                    if snapshot.isConstrained { ORIXChip(Text("Low Data Mode"), systemName: "tortoise") }81                }82                if let reason = snapshot.unsatisfiedReason, snapshot.status != .satisfied {83                    Text(verbatim: reason.title).font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)84                }85                if let addresses = network.input?.interfaces.value?.filter({ !$0.flags.isLoopback && $0.flags.isUp }), !addresses.isEmpty {86                    Divider()87                    ForEach(addresses.prefix(8)) { address in88                        HStack {89                            Text(verbatim: address.name).font(.orixMono).foregroundStyle(ORIX.Palette.textSecondary).frame(width: 64, alignment: .leading)90                            Text(verbatim: address.address).font(.orixMono).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1).truncationMode(.middle)91                            Spacer(minLength: 4)92                            Text(verbatim: address.scope.title).font(.caption2).foregroundStyle(ORIX.Palette.textTertiary)93                        }94                        .accessibilityElement(children: .combine)95                    }96                }97            } else {98                ProgressView().frame(maxWidth: .infinity)99            }100        }101        .frame(maxWidth: .infinity, alignment: .leading)102        .orixCard()103        .accessibilityElement(children: .contain)104        .accessibilityIdentifier("network.connection")105    }106107    // MARK: Wi-Fi108109    @ViewBuilder private var wifiSection: some View {110        ORIXSectionHeader("Wi-Fi security")111        VStack(alignment: .leading, spacing: ORIX.Space.sm) {112            switch network.input?.wifi {113            case .measured(let wifi):114                ReadingRow(label: String(localized: "Network"), value: .measured(wifi.ssid))115                ReadingRow(label: String(localized: "Security type"), value: .measured(wifi.security.title),116                           note: String(localized: "iOS reports open, WEP, personal or enterprise — not the WPA generation."))117                ReadingRow(label: String(localized: "Access point (BSSID)"), value: .measured(wifi.bssid))118            case .unavailable(let reason):119                Label("Not available", systemImage: "minus.circle").font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)120                Text(verbatim: reason.detail).font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)121                if reason.kind == .simulator || reason.kind == .unsupportedOnDevice {122                    EmptyView()123                } else if network.locationAuthorization == .notDetermined {124                    Text("Apple lets an app read the Wi-Fi name and security type only with Location permission. ORIX Secure uses it for that alone and never reads your position.")125                        .font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)126                    Button { network.requestLocationForWiFi() } label: { Label("Allow to Read Wi-Fi Security", systemImage: "wifi") }.buttonStyle(.orixSecondary)127                        .accessibilityIdentifier("network.wifiPermission")128                } else if network.locationAuthorization == .denied || network.locationAuthorization == .authorizedReducedAccuracy {129                    Button { openSettings() } label: { Label("Open Settings", systemImage: "gear") }.buttonStyle(.orixSecondary)130                }131            case nil:132                ProgressView()133            }134        }135        .frame(maxWidth: .infinity, alignment: .leading)136        .orixCard()137        .accessibilityElement(children: .contain)138        .accessibilityIdentifier("network.wifi")139    }140141    // MARK: Probes142143    @ViewBuilder private var probeSection: some View {144        ORIXSectionHeader("Test a host")145        VStack(alignment: .leading, spacing: ORIX.Space.sm) {146            Text("Resolves the name, times five TCP connections to port 443 and reads the certificate. Only this host is contacted.")147                .font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)148            HStack(spacing: ORIX.Space.sm) {149                TextField("Host name", text: $host)150                    .textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL).font(.orixMono)151                    .focused($focused)152                    .padding(ORIX.Space.sm)153                    .background(ORIX.Palette.surfaceRaised, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))154                    .accessibilityIdentifier("network.host")155                Button { focused = false; Task { await network.runProbes(on: host) } } label: { Text("Run") }156                    .buttonStyle(.borderedProminent)157                    .disabled(NetworkController.host(from: host) == nil || network.isRunning("tls") || network.isRunning("dns"))158                    .accessibilityIdentifier("network.run")159            }160        }161        .orixCard()162        if let probed = network.probedHost {163            probeCard(title: "Name resolution", key: "dns", identifier: "network.dns") {164                if let dns = network.dns {165                    if let failure = dns.failure {166                        Label { Text(verbatim: failure.reason) } icon: { Image(systemName: "exclamationmark.triangle") }.font(.orixCallout).foregroundStyle(ORIX.Palette.textPrimary)167                    } else {168                        ReadingRow(label: String(localized: "Resolved in"), value: .measured(ORIXFormat.milliseconds(dns.duration)))169                        ForEach(dns.addresses, id: \.address) { address in170                            Text(verbatim: address.address).font(.orixMono).foregroundStyle(ORIX.Palette.textPrimary).textSelection(.enabled)171                        }172                    }173                }174            }175            probeCard(title: "TCP connection time", key: "latency", identifier: "network.latency") {176                if let latency = network.latency {177                    switch latency.statistics {178                    case .measured(let stats):179                        ReadingRow(label: String(localized: "Median"), value: .measured(ORIXFormat.milliseconds(stats.median)))180                        ReadingRow(label: String(localized: "Fastest / slowest"), value: .measured("\(ORIXFormat.milliseconds(stats.minimum)) / \(ORIXFormat.milliseconds(stats.maximum))"))181                        ReadingRow(label: String(localized: "Jitter"), value: .measured(ORIXFormat.milliseconds(stats.jitter)))182                        ReadingRow(label: String(localized: "Failed attempts"), value: .measured("\(stats.lossCount) / \(stats.sampleCount)"))183                        LatencyBars(samples: latency.samples)184                    case .unavailable(let reason):185                        Text(verbatim: reason.detail).font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)186                    }187                    Text("TCP handshake time to port \(Int(latency.port)), not an ICMP ping.").font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)188                }189            }190            probeCard(title: "Certificate and TLS", key: "tls", identifier: "network.tls") {191                if let tls = network.tls { tlsContent(tls) }192            }193            if let tls = network.tls, !tls.findings.isEmpty {194                FindingList(findings: tls.findings.prioritized())195            }196            if network.tls != nil {197                VStack(alignment: .leading, spacing: ORIX.Space.sm) {198                    Text("Optional: send one HEAD request to https://\(probed)/ to read its redirect and HSTS policy. This is a real web request to that site.")199                        .font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)200                    Button { Task { await network.runHTTPSProbe() } } label: { Label("Check HTTPS Policy", systemImage: "lock.rotation") }.buttonStyle(.orixSecondary)201                        .disabled(network.isRunning("https"))202                        .accessibilityIdentifier("network.https")203                    if let https = network.https {204                        if let failure = https.failure { Text(verbatim: failure).font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary) }205                        if let status = https.finalStatus { ReadingRow(label: String(localized: "Final status"), value: .measured("\(status)")) }206                        if let final = https.finalURL { ReadingRow(label: String(localized: "Final address"), value: .measured(final)) }207                        ReadingRow(label: "HSTS", value: .measured(https.hsts == nil ? String(localized: "Not sent") : String(localized: "Sent")))208                    }209                }210                .orixCard()211                if let https = network.https, !https.findings.isEmpty { FindingList(findings: https.findings) }212            }213        }214    }215216    private func probeCard(title: LocalizedStringKey, key: String, identifier: String, @ViewBuilder content: () -> some View) -> some View {217        VStack(alignment: .leading, spacing: ORIX.Space.xs) {218            HStack {219                Text(title).font(.orixHeadline).foregroundStyle(ORIX.Palette.textPrimary)220                Spacer()221                if network.isRunning(key) { ProgressView() }222            }223            content()224        }225        .frame(maxWidth: .infinity, alignment: .leading)226        .orixCard()227        .accessibilityElement(children: .contain)228        .accessibilityIdentifier(identifier)229    }230231    @ViewBuilder private func tlsContent(_ tls: TLSInspection) -> some View {232        if let failure = tls.failure, !tls.handshakeCompleted {233            Label { Text(verbatim: failure) } icon: { Image(systemName: "exclamationmark.triangle") }.font(.orixCallout).foregroundStyle(ORIX.Palette.textPrimary)234        }235        ReadingRow(label: String(localized: "Protocol"), value: tls.protocolVersion.map(\.rawValue))236        ReadingRow(label: String(localized: "Cipher suite"), value: tls.cipherSuite.map(\.name))237        ReadingRow(label: String(localized: "System trust"), value: tls.trust.map { $0.isTrusted ? String(localized: "Trusted by iOS") : ($0.errorDescription ?? String(localized: "Not trusted")) })238        if let covered = tls.hostnameCovered {239            ReadingRow(label: String(localized: "Certificate covers this host"), value: .measured(covered ? String(localized: "Yes") : String(localized: "No")))240        }241        ForEach(Array(tls.chain.enumerated()), id: \.element.id) { index, certificate in242            Button { showCertificate = certificate } label: {243                HStack {244                    Image(systemName: index == 0 ? "doc.badge.gearshape" : "arrow.turn.down.right").foregroundStyle(ORIXAccent.secure.primary).accessibilityHidden(true)245                    VStack(alignment: .leading, spacing: 1) {246                        Text(verbatim: certificate.subject.shortDisplay).font(.orixCallout).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)247                        Text("Valid until \(certificate.notAfter.formatted(date: .abbreviated, time: .omitted))").font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)248                    }249                    Spacer()250                    Image(systemName: "chevron.right").font(.footnote).foregroundStyle(ORIX.Palette.textTertiary).accessibilityHidden(true)251                }252                .contentShape(Rectangle())253            }254            .buttonStyle(.plain)255            .accessibilityIdentifier("network.certificate.\(index)")256        }257    }258259    // MARK: Local network260261    @ViewBuilder private var localNetworkSection: some View {262        ORIXSectionHeader("Local network services")263        VStack(alignment: .leading, spacing: ORIX.Space.sm) {264            Text("Lists devices that announce services (AirPlay, printers, file sharing…) for six seconds. iOS asks for Local Network permission the first time.")265                .font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)266            Button { Task { await network.browseLocalNetwork() } } label: { Label("Scan Local Network", systemImage: "dot.radiowaves.left.and.right") }267                .buttonStyle(.orixSecondary)268                .disabled(network.isRunning("bonjour"))269                .accessibilityIdentifier("network.bonjour")270            if network.isRunning("bonjour") { ProgressView() }271            let services = network.bonjour?.value?.services ?? network.bonjourLive272            ForEach(services) { service in273                HStack {274                    VStack(alignment: .leading, spacing: 1) {275                        Text(verbatim: service.name).font(.orixCallout).foregroundStyle(ORIX.Palette.textPrimary)276                        Text(verbatim: LocalNetworkBrowser.label(forServiceType: service.type)).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)277                    }278                    Spacer()279                    Text(verbatim: service.type).font(.caption2.monospaced()).foregroundStyle(ORIX.Palette.textTertiary)280                }281                .accessibilityElement(children: .combine)282            }283            switch network.bonjour {284            case .measured(let summary):285                Text("\(summary.services.count) service(s) found. Only devices that announce these services are visible; this is not an inventory of the network.")286                    .font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)287            case .unavailable(let reason):288                Text(verbatim: reason.detail).font(.orixCallout).foregroundStyle(ORIX.Palette.textSecondary)289            case nil:290                EmptyView()291            }292        }293        .frame(maxWidth: .infinity, alignment: .leading)294        .orixCard()295        .accessibilityElement(children: .contain)296        .accessibilityIdentifier("network.local")297    }298299    // MARK: Changes300301    @ViewBuilder private var changesSection: some View {302        if !network.changes.isEmpty {303            ORIXSectionHeader("Connection changes while the app was open")304            VStack(alignment: .leading, spacing: ORIX.Space.sm) {305                ForEach(network.changes.prefix(10)) { change in306                    VStack(alignment: .leading, spacing: 1) {307                        Text(verbatim: change.timestamp.formatted(date: .omitted, time: .standard)).font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)308                        Text(verbatim: change.descriptions.joined(separator: " · ")).font(.orixCallout).foregroundStyle(ORIX.Palette.textPrimary)309                    }310                    .accessibilityElement(children: .combine)311                }312            }313            .frame(maxWidth: .infinity, alignment: .leading)314            .orixCard()315        }316    }317}318319/// One bar per connection attempt; a failed attempt is drawn as a hollow marker, never as a zero.320struct LatencyBars: View {321    let samples: [LatencySample]322    var body: some View {323        let peak = max(samples.compactMap(\.duration).max() ?? 0, 0.001)324        HStack(alignment: .bottom, spacing: 6) {325            ForEach(samples) { sample in326                if let duration = sample.duration {327                    RoundedRectangle(cornerRadius: 3).fill(ORIXAccent.secure.primary).frame(width: 18, height: max(4, 44 * duration / peak))328                } else {329                    RoundedRectangle(cornerRadius: 3).strokeBorder(ORIX.Palette.warning, style: StrokeStyle(lineWidth: 1.5, dash: [3])).frame(width: 18, height: 44)330                }331            }332        }333        .frame(height: 48, alignment: .bottom)334        .accessibilityElement()335        .accessibilityLabel(Text("Connection times"))336        .accessibilityValue(Text(verbatim: samples.map { $0.duration.map { ORIXFormat.milliseconds($0) } ?? String(localized: "failed") }.joined(separator: ", ")))337    }338}339340struct CertificateView: View {341    let certificate: X509Certificate342    @Environment(\.dismiss) private var dismiss343    var body: some View {344        NavigationStack {345            ScreenScroll {346                VStack(spacing: 0) {347                    row("Subject", certificate.subject.display)348                    row("Issuer", certificate.issuer.display)349                    row("Valid from", certificate.notBefore.formatted(date: .abbreviated, time: .shortened))350                    row("Valid until", certificate.notAfter.formatted(date: .abbreviated, time: .shortened))351                    row("Days remaining", "\(certificate.daysRemaining(at: Date()))")352                    row("Public key", certificate.publicKey.display)353                    row("Signature", certificate.signatureAlgorithm.name)354                    row("Serial number", certificate.serialNumber)355                    row("Certificate authority", certificate.isCA ? String(localized: "Yes") : String(localized: "No"))356                    if !certificate.subjectAlternativeNames.dnsNames.isEmpty { row("Names covered", certificate.subjectAlternativeNames.dnsNames.prefix(30).joined(separator: "\n")) }357                    row("SHA-256 fingerprint", certificate.sha256Fingerprint)358                }359                .orixCard(padding: ORIX.Space.sm)360                Text("Parsed on the device from the certificate the server presented. A valid certificate identifies the site; it does not make the site trustworthy.")361                    .font(.orixCaption).foregroundStyle(ORIX.Palette.textTertiary)362            }363            .navigationTitle("Certificate")364            .navigationBarTitleDisplayMode(.inline)365            .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() }.accessibilityIdentifier("certificate.done") } }366        }367        .accessibilityIdentifier("certificate")368    }369370    private func row(_ label: LocalizedStringKey, _ value: String) -> some View {371        VStack(alignment: .leading, spacing: 2) {372            Text(label).font(.orixCaption).foregroundStyle(ORIX.Palette.textSecondary)373            Text(verbatim: value).font(.orixMono).foregroundStyle(ORIX.Palette.textPrimary).textSelection(.enabled)374        }375        .padding(.vertical, 6)376        .frame(maxWidth: .infinity, alignment: .leading)377        .accessibilityElement(children: .combine)378    }379}380
Files main
Menu

Theme