rusty-fez 0.4.0

Agent-native management CLI for Fedora/RHEL (drives cockpit-bridge)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
//! Firewall management over firewalld (`org.fedoraproject.FirewallD1`).
//!
//! Reads (status/list/show/services) open an unprivileged `dbus-json3` channel;
//! mutations (add/remove service/port, set-default-zone, reload, confirm,
//! panic) open a privileged one and escalate. fez holds no state: the
//! runtime-vs-permanent split that guards against lockout is firewalld's own,
//! read live each call and committed only via `runtimeToPermanent`.

use crate::capabilities::{render_with_hints, View};
use crate::cli::{Cli, FirewallAction};
use crate::error::{is_service_unknown, FezError, Result};
use crate::protocol::client::BridgeClient;
use crate::transport;
use serde_json::{json, Value};

const FW_NAME: &str = "org.fedoraproject.FirewallD1";
const FW_PATH: &str = "/org/fedoraproject/FirewallD1";
const FW_IFACE: &str = "org.fedoraproject.FirewallD1";
const FW_ZONE_IFACE: &str = "org.fedoraproject.FirewallD1.zone";
const FW_CONFIG_PATH: &str = "/org/fedoraproject/FirewallD1/config";
const FW_CONFIG_IFACE: &str = "org.fedoraproject.FirewallD1.config";
const FW_CONFIG_ZONE_IFACE: &str = "org.fedoraproject.FirewallD1.config.zone";

/// Route a parsed `firewall` action to its handler and return the exit code.
pub fn dispatch(cli: &Cli, action: &FirewallAction) -> i32 {
    let view = run(cli, action);
    render_with_hints(cli, view, error_hints)
}

/// Safe read-only follow-up hints for an actionable firewall error (issue #60).
///
/// A `dependency-missing` failure points at the service-status check (fez
/// cannot tell absent from stopped, so the hint covers both); an
/// `unsupported-api` failure tells the caller the feature is unavailable on
/// this firewalld and not to retry. Other errors carry no firewall-specific
/// hint.
fn error_hints(e: &FezError) -> Option<Value> {
    match e {
        FezError::DependencyMissing { .. } => Some(json!({
            "checkService": "fez services status firewalld.service --json",
            "install": "dnf install firewalld",
        })),
        FezError::UnsupportedApi(method) => Some(json!({
            "unsupported": format!(
                "firewalld on this host does not expose {method}; treat the feature as unsupported"
            ),
        })),
        _ => None,
    }
}

/// The [`FezError::DependencyMissing`] returned when firewalld is absent.
fn dependency_missing() -> FezError {
    FezError::DependencyMissing {
        component: "firewalld".into(),
        dbus_name: FW_NAME.into(),
        remediation: "Install firewalld on the target (dnf install firewalld) and enable+start it (systemctl enable --now firewalld.service), then retry.".into(),
    }
}

/// Connect to the bridge and dispatch the requested action.
fn run(cli: &Cli, action: &FirewallAction) -> Result<View> {
    let transport = transport::from_host(cli.host.as_deref());
    let mut client = BridgeClient::connect(transport.as_ref())?;
    let host = client.host().to_string();
    match action {
        FirewallAction::Status => {
            let ch = open_channel(&mut client, false)?;
            status(&mut client, &ch, host)
        }
        FirewallAction::List => {
            let ch = open_channel(&mut client, false)?;
            list(&mut client, &ch, host)
        }
        FirewallAction::Show { zone } => {
            let ch = open_channel(&mut client, false)?;
            show(&mut client, &ch, host, zone)
        }
        FirewallAction::Services => {
            let ch = open_channel(&mut client, false)?;
            services(&mut client, &ch, host)
        }
        // Every mutation routes through the privileged path.
        _ => mutate(cli, &mut client, host, action),
    }
}

/// Open a firewalld `dbus-json3` channel (privileged for mutations).
///
/// firewalld activation failure (the service is absent) surfaces on the first
/// method call, not at open time; the caller probes it via [`fw_call`], which
/// maps ServiceUnknown to [`dependency_missing`]. A privileged open escalates
/// first and can itself fail with `AccessDenied` (exit 11).
///
/// # Errors
///
/// Propagates any channel-open or escalation error from the bridge client.
fn open_channel(client: &mut BridgeClient, privileged: bool) -> Result<String> {
    if privileged {
        client.dbus_open_privileged(FW_NAME)
    } else {
        client.dbus_open(FW_NAME)
    }
}

/// Call a firewalld method on the main object, mapping ServiceUnknown to the
/// dependency-missing error.
fn fw_call(
    client: &mut BridgeClient,
    channel: &str,
    iface: &str,
    method: &str,
    args: Value,
) -> Result<Value> {
    fw_call_path(client, channel, FW_PATH, iface, method, args)
}

/// Call a firewalld method on an explicit object path, mapping low-level
/// transport/D-Bus failures to actionable firewall errors via [`map_fw_error`].
fn fw_call_path(
    client: &mut BridgeClient,
    channel: &str,
    path: &str,
    iface: &str,
    method: &str,
    args: Value,
) -> Result<Value> {
    client
        .dbus_call(channel, path, iface, method, args)
        .map_err(|e| map_fw_error(e, method))
}

/// Map a raw bridge/D-Bus failure to an actionable firewall error (issue #60).
///
/// firewalld is D-Bus-activated, so an absent or failed service is not
/// observably distinct from "installed but stopped": both surface as the name
/// being unreachable. We therefore collapse all of those to
/// [`dependency_missing`] (whose remediation covers install **and**
/// enable+start) rather than inventing a `service-inactive` code fez cannot
/// reliably detect:
/// - `Dbus { ServiceUnknown | NameHasNoOwner }`: name not activatable.
/// - `Problem("not-found")`: cockpit closed the channel because the name could
///   not be reached (the symptom reported in #60).
/// - `Problem("not-supported")`: the bus refused the name.
///
/// A `Dbus { UnknownMethod }` means firewalld is reachable but too old to
/// expose the method; that maps to [`FezError::UnsupportedApi`] carrying the
/// method name, so a caller treats the feature as unsupported instead of
/// recommending an install. All other errors pass through unchanged, so the
/// raw cause is preserved when it is already actionable (e.g. `AccessDenied`).
fn map_fw_error(e: FezError, method: &str) -> FezError {
    match e {
        FezError::Dbus { ref name, .. } if is_service_unknown(name) => dependency_missing(),
        FezError::Dbus { ref name, .. } if name.contains("UnknownMethod") => {
            FezError::UnsupportedApi(method.to_string())
        }
        FezError::Problem(ref p) if p == "not-found" || p == "not-supported" => {
            dependency_missing()
        }
        other => other,
    }
}

/// First out-arg of a reply as a string array.
fn arg_str_vec(out: &Value) -> Vec<String> {
    out.get(0)
        .and_then(Value::as_array)
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default()
}

/// First out-arg of a reply as a single string.
fn arg_str(out: &Value) -> String {
    out.get(0).and_then(Value::as_str).unwrap_or("").to_string()
}

/// First out-arg of a reply as a bool.
fn arg_bool(out: &Value) -> bool {
    out.get(0).and_then(Value::as_bool).unwrap_or(false)
}

/// Render a `getPorts` `aas` reply (each entry `[port, proto]`) as
/// `"port/proto"` labels.
fn ports_from_reply(out: &Value) -> Vec<String> {
    out.get(0)
        .and_then(Value::as_array)
        .map(|a| a.iter().map(port_label).filter(|s| !s.is_empty()).collect())
        .unwrap_or_default()
}

/// Join a firewalld `[port, protocol]` entry into a `"port/proto"` label.
/// A malformed entry renders empty.
fn port_label(entry: &Value) -> String {
    let port = entry.get(0).and_then(Value::as_str).unwrap_or("");
    let proto = entry.get(1).and_then(Value::as_str).unwrap_or("");
    if port.is_empty() || proto.is_empty() {
        String::new()
    } else {
        format!("{port}/{proto}")
    }
}

/// Parse a `port/proto` spec into `(port, protocol)`.
///
/// # Errors
///
/// Returns [`FezError::NotFound`] when the spec is not `<u16>/<proto>` with a
/// non-empty protocol (used as a bad-argument signal; renders exit 4).
fn parse_port_spec(spec: &str) -> Result<(u16, String)> {
    let (port, proto) = spec
        .split_once('/')
        .ok_or_else(|| FezError::NotFound(format!("port spec {spec:?} (expected port/proto)")))?;
    let port: u16 = port
        .parse()
        .map_err(|_| FezError::NotFound(format!("port {port:?} (expected 1-65535)")))?;
    if proto.is_empty() {
        return Err(FezError::NotFound(format!(
            "port spec {spec:?} (empty protocol)"
        )));
    }
    Ok((port, proto.to_string()))
}

/// Compute runtime-vs-permanent drift as a list of `"+/-kind value"` tokens.
///
/// `+` means present at runtime but not permanent (would be lost on reload);
/// `-` means present permanent but not runtime (removed at runtime, not yet
/// committed). Covers services, ports, and masquerade. Stateless: both sides
/// are read live each call.
fn compute_drift(
    runtime_services: &[String],
    permanent_services: &[String],
    runtime_ports: &[String],
    permanent_ports: &[String],
    runtime_masquerade: bool,
    permanent_masquerade: bool,
) -> Vec<String> {
    let mut drift = Vec::new();
    for s in runtime_services {
        if !permanent_services.contains(s) {
            drift.push(format!("+service {s}"));
        }
    }
    for s in permanent_services {
        if !runtime_services.contains(s) {
            drift.push(format!("-service {s}"));
        }
    }
    for p in runtime_ports {
        if !permanent_ports.contains(p) {
            drift.push(format!("+port {p}"));
        }
    }
    for p in permanent_ports {
        if !runtime_ports.contains(p) {
            drift.push(format!("-port {p}"));
        }
    }
    if runtime_masquerade && !permanent_masquerade {
        drift.push("+masquerade".to_string());
    }
    if permanent_masquerade && !runtime_masquerade {
        drift.push("-masquerade".to_string());
    }
    drift
}

/// Whether a permanent-config read failed because firewalld rejected the
/// `config.info` polkit action. This is distinct from failing to open a
/// privileged cockpit channel: the read reached firewalld, but firewalld denied
/// the config API.
fn is_config_info_denied(e: &FezError) -> bool {
    match e {
        FezError::Dbus { name, message } => {
            name.contains("NotAuthorized")
                || name.contains("AccessDenied")
                || message.contains("config.info")
        }
        _ => false,
    }
}

/// Read the permanent (`config`) services, ports, and masquerade for a zone,
/// for drift.
fn permanent_zone(
    client: &mut BridgeClient,
    channel: &str,
    zone: &str,
) -> Result<(Vec<String>, Vec<String>, bool)> {
    let obj = fw_call_path(
        client,
        channel,
        FW_CONFIG_PATH,
        FW_CONFIG_IFACE,
        "getZoneByName",
        json!([zone]),
    )?;
    let zone_path = arg_str(&obj);
    let services = arg_str_vec(&fw_call_path(
        client,
        channel,
        &zone_path,
        FW_CONFIG_ZONE_IFACE,
        "getServices",
        json!([]),
    )?);
    let ports = ports_from_reply(&fw_call_path(
        client,
        channel,
        &zone_path,
        FW_CONFIG_ZONE_IFACE,
        "getPorts",
        json!([]),
    )?);
    let masquerade = arg_bool(&fw_call_path(
        client,
        channel,
        &zone_path,
        FW_CONFIG_ZONE_IFACE,
        "getMasquerade",
        json!([]),
    )?);
    Ok((services, ports, masquerade))
}

/// Read the runtime services, ports, and masquerade for a zone.
fn runtime_zone(
    client: &mut BridgeClient,
    channel: &str,
    zone: &str,
) -> Result<(Vec<String>, Vec<String>, bool)> {
    let services = arg_str_vec(&fw_call(
        client,
        channel,
        FW_ZONE_IFACE,
        "getServices",
        json!([zone]),
    )?);
    let ports = ports_from_reply(&fw_call(
        client,
        channel,
        FW_ZONE_IFACE,
        "getPorts",
        json!([zone]),
    )?);
    let masquerade = arg_bool(&fw_call(
        client,
        channel,
        FW_ZONE_IFACE,
        "getMasquerade",
        json!([zone]),
    )?);
    Ok((services, ports, masquerade))
}

/// `firewall status`: state, default zone, panic flag, and pending drift.
///
/// Runtime reads (default zone, panic flag, the runtime zone's services/ports)
/// go over the unprivileged `channel`. The permanent-config read needed for
/// drift is polkit-gated (firewalld's `PK_ACTION_CONFIG`, `auth_admin_keep` on
/// both server and desktop installs), so it is issued on a separate privileged
/// channel that escalates first. A host with no usable escalation mechanism
/// therefore fails `status` with `access-denied` (exit 11) rather than
/// silently reporting empty drift.
fn status(client: &mut BridgeClient, channel: &str, host: String) -> Result<View> {
    let default_zone = arg_str(&fw_call(
        client,
        channel,
        FW_IFACE,
        "getDefaultZone",
        json!([]),
    )?);
    let panic = arg_bool(&fw_call(
        client,
        channel,
        FW_IFACE,
        "queryPanicMode",
        json!([]),
    )?);
    let (rt_services, rt_ports, rt_masq) = runtime_zone(client, channel, &default_zone)?;
    // Permanent config is polkit-gated; read it on a privileged channel.
    let priv_channel = open_channel(client, true)?;
    let drift = match permanent_zone(client, &priv_channel, &default_zone) {
        Ok((perm_services, perm_ports, perm_masq)) => Some(compute_drift(
            &rt_services,
            &perm_services,
            &rt_ports,
            &perm_ports,
            rt_masq,
            perm_masq,
        )),
        Err(e) if is_config_info_denied(&e) => None,
        Err(e) => return Err(e),
    };

    let data = json!({
        "running": true,
        "default_zone": default_zone,
        "panic_mode": panic,
        "masquerade": rt_masq,
        "pending_changes": drift.clone().unwrap_or_default(),
        "pending_changes_available": drift.is_some(),
    });
    let mut human = format!(
        "running:       yes\ndefault zone:  {default_zone}\npanic mode:    {}\nmasquerade:    {}\n",
        if panic { "on" } else { "off" },
        if rt_masq { "on" } else { "off" }
    );
    let hints = match drift {
        Some(drift) if drift.is_empty() => {
            human.push_str("pending:       none\n");
            None
        }
        Some(drift) => {
            human.push_str(&format!("pending:       {}\n", drift.join(", ")));
            Some(json!({
                "warning": "uncommitted runtime changes; run `fez firewall confirm` to persist or `fez firewall reload` to discard",
                "pending": drift,
            }))
        }
        None => {
            human.push_str("pending:       unavailable (permanent config not readable)\n");
            Some(json!({
                "warning": "permanent firewall config was not readable; runtime status is shown but pending_changes may be incomplete",
                "follow_up": "Check firewalld config.info authorization for the target user or run `fez firewall status` from a context allowed by polkit."
            }))
        }
    };
    Ok(View::new("FirewallStatus", host, data, human).with_hints_opt(hints))
}

/// `firewall list`: every zone with a per-zone summary.
fn list(client: &mut BridgeClient, channel: &str, host: String) -> Result<View> {
    let zones = arg_str_vec(&fw_call(
        client,
        channel,
        FW_ZONE_IFACE,
        "getZones",
        json!([]),
    )?);
    let default_zone = arg_str(&fw_call(
        client,
        channel,
        FW_IFACE,
        "getDefaultZone",
        json!([]),
    )?);

    let columns = ["zone", "default", "services", "ports", "interfaces"];
    let mut rows = Vec::new();
    let mut human = format!(
        "{:<12} {:<8} {:<24} {:<16} {}\n",
        "ZONE", "DEFAULT", "SERVICES", "PORTS", "INTERFACES"
    );
    for zone in &zones {
        let (services, ports, _masquerade) = runtime_zone(client, channel, zone)?;
        let interfaces = arg_str_vec(&fw_call(
            client,
            channel,
            FW_ZONE_IFACE,
            "getInterfaces",
            json!([zone]),
        )?);
        let is_default = *zone == default_zone;
        human.push_str(&format!(
            "{:<12} {:<8} {:<24} {:<16} {}\n",
            zone,
            if is_default { "yes" } else { "" },
            services.join(","),
            ports.join(","),
            interfaces.join(","),
        ));
        rows.push(json!([
            zone,
            is_default,
            services.join(","),
            ports.join(","),
            interfaces.join(","),
        ]));
    }
    Ok(View::new(
        "FirewallZoneList",
        host,
        crate::envelope::table_data(&columns, rows),
        human,
    ))
}

/// `firewall show <zone>`: one zone's full detail.
fn show(client: &mut BridgeClient, channel: &str, host: String, zone: &str) -> Result<View> {
    let zones = arg_str_vec(&fw_call(
        client,
        channel,
        FW_ZONE_IFACE,
        "getZones",
        json!([]),
    )?);
    if !zones.iter().any(|z| z == zone) {
        return Err(FezError::NotFound(format!("firewall zone {zone}")));
    }
    let (services, ports, masquerade) = runtime_zone(client, channel, zone)?;
    let interfaces = arg_str_vec(&fw_call(
        client,
        channel,
        FW_ZONE_IFACE,
        "getInterfaces",
        json!([zone]),
    )?);
    let sources = arg_str_vec(&fw_call(
        client,
        channel,
        FW_ZONE_IFACE,
        "getSources",
        json!([zone]),
    )?);
    let data = json!({
        "zone": zone,
        "services": services,
        "ports": ports,
        "interfaces": interfaces,
        "sources": sources,
        "masquerade": masquerade,
    });
    let human = format!(
        "Zone:       {zone}\nServices:   {}\nPorts:      {}\nInterfaces: {}\nSources:    {}\nMasquerade: {}\n",
        services.join(", "),
        ports.join(", "),
        interfaces.join(", "),
        sources.join(", "),
        if masquerade { "on" } else { "off" },
    );
    Ok(View::new("FirewallZone", host, data, human))
}

/// `firewall services`: the service catalog firewalld knows about.
fn services(client: &mut BridgeClient, channel: &str, host: String) -> Result<View> {
    let mut catalog = arg_str_vec(&fw_call(
        client,
        channel,
        FW_IFACE,
        "listServices",
        json!([]),
    )?);
    catalog.sort();
    let mut human = String::new();
    for s in &catalog {
        human.push_str(s);
        human.push('\n');
    }
    Ok(View::new(
        "FirewallServiceCatalog",
        host,
        json!({ "services": catalog }),
        human,
    ))
}

/// The set of firewall services treated as session-critical (always `ssh`).
fn session_services() -> Vec<String> {
    vec!["ssh".to_string()]
}

/// Parse the server-side port (4th field) out of an `SSH_CONNECTION` value.
fn session_port_from(ssh_connection: &str) -> Option<u16> {
    ssh_connection.split_whitespace().nth(3)?.parse().ok()
}

/// The session-critical port set, derived live from `$SSH_CONNECTION`.
/// Empty when fez is invoked locally (no SSH session).
fn session_ports() -> Vec<u16> {
    std::env::var("SSH_CONNECTION")
        .ok()
        .and_then(|c| session_port_from(&c))
        .into_iter()
        .collect()
}

/// Resolve the effective zone for a mutation: the `--zone` flag, or the live
/// default zone when omitted.
fn effective_zone(
    client: &mut BridgeClient,
    channel: &str,
    requested: &Option<String>,
) -> Result<String> {
    match requested {
        Some(z) => Ok(z.clone()),
        None => Ok(arg_str(&fw_call(
            client,
            channel,
            FW_IFACE,
            "getDefaultZone",
            json!([]),
        )?)),
    }
}

/// Run a privileged firewalld mutation: open the privileged channel, apply the
/// protected guards, audit attempt/result around the runtime-only call, and
/// attach the confirm hint.
fn mutate(
    cli: &Cli,
    client: &mut BridgeClient,
    host: String,
    action: &FirewallAction,
) -> Result<View> {
    let channel = open_channel(client, true)?;

    match action {
        FirewallAction::AddService {
            service,
            zone,
            timeout,
        } => {
            let zone = effective_zone(client, &channel, zone)?;
            let t = i64::from(timeout.unwrap_or(0));
            run_audited(
                client,
                &channel,
                &host,
                "add-service",
                &format!("{zone}:{service}"),
                FW_ZONE_IFACE,
                "addService",
                json!([zone, service, t]),
            )?;
            Ok(change_view(
                host,
                "add-service",
                &zone,
                &format!("service {service}"),
                *timeout,
            ))
        }
        FirewallAction::RemoveService { service, zone } => {
            let zone = effective_zone(client, &channel, zone)?;
            crate::safety::check_firewall_service_removal(service, &session_services(), cli.force)?;
            run_audited(
                client,
                &channel,
                &host,
                "remove-service",
                &format!("{zone}:{service}"),
                FW_ZONE_IFACE,
                "removeService",
                json!([zone, service]),
            )?;
            Ok(change_view(
                host,
                "remove-service",
                &zone,
                &format!("service {service}"),
                None,
            ))
        }
        FirewallAction::AddPort {
            port,
            zone,
            timeout,
        } => {
            let (p, proto) = parse_port_spec(port)?;
            let zone = effective_zone(client, &channel, zone)?;
            let t = i64::from(timeout.unwrap_or(0));
            run_audited(
                client,
                &channel,
                &host,
                "add-port",
                &format!("{zone}:{p}/{proto}"),
                FW_ZONE_IFACE,
                "addPort",
                json!([zone, p.to_string(), proto, t]),
            )?;
            Ok(change_view(
                host,
                "add-port",
                &zone,
                &format!("port {p}/{proto}"),
                *timeout,
            ))
        }
        FirewallAction::RemovePort { port, zone } => {
            let (p, proto) = parse_port_spec(port)?;
            let zone = effective_zone(client, &channel, zone)?;
            crate::safety::check_firewall_port_removal(p, &session_ports(), cli.force)?;
            run_audited(
                client,
                &channel,
                &host,
                "remove-port",
                &format!("{zone}:{p}/{proto}"),
                FW_ZONE_IFACE,
                "removePort",
                json!([zone, p.to_string(), proto]),
            )?;
            Ok(change_view(
                host,
                "remove-port",
                &zone,
                &format!("port {p}/{proto}"),
                None,
            ))
        }
        FirewallAction::SetDefaultZone { zone } => {
            crate::safety::check_firewall_default_zone(cli.force)?;
            run_audited(
                client,
                &channel,
                &host,
                "set-default-zone",
                zone,
                FW_IFACE,
                "setDefaultZone",
                json!([zone]),
            )?;
            Ok(change_view(
                host,
                "set-default-zone",
                zone,
                "default zone",
                None,
            ))
        }
        FirewallAction::Reload => {
            let default_zone = arg_str(&fw_call(
                client,
                &channel,
                FW_IFACE,
                "getDefaultZone",
                json!([]),
            )?);
            let (rt_s, rt_p, rt_m) = runtime_zone(client, &channel, &default_zone)?;
            let has_drift = match permanent_zone(client, &channel, &default_zone) {
                Ok((pm_s, pm_p, pm_m)) => {
                    !compute_drift(&rt_s, &pm_s, &rt_p, &pm_p, rt_m, pm_m).is_empty()
                }
                Err(e) if is_config_info_denied(&e) => true,
                Err(e) => return Err(e),
            };
            crate::safety::check_firewall_reload(has_drift, cli.force)?;
            run_audited(
                client,
                &channel,
                &host,
                "reload",
                "firewall",
                FW_IFACE,
                "reload",
                json!([]),
            )?;
            Ok(reload_view(host))
        }
        FirewallAction::Confirm => {
            run_audited(
                client,
                &channel,
                &host,
                "confirm",
                "firewall",
                FW_IFACE,
                "runtimeToPermanent",
                json!([]),
            )?;
            Ok(confirm_view(host))
        }
        FirewallAction::Panic { state } => {
            let on = state == "on";
            if on {
                crate::safety::check_firewall_panic_on(cli.force)?;
            }
            let method = if on {
                "enablePanicMode"
            } else {
                "disablePanicMode"
            };
            run_audited(
                client,
                &channel,
                &host,
                &format!("panic-{state}"),
                "firewall",
                FW_IFACE,
                method,
                json!([]),
            )?;
            Ok(panic_view(host, on))
        }
        FirewallAction::Masquerade {
            state,
            zone,
            timeout,
        } => {
            let on = state == "on";
            let zone = effective_zone(client, &channel, zone)?;
            if !on {
                crate::safety::check_firewall_masquerade_off(cli.force)?;
            }
            let (method, args) = if on {
                let t = i64::from(timeout.unwrap_or(0));
                ("addMasquerade", json!([zone, t]))
            } else {
                ("removeMasquerade", json!([zone]))
            };
            run_audited(
                client,
                &channel,
                &host,
                &format!("masquerade-{state}"),
                &zone,
                FW_ZONE_IFACE,
                method,
                args,
            )?;
            Ok(masquerade_view(
                host,
                &zone,
                on,
                if on { *timeout } else { None },
            ))
        }
        // Reads are dispatched in `run`; they never reach `mutate`. Return a
        // defensive error rather than panicking, so a future refactor that
        // reroutes a read here fails gracefully instead of aborting.
        FirewallAction::Status
        | FirewallAction::List
        | FirewallAction::Show { .. }
        | FirewallAction::Services => Err(FezError::Problem("read action routed to mutate".into())),
    }
}

/// Audit the attempt, run the runtime-only firewalld call, audit the result.
#[allow(clippy::too_many_arguments)]
fn run_audited(
    client: &mut BridgeClient,
    channel: &str,
    host: &str,
    operation: &str,
    target: &str,
    iface: &str,
    method: &str,
    args: Value,
) -> Result<()> {
    let sink = crate::audit::sink_from_env();
    let ctx = crate::audit::AuditContext::new(
        &crate::audit::actor(),
        host,
        operation,
        target,
        &crate::audit::correlation_id(),
    );
    sink.write(&ctx.record(crate::audit::Outcome::Attempt));
    let exec = fw_call(client, channel, iface, method, args);
    match &exec {
        Ok(_) => sink.write(&ctx.record(crate::audit::Outcome::Ok)),
        Err(e) => sink.write(&ctx.record(crate::audit::Outcome::Error(e.to_string()))),
    }
    exec.map(|_| ())
}

/// The standard "runtime-only; confirm to persist" hint.
fn confirm_hint() -> Value {
    json!({
        "persisted": false,
        "note": "runtime-only change; run `fez firewall confirm` to persist it",
    })
}

/// Build the `FirewallChange` view for an add/remove/set mutation.
fn change_view(host: String, op: &str, zone: &str, what: &str, timeout: Option<u32>) -> View {
    let mut data = json!({
        "operation": op,
        "zone": zone,
        "change": what,
        "persisted": false,
    });
    if let Some(t) = timeout {
        data["timeout"] = json!(t);
    }
    let human = format!("{op} {what} in zone {zone} (runtime only)\n");
    View::new("FirewallChange", host, data, human).with_hints(confirm_hint())
}

/// Build the `FirewallChange` view for `reload`.
fn reload_view(host: String) -> View {
    View::new(
        "FirewallChange",
        host,
        json!({"operation": "reload", "persisted": true}),
        "reloaded permanent config into runtime\n".into(),
    )
}

/// Build the `FirewallConfirm` view for `confirm`.
fn confirm_view(host: String) -> View {
    View::new(
        "FirewallConfirm",
        host,
        json!({"operation": "confirm", "persisted": true}),
        "runtime config committed to permanent\n".into(),
    )
}

/// Build the `FirewallChange` view for `panic on|off`.
fn panic_view(host: String, on: bool) -> View {
    View::new(
        "FirewallChange",
        host,
        json!({"operation": "panic", "panic_mode": on, "persisted": false}),
        format!("panic mode {}\n", if on { "enabled" } else { "disabled" }),
    )
}

/// Build the `FirewallChange` view for `masquerade on|off`.
fn masquerade_view(host: String, zone: &str, on: bool, timeout: Option<u32>) -> View {
    let mut data = json!({
        "operation": "masquerade",
        "zone": zone,
        "change": if on { "+masquerade" } else { "-masquerade" },
        "masquerade": on,
        "persisted": false,
    });
    if let Some(t) = timeout {
        data["timeout"] = json!(t);
    }
    let human = format!(
        "masquerade {} in zone {zone} (runtime only)\n",
        if on { "enabled" } else { "disabled" }
    );
    View::new("FirewallChange", host, data, human).with_hints(confirm_hint())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn dbus(name: &str) -> FezError {
        FezError::Dbus {
            name: name.into(),
            message: "boom".into(),
        }
    }

    #[test]
    fn map_fw_error_service_unknown_is_dependency_missing() {
        let mapped = map_fw_error(
            dbus("org.freedesktop.DBus.Error.ServiceUnknown"),
            "getZones",
        );
        assert_eq!(mapped.code(), "dependency-missing");
        assert_eq!(mapped.exit_code(), 9);
        // NameHasNoOwner (the other activation-failure name) maps the same way.
        assert_eq!(
            map_fw_error(
                dbus("org.freedesktop.DBus.Error.NameHasNoOwner"),
                "getZones"
            )
            .code(),
            "dependency-missing"
        );
    }

    #[test]
    fn map_fw_error_unknown_method_is_unsupported_api() {
        let mapped = map_fw_error(
            dbus("org.freedesktop.DBus.Error.UnknownMethod"),
            "getMasquerade",
        );
        assert_eq!(mapped.code(), "unsupported-api");
        assert_eq!(mapped.exit_code(), 12);
        // The method name is carried for the caller.
        assert!(matches!(
            mapped,
            FezError::UnsupportedApi(ref m) if m == "getMasquerade"
        ));
    }

    #[test]
    fn map_fw_error_channel_problem_is_dependency_missing() {
        for problem in ["not-found", "not-supported"] {
            let mapped = map_fw_error(FezError::Problem(problem.into()), "getZones");
            assert_eq!(
                mapped.code(),
                "dependency-missing",
                "Problem({problem}) should map to dependency-missing"
            );
        }
    }

    #[test]
    fn map_fw_error_passes_through_unrelated_errors() {
        // A channel problem that is not an activation symptom is left as-is, so
        // its already-actionable raw cause survives (here: an unrelated
        // "authentication-failed" -> code auth-failed, not dependency-missing).
        assert_eq!(
            map_fw_error(
                FezError::Problem("authentication-failed".into()),
                "getZones"
            )
            .code(),
            "auth-failed"
        );
        // AccessDenied is untouched.
        let denied = FezError::AccessDenied {
            remediation: "enable sudo".into(),
        };
        assert_eq!(map_fw_error(denied, "getZones").code(), "access-denied");
    }

    #[test]
    fn parse_port_spec_splits_port_and_proto() {
        assert_eq!(
            parse_port_spec("8080/tcp").unwrap(),
            (8080, "tcp".to_string())
        );
        assert_eq!(parse_port_spec("53/udp").unwrap(), (53, "udp".to_string()));
    }

    #[test]
    fn parse_port_spec_rejects_garbage() {
        assert!(parse_port_spec("nope").is_err());
        assert!(parse_port_spec("8080").is_err());
        assert!(parse_port_spec("99999/tcp").is_err()); // out of u16 range
        assert!(parse_port_spec("80/").is_err());
    }

    #[test]
    fn port_label_joins_port_and_proto() {
        assert_eq!(port_label(&json!(["9090", "tcp"])), "9090/tcp");
        // A malformed entry renders empty rather than panicking.
        assert_eq!(port_label(&json!([])), "");
    }

    #[test]
    fn drift_reports_runtime_only_ports() {
        // runtime has 9090/tcp + ssh; permanent has only ssh -> one added port.
        let runtime_ports = vec!["9090/tcp".to_string()];
        let permanent_ports: Vec<String> = vec![];
        let runtime_services = vec!["ssh".to_string()];
        let permanent_services = vec!["ssh".to_string()];
        let drift = compute_drift(
            &runtime_services,
            &permanent_services,
            &runtime_ports,
            &permanent_ports,
            false,
            false,
        );
        assert_eq!(drift, vec!["+port 9090/tcp".to_string()]);
    }

    #[test]
    fn drift_empty_when_runtime_matches_permanent() {
        let s = vec!["ssh".to_string()];
        let p: Vec<String> = vec![];
        assert!(compute_drift(&s, &s, &p, &p, false, false).is_empty());
    }

    #[test]
    fn drift_reports_removed_service() {
        // permanent has http but runtime does not -> service removed at runtime.
        let runtime_services: Vec<String> = vec![];
        let permanent_services = vec!["http".to_string()];
        let p: Vec<String> = vec![];
        let drift = compute_drift(&runtime_services, &permanent_services, &p, &p, false, false);
        assert_eq!(drift, vec!["-service http".to_string()]);
    }

    #[test]
    fn drift_reports_masquerade_added_at_runtime() {
        // runtime masquerade on, permanent off -> +masquerade.
        let s = vec!["ssh".to_string()];
        let p: Vec<String> = vec![];
        let drift = compute_drift(&s, &s, &p, &p, true, false);
        assert_eq!(drift, vec!["+masquerade".to_string()]);
    }

    #[test]
    fn drift_reports_masquerade_removed_at_runtime() {
        let s = vec!["ssh".to_string()];
        let p: Vec<String> = vec![];
        let drift = compute_drift(&s, &s, &p, &p, false, true);
        assert_eq!(drift, vec!["-masquerade".to_string()]);
    }

    #[test]
    fn drift_empty_when_masquerade_matches() {
        let s = vec!["ssh".to_string()];
        let p: Vec<String> = vec![];
        assert!(compute_drift(&s, &s, &p, &p, true, true).is_empty());
    }

    #[test]
    fn session_port_parses_ssh_connection() {
        // SSH_CONNECTION = "client_ip client_port server_ip server_port".
        assert_eq!(session_port_from("10.0.0.1 5520 10.0.0.2 22"), Some(22));
        assert_eq!(session_port_from("10.0.0.1 5520 10.0.0.2 2222"), Some(2222));
    }

    #[test]
    fn session_port_none_when_absent_or_malformed() {
        assert_eq!(session_port_from(""), None);
        assert_eq!(session_port_from("garbage"), None);
        assert_eq!(session_port_from("a b c notaport"), None);
    }

    #[test]
    fn session_services_always_includes_ssh() {
        assert_eq!(session_services(), vec!["ssh".to_string()]);
    }
}