unifly-api 0.9.2

Async Rust client, reactive data layer, and domain model for UniFi controller APIs
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
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::model::{EntityId, FirewallAction};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateFirewallPolicyRequest {
    pub name: String,
    pub action: FirewallAction,
    #[serde(alias = "source_zone")]
    pub source_zone_id: EntityId,
    #[serde(alias = "dest_zone")]
    pub destination_zone_id: EntityId,
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(default, alias = "logging")]
    pub logging_enabled: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub allow_return_traffic: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ip_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection_states: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_filter: Option<TrafficFilterSpec>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destination_filter: Option<TrafficFilterSpec>,
}

fn default_true() -> bool {
    true
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateFirewallPolicyRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<FirewallAction>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub allow_return_traffic: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ip_version: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub connection_states: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_filter: Option<TrafficFilterSpec>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destination_filter: Option<TrafficFilterSpec>,
    #[serde(skip_serializing_if = "Option::is_none", alias = "logging")]
    pub logging_enabled: Option<bool>,
}

/// Port-side specification: either inline values or a reference to a
/// firewall port-group by its `external_id`. Mirrors the controller's
/// portFilter wire shape.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum PortSpec {
    /// Inline port values (single ports or ranges like `"8000-9000"`).
    Values {
        items: Vec<String>,
        #[serde(default)]
        match_opposite: bool,
    },
    /// Reference to a port-group via its `external_id` UUID.
    MatchingList {
        list_id: String,
        #[serde(default)]
        match_opposite: bool,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(
    tag = "type",
    rename_all = "snake_case",
    from = "TrafficFilterSpecWire"
)]
pub enum TrafficFilterSpec {
    Network {
        network_ids: Vec<String>,
        #[serde(default)]
        match_opposite: bool,
        /// Optional port restriction (the API nests portFilter inside the
        /// network/IP filter rather than treating it as a separate type).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        ports: Option<PortSpec>,
    },
    IpAddress {
        addresses: Vec<String>,
        #[serde(default)]
        match_opposite: bool,
        /// Optional port restriction.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        ports: Option<PortSpec>,
    },
    Port {
        ports: PortSpec,
    },
    /// Address-group filter referencing a firewall group (address-group)
    /// by its `external_id`. May carry an optional port restriction in
    /// the same filter (mirrors what `IpAddress` supports for inline
    /// addresses).
    IpMatchingList {
        list_id: String,
        #[serde(default)]
        match_opposite: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        ports: Option<PortSpec>,
    },
}

/// Internal wire-format wrapper used during deserialization to accept
/// pre-PortSpec JSON files. The legacy `Port` variant stored ports as a
/// flat `Vec<String>` with `match_opposite` at the variant level. The
/// legacy `port_matching_list` top-level variant carried a port-group
/// reference; it lowers to `Port { ports: PortSpec::MatchingList { ... } }`.
#[derive(Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum TrafficFilterSpecWire {
    Network {
        network_ids: Vec<String>,
        #[serde(default)]
        match_opposite: bool,
        #[serde(default, deserialize_with = "deserialize_port_spec_opt")]
        ports: Option<PortSpec>,
    },
    IpAddress {
        addresses: Vec<String>,
        #[serde(default)]
        match_opposite: bool,
        #[serde(default, deserialize_with = "deserialize_port_spec_opt")]
        ports: Option<PortSpec>,
    },
    Port {
        #[serde(deserialize_with = "deserialize_port_spec")]
        ports: PortSpec,
        /// Legacy field: pre-PortSpec the Port variant carried
        /// `match_opposite` at the variant level. Folded into the inner
        /// `PortSpec` during conversion.
        #[serde(default)]
        match_opposite: bool,
    },
    /// Legacy top-level port-group reference. Lowered to `Port` with a
    /// nested `PortSpec::MatchingList` during conversion.
    PortMatchingList {
        list_id: String,
        #[serde(default)]
        match_opposite: bool,
    },
    /// Address-group filter. Optional `ports` companion supports rules
    /// like "members of address-group X on port-group Y" in one filter.
    IpMatchingList {
        list_id: String,
        #[serde(default)]
        match_opposite: bool,
        #[serde(default, deserialize_with = "deserialize_port_spec_opt")]
        ports: Option<PortSpec>,
    },
}

impl From<TrafficFilterSpecWire> for TrafficFilterSpec {
    fn from(wire: TrafficFilterSpecWire) -> Self {
        match wire {
            TrafficFilterSpecWire::Network {
                network_ids,
                match_opposite,
                ports,
            } => Self::Network {
                network_ids,
                match_opposite,
                ports,
            },
            TrafficFilterSpecWire::IpAddress {
                addresses,
                match_opposite,
                ports,
            } => Self::IpAddress {
                addresses,
                match_opposite,
                ports,
            },
            TrafficFilterSpecWire::Port {
                mut ports,
                match_opposite: legacy_mo,
            } => {
                if legacy_mo {
                    match &mut ports {
                        PortSpec::Values { match_opposite, .. }
                        | PortSpec::MatchingList { match_opposite, .. } => {
                            *match_opposite = *match_opposite || legacy_mo;
                        }
                    }
                }
                Self::Port { ports }
            }
            TrafficFilterSpecWire::PortMatchingList {
                list_id,
                match_opposite,
            } => Self::Port {
                ports: PortSpec::MatchingList {
                    list_id,
                    match_opposite,
                },
            },
            TrafficFilterSpecWire::IpMatchingList {
                list_id,
                match_opposite,
                ports,
            } => Self::IpMatchingList {
                list_id,
                match_opposite,
                ports,
            },
        }
    }
}

/// Deserialize a [`PortSpec`] from either the new tagged shape
/// (`{"type": "values", "items": [...]}`) or the legacy flat
/// `Vec<String>` array used pre-PortSpec.
fn deserialize_port_spec<'de, D>(deserializer: D) -> Result<PortSpec, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Compat {
        Tagged(PortSpec),
        LegacyArray(Vec<String>),
    }
    Ok(match Compat::deserialize(deserializer)? {
        Compat::Tagged(spec) => spec,
        Compat::LegacyArray(items) => PortSpec::Values {
            items,
            match_opposite: false,
        },
    })
}

fn deserialize_port_spec_opt<'de, D>(deserializer: D) -> Result<Option<PortSpec>, D::Error>
where
    D: serde::Deserializer<'de>,
{
    #[derive(Deserialize)]
    #[serde(untagged)]
    enum Compat {
        Tagged(PortSpec),
        LegacyArray(Vec<String>),
    }
    let opt: Option<Compat> = Option::deserialize(deserializer)?;
    Ok(opt.map(|compat| match compat {
        Compat::Tagged(spec) => spec,
        Compat::LegacyArray(items) => PortSpec::Values {
            items,
            match_opposite: false,
        },
    }))
}

impl CreateFirewallPolicyRequest {
    /// Compatibility no-op retained for callers from the pre-0.10 request shape.
    ///
    /// Policy requests are canonical now; CLI-only shorthand fields are
    /// normalized before constructing this public API type.
    pub fn resolve_filters(&mut self) -> Result<(), String> {
        Ok(())
    }
}

impl UpdateFirewallPolicyRequest {
    /// Same as [`CreateFirewallPolicyRequest::resolve_filters`].
    pub fn resolve_filters(&mut self) -> Result<(), String> {
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateFirewallZoneRequest {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(alias = "networks")]
    pub network_ids: Vec<EntityId>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateFirewallZoneRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", alias = "networks")]
    pub network_ids: Option<Vec<EntityId>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateAclRuleRequest {
    pub name: String,
    #[serde(default = "default_acl_rule_type")]
    pub rule_type: String,
    pub action: FirewallAction,
    #[serde(alias = "source_zone")]
    pub source_zone_id: EntityId,
    #[serde(alias = "dest_zone")]
    pub destination_zone_id: EntityId,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub protocol: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", alias = "src_port")]
    pub source_port: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", alias = "dst_port")]
    pub destination_port: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_filter: Option<TrafficFilterSpec>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destination_filter: Option<TrafficFilterSpec>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enforcing_device_filter: Option<Value>,
    #[serde(default = "default_true")]
    pub enabled: bool,
}

fn default_acl_rule_type() -> String {
    "IP".into()
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateAclRuleRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
    pub rule_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub action: Option<FirewallAction>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", alias = "source_zone")]
    pub source_zone_id: Option<EntityId>,
    #[serde(skip_serializing_if = "Option::is_none", alias = "dest_zone")]
    pub destination_zone_id: Option<EntityId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub protocol: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", alias = "src_port")]
    pub source_port: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", alias = "dst_port")]
    pub destination_port: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_filter: Option<TrafficFilterSpec>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destination_filter: Option<TrafficFilterSpec>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enforcing_device_filter: Option<Value>,
}

// ── NAT Policy ──────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateNatPolicyRequest {
    pub name: String,
    /// masquerade | source | destination
    #[serde(rename = "type", alias = "nat_type")]
    pub nat_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default = "default_true")]
    pub enabled: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interface_id: Option<EntityId>,
    /// tcp | udp | tcp_udp | all
    #[serde(skip_serializing_if = "Option::is_none")]
    pub protocol: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub src_address: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub src_port: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dst_address: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dst_port: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub translated_address: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub translated_port: Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateNatPolicyRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// masquerade | source | destination
    #[serde(
        rename = "type",
        alias = "nat_type",
        skip_serializing_if = "Option::is_none"
    )]
    pub nat_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enabled: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interface_id: Option<EntityId>,
    /// tcp | udp | tcp_udp | all
    #[serde(skip_serializing_if = "Option::is_none")]
    pub protocol: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub src_address: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub src_port: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dst_address: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub dst_port: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub translated_address: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub translated_port: Option<String>,
}

// ── Firewall Group ───────────────────────────────────────────

use crate::model::FirewallGroupType;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateFirewallGroupRequest {
    pub name: String,
    /// Group type. Required from `--from-file`; the CLI flag path always
    /// populates this. Accepts kebab-case (`"port-group"`,
    /// `"address-group"`, `"ipv6-address-group"`) matching the CLI
    /// `--type` flag, and PascalCase variant names for backward
    /// compatibility. Aliased as `type` so JSON files mirroring the
    /// CLI flag (`{"type": "address-group", ...}`) round-trip cleanly.
    #[serde(alias = "type")]
    pub group_type: FirewallGroupType,
    #[serde(alias = "members")]
    pub group_members: Vec<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UpdateFirewallGroupRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", alias = "members")]
    pub group_members: Option<Vec<String>>,
}

#[cfg(test)]
mod tests {
    use super::{
        CreateAclRuleRequest, CreateFirewallGroupRequest, CreateFirewallPolicyRequest, PortSpec,
        TrafficFilterSpec, UpdateAclRuleRequest, UpdateFirewallGroupRequest,
    };
    use crate::model::{FirewallAction, FirewallGroupType};

    /// The existing source_filter / destination_filter path must still work
    /// for users who write the full TrafficFilterSpec in their JSON files.
    #[test]
    fn create_firewall_policy_full_filter_spec_still_works() {
        let req: CreateFirewallPolicyRequest = serde_json::from_value(serde_json::json!({
            "name": "Full filter",
            "action": "Allow",
            "source_zone_id": "aaa",
            "destination_zone_id": "bbb",
            "destination_filter": {
                "type": "ip_address",
                "addresses": ["10.0.40.10"],
                "match_opposite": false
            }
        }))
        .expect("full filter spec should deserialize");

        assert!(req.destination_filter.is_some());
    }

    /// Pre-PortSpec JSON files used a flat `Vec<String>` for `Port.ports`
    /// with `match_opposite` at the variant level. The new schema nests
    /// both inside `PortSpec`, but the deserializer must still accept the
    /// legacy shape so existing payloads keep working.
    #[test]
    fn destination_filter_accepts_legacy_port_variant_shape() {
        let req: CreateFirewallPolicyRequest = serde_json::from_value(serde_json::json!({
            "name": "Block port 80",
            "action": "Block",
            "source_zone_id": "d2864b8e-56fb-4945-b69f-6d424fa5b248",
            "destination_zone_id": "5888bc93-aaae-4242-ae2f-2050d76211fd",
            "destination_filter": {
                "type": "port",
                "ports": ["80"],
                "match_opposite": true
            }
        }))
        .expect("legacy port shape should still deserialize");

        let Some(TrafficFilterSpec::Port {
            ports:
                PortSpec::Values {
                    items,
                    match_opposite,
                },
        }) = &req.destination_filter
        else {
            panic!(
                "expected Port with PortSpec::Values, got {:?}",
                req.destination_filter
            )
        };
        assert_eq!(items, &["80"]);
        // Legacy outer match_opposite is folded into the inner PortSpec.
        assert!(*match_opposite);
    }

    /// Tagged PortSpec::MatchingList round-trips from JSON as a sibling of
    /// addresses (the shape PR 2's group resolver emits and what users will
    /// hand-write for direct group-uuid references).
    #[test]
    fn destination_filter_accepts_ip_address_with_port_matching_list() {
        let mut req: CreateFirewallPolicyRequest = serde_json::from_value(serde_json::json!({
            "name": "Apple Companion Link",
            "action": "Allow",
            "source_zone_id": "d2864b8e-56fb-4945-b69f-6d424fa5b248",
            "destination_zone_id": "5888bc93-aaae-4242-ae2f-2050d76211fd",
            "destination_filter": {
                "type": "ip_address",
                "addresses": ["10.0.10.2", "10.0.10.4"],
                "ports": {
                    "type": "matching_list",
                    "list_id": "24740a56-9cb9-4890-a5ac-589d30914a55"
                }
            }
        }))
        .expect("ip_address + port matching_list should deserialize");

        req.resolve_filters().expect("no shorthand, no-op");

        let Some(TrafficFilterSpec::IpAddress {
            addresses,
            ports: Some(PortSpec::MatchingList { list_id, .. }),
            ..
        }) = &req.destination_filter
        else {
            panic!(
                "expected IpAddress with PortSpec::MatchingList, got {:?}",
                req.destination_filter
            )
        };
        assert_eq!(addresses, &["10.0.10.2", "10.0.10.4"]);
        assert_eq!(list_id, "24740a56-9cb9-4890-a5ac-589d30914a55");
    }

    #[test]
    fn create_acl_rule_request_defaults_rule_type() {
        let request: CreateAclRuleRequest = serde_json::from_value(serde_json::json!({
            "name": "Allow IoT",
            "action": "Allow",
            "source_zone_id": "iot",
            "destination_zone_id": "lan",
            "enabled": true
        }))
        .expect("acl rule request should deserialize");

        assert_eq!(request.rule_type, "IP");
    }

    #[test]
    fn update_acl_rule_request_serializes_type_field() {
        let request = UpdateAclRuleRequest {
            rule_type: Some("DEVICE".into()),
            action: Some(FirewallAction::Allow),
            ..Default::default()
        };

        let value = serde_json::to_value(&request).expect("acl rule request should serialize");
        assert_eq!(
            value.get("type").and_then(serde_json::Value::as_str),
            Some("DEVICE")
        );
        assert_eq!(value.get("rule_type"), None);
    }

    /// Firewall-group `--from-file` JSON should accept `members` (mirroring
    /// the CLI flag name) as well as the wire-level `group_members`.
    /// Otherwise serde silently drops the CLI-style field and a file
    /// written from `--help` output PUTs an unchanged group while
    /// reporting success.
    #[test]
    fn create_firewall_group_request_accepts_members_alias() {
        let req: CreateFirewallGroupRequest = serde_json::from_value(serde_json::json!({
            "name": "HA",
            "type": "port-group",
            "members": ["80", "8000-8002"]
        }))
        .expect("members alias should deserialize");

        assert_eq!(req.name, "HA");
        assert_eq!(req.group_members, vec!["80", "8000-8002"]);
    }

    /// `--from-file` JSON should accept the kebab-case `type` field
    /// (mirroring the CLI `--type` flag) and deserialize each known
    /// group type into its Rust variant. Without this, a file like
    /// `{"type": "address-group", ...}` was silently parsed as a port
    /// group via the previous default, corrupting the wire payload.
    #[test]
    fn create_firewall_group_request_kebab_case_type_alias() {
        let port: CreateFirewallGroupRequest = serde_json::from_value(serde_json::json!({
            "name": "HA",
            "type": "port-group",
            "members": ["80"]
        }))
        .expect("kebab-case port-group should deserialize");
        assert_eq!(port.group_type, FirewallGroupType::PortGroup);

        let addr: CreateFirewallGroupRequest = serde_json::from_value(serde_json::json!({
            "name": "Cloud IOT",
            "type": "address-group",
            "members": ["10.0.0.1"]
        }))
        .expect("kebab-case address-group should deserialize");
        assert_eq!(addr.group_type, FirewallGroupType::AddressGroup);

        let ipv6: CreateFirewallGroupRequest = serde_json::from_value(serde_json::json!({
            "name": "ULA",
            "type": "ipv6-address-group",
            "members": ["fd00::/8"]
        }))
        .expect("kebab-case ipv6-address-group should deserialize");
        assert_eq!(ipv6.group_type, FirewallGroupType::Ipv6AddressGroup);

        // PascalCase still works for backward compatibility with files
        // produced before the alias was added.
        let legacy: CreateFirewallGroupRequest = serde_json::from_value(serde_json::json!({
            "name": "HA",
            "group_type": "AddressGroup",
            "members": ["10.0.0.1"]
        }))
        .expect("PascalCase variant should deserialize");
        assert_eq!(legacy.group_type, FirewallGroupType::AddressGroup);
    }

    /// Missing type should now error rather than silently default to
    /// `port-group` -- a payload like `{"name":"x","members":["10.0.0.1"]}`
    /// was getting silently classified as a port group with addresses
    /// as members, producing an invalid wire payload.
    #[test]
    fn create_firewall_group_request_requires_type() {
        let result: Result<CreateFirewallGroupRequest, _> =
            serde_json::from_value(serde_json::json!({
                "name": "Cloud IOT",
                "members": ["10.0.0.1"]
            }));
        assert!(
            result.is_err(),
            "missing `type` / `group_type` should not silently default to PortGroup"
        );
    }

    #[test]
    fn update_firewall_group_request_accepts_members_alias() {
        let req: UpdateFirewallGroupRequest = serde_json::from_value(serde_json::json!({
            "members": ["80", "443"]
        }))
        .expect("members alias should deserialize");

        assert_eq!(
            req.group_members.as_deref(),
            Some(&["80".into(), "443".into()][..])
        );
    }

    // ── TrafficFilterSpec matching list variants ───────────────────

    /// Port-group references are modeled as `Port { ports: PortSpec::MatchingList }`.
    /// The legacy `port_matching_list` top-level variant is accepted on
    /// deserialize and lowered to the new shape.
    #[test]
    fn port_group_reference_round_trips_via_port_variant() {
        let spec = TrafficFilterSpec::Port {
            ports: PortSpec::MatchingList {
                list_id: "24740a56-9cb9-4890-a5ac-589d30914a55".into(),
                match_opposite: false,
            },
        };
        let json = serde_json::to_value(&spec).expect("should serialize");
        assert_eq!(json.get("type").and_then(|v| v.as_str()), Some("port"));

        // Legacy port_matching_list shape still deserializes (lowered to Port).
        let legacy = serde_json::json!({
            "type": "port_matching_list",
            "list_id": "24740a56-9cb9-4890-a5ac-589d30914a55",
            "match_opposite": false,
        });
        let from_legacy: TrafficFilterSpec =
            serde_json::from_value(legacy).expect("legacy shape should deserialize");
        assert!(matches!(
            from_legacy,
            TrafficFilterSpec::Port {
                ports: PortSpec::MatchingList { .. },
            }
        ));
    }

    #[test]
    fn ip_matching_list_round_trips() {
        let spec = TrafficFilterSpec::IpMatchingList {
            list_id: "b777b27c-410c-4b40-8489-a61bf1a536d4".into(),
            match_opposite: true,
            ports: None,
        };
        let json = serde_json::to_value(&spec).expect("should serialize");
        assert_eq!(
            json.get("type").and_then(|v| v.as_str()),
            Some("ip_matching_list")
        );

        let round_tripped: TrafficFilterSpec =
            serde_json::from_value(json).expect("should deserialize");
        match round_tripped {
            TrafficFilterSpec::IpMatchingList { match_opposite, .. } => assert!(match_opposite),
            other => panic!("expected IpMatchingList, got {other:?}"),
        }
    }
}