axiam-sdk 1.2.2

Official Rust client SDK for AXIAM IAM
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
//! The `network` namespace in a manifest — CONTRACT.md §27.6.2 (contract 1.62).
//!
//! A tenant's network segments, the reply profile each owns and the tenant's
//! `Session-Timeout` cap (CONTRACT.md §36) are *shape*, and so a manifest
//! namespace. Three specs, three natural keys:
//!
//! | Spec | Natural key |
//! |---|---|
//! | [`NetworkSegmentSpec`] | **site + kind + name**, where `kind` is the wire spelling `access` or `quarantine` |
//! | [`NetworkProfileSpec`] | **its segment**: a profile has no name or id of its own |
//! | [`NetworkPolicySpec`]  | **a singleton**: the tenant has exactly one |
//!
//! # Order
//!
//! After everything else a manifest plans: the policy, then the segments, then
//! the profiles, and within the profiles the segments' order. The policy is
//! first because a profile's timeout is checked against the cap at the write.
//!
//! # Judged on the read
//!
//! Every stated member is compared with the value as the read returns it — for
//! a profile, the **effective** one. Two consequences worth knowing:
//!
//! * **A clamped profile.** A profile whose stored timeout is above a lowered
//!   cap reads as the cap, with `session_timeout_clamped: true`. A manifest
//!   that states the cap is `NoChange` (the stored value is neither restored
//!   nor rewritten). A manifest that states a value **above** the cap differs
//!   from the read, so [`plan`](super::Manifest::plan) shows an `Update`, and
//!   [`apply`](super::Manifest::apply) sends the `replace_profile` — which the
//!   server refuses with `403 authorization_denied`, its message naming the
//!   cap. That is the action's failure: reported as given, `apply` stops, and
//!   nothing is retried, adjusted or lowered to the cap by this SDK. Lower the
//!   stated value, or state a higher [`NetworkPolicySpec`] in the same manifest
//!   (the policy is written first).
//!
//!   A read-modify-write of a clamped profile **cannot restore the stored
//!   value**: it can send at most the cap, and what it sends is what is stored
//!   from then on (§36.3 rule 6). An `Update` that does not state the timeout
//!   carries the *read's* — the clamped — value. Raise the cap first, with the
//!   profile left alone, to get the stored value back at read.
//! * **`filter_ids` is a set.** The same names in another order are `NoChange`.
//!   When this SDK does write a segment it sends the names in the order the
//!   manifest states. A list that repeats a name is refused at `plan`, with no
//!   request made.
//!
//! # What this SDK does not do
//!
//! * It never retries a write, and never re-reads and tries again on a `409`:
//!   another administrator wrote, and the administrator decides (§36.9). The
//!   action fails with [`Outcome::Conflict`](super::Outcome::Conflict), which
//!   exposes the server's `reason_code`; run `apply` again, which re-reads.
//! * It does not **prune**. §27.6 rule 4 makes deletion opt-in, per namespace,
//!   and this SDK offers no such opt-in for any namespace, so `plan` never
//!   emits a `Delete` — for a segment, a profile or anything else. Use
//!   `network().delete_segment` / `delete_profile` (each takes the `version`).
//! * The `manifest!` macro and [`ManifestBuilder`](super::ManifestBuilder) do
//!   not declare `network` statements; build it with the constructors below.
//!
//! The namespace is **human-only** (§36.1): an `apply` whose manifest has a
//! `network` section needs a human caller, and a service-account token meets
//! `401` at the first network action.

use std::collections::{BTreeSet, HashSet};

use uuid::Uuid;

use super::plan::{Change, PlannedAction, Resolved, Target};
use super::{Done, Manifest, Step, StepError, action, lookup};
use crate::AxiamError;
use crate::management::models::{
    CreateNetworkReplyProfileRequest, CreateNetworkSegmentRequest, NetworkPolicyResponse,
    NetworkReplyProfile, NetworkReplyProfileInput, NetworkSegmentKind, NetworkSegmentResponse,
    RadiusServiceType, RadiusTerminationAction, ReplaceNetworkPolicyRequest,
    ReplaceNetworkReplyProfileRequest, ReplaceNetworkSegmentRequest,
};

// ---------------------------------------------------------------------------
// Specs
// ---------------------------------------------------------------------------

/// The `network` section of a [`ManagementManifest`](super::ManagementManifest).
///
/// Empty by default, and an empty section costs no request: a manifest without
/// one plans exactly as it did before contract 1.62.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct NetworkSpec {
    /// The tenant's `Session-Timeout` cap, when the manifest states it. At most
    /// one — the type cannot hold two, which is §27.6.2's "a manifest carries at
    /// most one". Never `Create` (the tenant's policy always exists, at
    /// version 0 until first written) and never pruned.
    pub policy: Option<NetworkPolicySpec>,
    /// Segments, in the order they are planned and written.
    pub segments: Vec<NetworkSegmentSpec>,
    /// Reply profiles, one per segment at most.
    pub profiles: Vec<NetworkProfileSpec>,
}

impl NetworkSpec {
    /// Whether the manifest states nothing about the network.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.policy.is_none() && self.segments.is_empty() && self.profiles.is_empty()
    }
}

/// The tenant's cap on a reply profile's `Session-Timeout` — a singleton.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NetworkPolicySpec {
    /// `session_timeout_max_secs`, 300 to 86 400. This SDK does not check the
    /// range: the server's `400` is the answer (§36.3 rule 5).
    pub session_timeout_max_secs: i32,
}

impl NetworkPolicySpec {
    /// A cap of `session_timeout_max_secs` seconds.
    #[must_use]
    pub fn new(session_timeout_max_secs: i32) -> Self {
        Self {
            session_timeout_max_secs,
        }
    }
}

/// A network segment — natural key **site + kind + name**.
///
/// `site`, `kind` and `name` are the key and are never drift: a segment's kind
/// and place in the tree do not change (§36.3 rule 4). Every other member is a
/// field. An unset optional member is silent (§27.6 rule 3), and is carried
/// from the read when a segment is replaced; `Some(None)` on `rank` is a stated
/// "none", which leaves the key out of the body.
#[derive(Debug, Clone, PartialEq)]
pub struct NetworkSegmentSpec {
    /// Manifest-local identifier, referred to by a [`NetworkProfileSpec`].
    pub key: String,
    /// The site key (`site_key` on the wire). A single-site tenant uses `default`.
    pub site: String,
    /// `access` or `quarantine`, **the wire spelling** — the value the API reads
    /// and writes. There is no `zones` spelling here.
    pub kind: NetworkSegmentKind,
    /// The segment's name, unique within its site.
    pub name: String,
    /// The VLAN, 1 to 4094, unique within the site.
    pub vlan_id: i32,
    /// The placement rank of an `access` segment. `None` is silent;
    /// `Some(None)` states "none".
    pub rank: Option<Option<i32>>,
    /// The segment's `Filter-Id` envelope. Compared as a **set**; sent in the
    /// order stated. `None` is silent.
    pub filter_ids: Option<Vec<String>>,
    /// Whether the segment is a placement candidate. `None` is silent.
    pub enabled: Option<bool>,
}

impl NetworkSegmentSpec {
    /// A segment of any `kind`; the optional members are silent.
    pub fn new(
        key: impl Into<String>,
        site: impl Into<String>,
        kind: NetworkSegmentKind,
        name: impl Into<String>,
        vlan_id: i32,
    ) -> Self {
        Self {
            key: key.into(),
            site: site.into(),
            kind,
            name: name.into(),
            vlan_id,
            rank: None,
            filter_ids: None,
            enabled: None,
        }
    }

    /// An `access` segment, which needs a `rank`.
    pub fn access(
        key: impl Into<String>,
        site: impl Into<String>,
        name: impl Into<String>,
        vlan_id: i32,
        rank: i32,
    ) -> Self {
        Self::new(key, site, NetworkSegmentKind::Access, name, vlan_id).with_rank(rank)
    }

    /// A `quarantine` segment, which has no rank.
    pub fn quarantine(
        key: impl Into<String>,
        site: impl Into<String>,
        name: impl Into<String>,
        vlan_id: i32,
    ) -> Self {
        Self::new(key, site, NetworkSegmentKind::Quarantine, name, vlan_id)
    }

    /// State the placement rank.
    #[must_use]
    pub fn with_rank(mut self, rank: i32) -> Self {
        self.rank = Some(Some(rank));
        self
    }

    /// State that the segment has **no** rank (the key is left out of the body).
    #[must_use]
    pub fn with_no_rank(mut self) -> Self {
        self.rank = Some(None);
        self
    }

    /// State the `Filter-Id` envelope.
    #[must_use]
    pub fn with_filter_ids(
        mut self,
        filter_ids: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.filter_ids = Some(filter_ids.into_iter().map(Into::into).collect());
        self
    }

    /// State whether the segment is a placement candidate.
    #[must_use]
    pub fn with_enabled(mut self, enabled: bool) -> Self {
        self.enabled = Some(enabled);
        self
    }
}

/// A segment's reply profile — natural key **its segment**.
///
/// Compared with the *effective* profile the read returns (see the module
/// docs). An unset optional member is silent and carried from the read on an
/// `Update`; `Some(None)` states "none" and leaves the key out of the body.
#[derive(Debug, Clone, PartialEq)]
pub struct NetworkProfileSpec {
    /// The `key` of the [`NetworkSegmentSpec`] this profile belongs to. A key no
    /// segment spec of the manifest declares is refused before any request.
    pub segment: String,
    /// `Session-Timeout`, seconds. A value above the tenant's cap differs from
    /// the read and is refused by the server on `apply` (module docs).
    pub session_timeout_secs: i32,
    /// `Termination-Action`. `None` is silent.
    pub termination_action: Option<RadiusTerminationAction>,
    /// `Idle-Timeout`, seconds. `None` is silent; `Some(None)` states "none".
    pub idle_timeout_secs: Option<Option<i32>>,
    /// `Filter-Id`, one of the segment's `filter_ids`. `None` is silent;
    /// `Some(None)` states "none".
    pub filter_id: Option<Option<String>>,
    /// `Service-Type`. `None` is silent; `Some(None)` states "none".
    pub service_type: Option<Option<RadiusServiceType>>,
}

impl NetworkProfileSpec {
    /// A profile for the segment with key `segment`.
    pub fn new(segment: impl Into<String>, session_timeout_secs: i32) -> Self {
        Self {
            segment: segment.into(),
            session_timeout_secs,
            termination_action: None,
            idle_timeout_secs: None,
            filter_id: None,
            service_type: None,
        }
    }

    /// State `Termination-Action`.
    #[must_use]
    pub fn with_termination_action(mut self, action: RadiusTerminationAction) -> Self {
        self.termination_action = Some(action);
        self
    }

    /// State `Idle-Timeout`.
    #[must_use]
    pub fn with_idle_timeout_secs(mut self, secs: i32) -> Self {
        self.idle_timeout_secs = Some(Some(secs));
        self
    }

    /// State that the profile has **no** `Idle-Timeout`.
    #[must_use]
    pub fn with_no_idle_timeout(mut self) -> Self {
        self.idle_timeout_secs = Some(None);
        self
    }

    /// State `Filter-Id`.
    #[must_use]
    pub fn with_filter_id(mut self, filter_id: impl Into<String>) -> Self {
        self.filter_id = Some(Some(filter_id.into()));
        self
    }

    /// State that the profile has **no** `Filter-Id`.
    #[must_use]
    pub fn with_no_filter_id(mut self) -> Self {
        self.filter_id = Some(None);
        self
    }

    /// State `Service-Type`.
    #[must_use]
    pub fn with_service_type(mut self, service_type: RadiusServiceType) -> Self {
        self.service_type = Some(Some(service_type));
        self
    }

    /// State that the profile has **no** `Service-Type`.
    #[must_use]
    pub fn with_no_service_type(mut self) -> Self {
        self.service_type = Some(None);
        self
    }
}

// ---------------------------------------------------------------------------
// Validation (before any request)
// ---------------------------------------------------------------------------

/// The refusal of §27.6.2 item 4: the read holds an open-enum `value` this SDK
/// cannot name in `member`, the manifest does not state it, and the profile
/// would be replaced. State the member to resolve it.
fn unknown_open_enum(segment: &str, member: &str, value: &str) -> AxiamError {
    // `e.validation()` is `Some` and `fields[0].field` is the member; the
    // value is kept in the text (D-15: this SDK's `Unknown` holds it).
    crate::management::error::local_refusal(
        "manifest.plan",
        member,
        format!(
            "network profile of segment {segment:?}: {member} is {value:?} on the server, a \
             value this SDK does not know and never re-sends; state {member} in the manifest to \
             replace it (CONTRACT.md §27.6.2)"
        ),
    )
}

/// The wire spelling of a kind, for natural-key comparison and summaries.
fn kind_wire(kind: &NetworkSegmentKind) -> &str {
    match kind {
        NetworkSegmentKind::Access => "access",
        NetworkSegmentKind::Quarantine => "quarantine",
        NetworkSegmentKind::Unknown(other) => other,
    }
}

/// §27.6.2 item 1: the refusals that need no request.
///
/// A natural key named twice, a profile for a segment the manifest does not
/// declare, two profiles for one segment, a segment that lists one Filter-Id
/// twice, a segment key declared twice. Each would otherwise surface halfway
/// through an `apply`, or never — the server cannot see a manifest.
pub(crate) fn validate(spec: &NetworkSpec, problems: &mut Vec<String>) {
    let mut keys: HashSet<&str> = HashSet::new();
    let mut natural: HashSet<(&str, &str, &str)> = HashSet::new();
    for segment in &spec.segments {
        if !keys.insert(segment.key.as_str()) {
            problems.push(format!(
                "network segment key {:?} is declared more than once",
                segment.key
            ));
        }
        if !natural.insert((
            segment.site.as_str(),
            kind_wire(&segment.kind),
            segment.name.as_str(),
        )) {
            problems.push(format!(
                "network segment {:?} (site {:?}, kind {:?}) is declared more than once; one \
                 natural key is one server row",
                segment.name,
                segment.site,
                kind_wire(&segment.kind)
            ));
        }
        if let Some(filter_ids) = &segment.filter_ids {
            let mut seen: HashSet<&str> = HashSet::new();
            for name in filter_ids {
                if !seen.insert(name.as_str()) {
                    problems.push(format!(
                        "network segment {:?} lists Filter-Id {name:?} more than once; \
                         filter_ids is a set",
                        segment.key
                    ));
                }
            }
        }
    }

    let mut profiled: HashSet<&str> = HashSet::new();
    for profile in &spec.profiles {
        if !keys.contains(profile.segment.as_str()) {
            problems.push(format!(
                "a network profile names segment {:?}, which no segment of the manifest declares",
                profile.segment
            ));
        }
        if !profiled.insert(profile.segment.as_str()) {
            problems.push(format!(
                "network segment {:?} has more than one profile; a segment has at most one",
                profile.segment
            ));
        }
    }
}

// ---------------------------------------------------------------------------
// What `plan` reads
// ---------------------------------------------------------------------------

/// The network state a plan is computed against.
#[derive(Debug, Default)]
pub(crate) struct NetworkSnapshot {
    pub(crate) policy: Option<NetworkPolicyResponse>,
    pub(crate) segments: Vec<NetworkSegmentResponse>,
    pub(crate) profiles: Vec<NetworkReplyProfile>,
}

impl<'c> Manifest<'c> {
    /// `get_policy`, `list_segments` and `list_profiles`, each only when the
    /// manifest has something to compare against it, each walked to exhaustion.
    pub(super) async fn read_network(
        &self,
        spec: &NetworkSpec,
    ) -> Result<NetworkSnapshot, AxiamError> {
        let network = self.client.network();
        let start = || crate::management::page::PageRequest::first(super::PLAN_PAGE);
        let policy = if spec.policy.is_some() {
            Some(network.get_policy().await?)
        } else {
            None
        };
        // A profile is matched to its segment, so profiles need the segments
        // too; segments alone need no profile read.
        let segments = if spec.segments.is_empty() && spec.profiles.is_empty() {
            Vec::new()
        } else {
            network.list_segments_all(None, start()).await?
        };
        let profiles = if spec.profiles.is_empty() {
            Vec::new()
        } else {
            network.list_profiles_all(start()).await?
        };
        Ok(NetworkSnapshot {
            policy,
            segments,
            profiles,
        })
    }
}

// ---------------------------------------------------------------------------
// Plan
// ---------------------------------------------------------------------------

/// One executable network step.
#[derive(Debug, Clone)]
pub(super) enum NetStep {
    /// `replace_policy`, carrying the policy's `version` as read.
    ReplacePolicy { body: ReplaceNetworkPolicyRequest },
    /// `create_segment`.
    CreateSegment {
        key: String,
        body: CreateNetworkSegmentRequest,
    },
    /// `replace_segment`: the full body, `version` as read.
    ReplaceSegment {
        key: String,
        id: Uuid,
        body: ReplaceNetworkSegmentRequest,
    },
    /// `create_profile`: the segment's id and version are taken at execution,
    /// from the read or from the segment write that preceded it.
    CreateProfile {
        segment: String,
        profile: NetworkReplyProfileInput,
    },
    /// `replace_profile`: `version` as read; the `segment_version` is taken at
    /// execution.
    ReplaceProfile {
        segment: String,
        version: i64,
        profile: NetworkReplyProfileInput,
    },
}

fn as_set(names: &[String]) -> BTreeSet<&str> {
    names.iter().map(String::as_str).collect()
}

fn change(drifted: bool) -> Change {
    if drifted {
        Change::Update
    } else {
        Change::NoChange
    }
}

/// Plan the `network` namespace and append its actions: the policy, then the
/// segments, then the profiles (§27.6.2 item 2).
pub(super) fn plan(
    spec: &NetworkSpec,
    snapshot: &NetworkSnapshot,
    resolved: &mut Resolved,
    steps: &mut Vec<(PlannedAction, Step)>,
) -> Result<(), AxiamError> {
    // The policy always exists, so it is `NoChange` or `Update`, never `Create`.
    if let Some(stated) = &spec.policy {
        let read = snapshot.policy.as_ref().ok_or_else(|| {
            AxiamError::network("internal: the network policy was not read although it is stated")
        })?;
        let drifted = read.session_timeout_max_secs != stated.session_timeout_max_secs;
        steps.push((
            action(
                change(drifted),
                Target::NetworkPolicy,
                "policy",
                format!(
                    "network policy: session_timeout_max_secs {}",
                    stated.session_timeout_max_secs
                ),
            ),
            if drifted {
                Step::Network(NetStep::ReplacePolicy {
                    body: ReplaceNetworkPolicyRequest {
                        session_timeout_max_secs: stated.session_timeout_max_secs,
                        version: read.version,
                    },
                })
            } else {
                Step::Noop
            },
        ));
    }

    for segment in &spec.segments {
        let summary = format!(
            "network segment {:?} ({} on site {:?})",
            segment.name,
            kind_wire(&segment.kind),
            segment.site
        );
        let found = snapshot.segments.iter().find(|r| {
            r.site_key == segment.site && r.kind == segment.kind && r.name == segment.name
        });
        match found {
            Some(read) => {
                resolved
                    .network_segments
                    .insert(segment.key.clone(), read.id);
                resolved
                    .network_segment_versions
                    .insert(segment.key.clone(), read.version);
                // Judged on the read: vlan, then each stated optional member.
                let drifted = read.vlan_id != segment.vlan_id
                    || segment
                        .rank
                        .as_ref()
                        .is_some_and(|stated| *stated != read.rank)
                    || segment
                        .filter_ids
                        .as_ref()
                        .is_some_and(|stated| as_set(stated) != as_set(&read.filter_ids))
                    || segment.enabled.is_some_and(|stated| stated != read.enabled);
                steps.push((
                    action(
                        change(drifted),
                        Target::NetworkSegment,
                        &segment.key,
                        summary,
                    ),
                    if drifted {
                        Step::Network(NetStep::ReplaceSegment {
                            key: segment.key.clone(),
                            id: read.id,
                            // Every member the manifest states replaces the
                            // read's; every one it does not is carried from
                            // it; a stated "none" is left out. `kind`,
                            // `site_key` and `name` are not in the body.
                            body: ReplaceNetworkSegmentRequest {
                                version: read.version,
                                vlan_id: segment.vlan_id,
                                filter_ids: segment
                                    .filter_ids
                                    .clone()
                                    .unwrap_or_else(|| read.filter_ids.clone()),
                                enabled: segment.enabled.unwrap_or(read.enabled),
                                rank: match segment.rank {
                                    Some(stated) => stated,
                                    None => read.rank,
                                },
                            },
                        })
                    } else {
                        Step::Noop
                    },
                ));
            }
            None => steps.push((
                action(
                    Change::Create,
                    Target::NetworkSegment,
                    &segment.key,
                    summary,
                ),
                Step::Network(NetStep::CreateSegment {
                    key: segment.key.clone(),
                    body: CreateNetworkSegmentRequest {
                        kind: segment.kind.clone(),
                        site_key: segment.site.clone(),
                        name: segment.name.clone(),
                        vlan_id: segment.vlan_id,
                        // Sent in the order the manifest states.
                        filter_ids: segment.filter_ids.clone(),
                        rank: segment.rank.flatten(),
                        enabled: segment.enabled,
                    },
                }),
            )),
        }
    }

    // Profiles follow their segments, in the segments' order, so `plan` is stable.
    for segment in &spec.segments {
        let Some(stated) = spec.profiles.iter().find(|p| p.segment == segment.key) else {
            continue;
        };
        let summary = format!(
            "network profile of segment {:?} (session_timeout_secs {})",
            segment.name, stated.session_timeout_secs
        );
        let read = resolved
            .network_segments
            .get(&segment.key)
            .and_then(|id| snapshot.profiles.iter().find(|p| p.segment_id == *id));
        match read {
            Some(read) => {
                let drifted = read.session_timeout_secs != stated.session_timeout_secs
                    || stated
                        .termination_action
                        .as_ref()
                        .is_some_and(|s| *s != read.termination_action)
                    || stated
                        .idle_timeout_secs
                        .is_some_and(|s| s != read.idle_timeout_secs)
                    || stated
                        .filter_id
                        .as_ref()
                        .is_some_and(|s| *s != read.filter_id)
                    || stated
                        .service_type
                        .as_ref()
                        .is_some_and(|s| *s != read.service_type);
                // §27.6.2 item 4 (maintainer, 2026-10-16): an `Update` carries
                // an unstated member from the read, and an open-enum value this
                // SDK has no name for is never re-sent. Refuse at `plan`, with
                // no request, naming the member and the value.
                if drifted {
                    if stated.termination_action.is_none()
                        && let RadiusTerminationAction::Unknown(value) = &read.termination_action
                    {
                        return Err(unknown_open_enum(&segment.key, "termination_action", value));
                    }
                    if stated.service_type.is_none()
                        && let Some(RadiusServiceType::Unknown(value)) = &read.service_type
                    {
                        return Err(unknown_open_enum(&segment.key, "service_type", value));
                    }
                }
                steps.push((
                    action(
                        change(drifted),
                        Target::NetworkProfile,
                        &segment.key,
                        summary,
                    ),
                    if drifted {
                        Step::Network(NetStep::ReplaceProfile {
                            segment: segment.key.clone(),
                            version: read.version,
                            profile: NetworkReplyProfileInput {
                                // Carried from the read: the dictionary the
                                // profile was validated against.
                                dictionary: Some(read.dictionary.clone()),
                                session_timeout_secs: stated.session_timeout_secs,
                                termination_action: Some(
                                    stated
                                        .termination_action
                                        .clone()
                                        .unwrap_or_else(|| read.termination_action.clone()),
                                ),
                                idle_timeout_secs: stated
                                    .idle_timeout_secs
                                    .unwrap_or(read.idle_timeout_secs),
                                filter_id: stated
                                    .filter_id
                                    .clone()
                                    .unwrap_or_else(|| read.filter_id.clone()),
                                service_type: stated
                                    .service_type
                                    .clone()
                                    .unwrap_or_else(|| read.service_type.clone()),
                            },
                        })
                    } else {
                        Step::Noop
                    },
                ));
            }
            None => steps.push((
                action(
                    Change::Create,
                    Target::NetworkProfile,
                    &segment.key,
                    summary,
                ),
                Step::Network(NetStep::CreateProfile {
                    segment: segment.key.clone(),
                    profile: NetworkReplyProfileInput {
                        dictionary: None,
                        session_timeout_secs: stated.session_timeout_secs,
                        termination_action: stated.termination_action.clone(),
                        idle_timeout_secs: stated.idle_timeout_secs.flatten(),
                        filter_id: stated.filter_id.clone().flatten(),
                        service_type: stated.service_type.clone().flatten(),
                    },
                }),
            )),
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Apply
// ---------------------------------------------------------------------------

impl<'c> Manifest<'c> {
    /// Run one network step. Every write is issued **once** and never retried;
    /// a refusal — `409` and its `reason_code`, or the write gate's `403` — is
    /// this action's failure, and the caller stops (§27.6 rule 7).
    pub(super) async fn run_network(
        &self,
        step: NetStep,
        resolved: &mut Resolved,
    ) -> Result<Done, StepError> {
        let network = self.client.network();
        match step {
            NetStep::ReplacePolicy { body } => {
                network.replace_policy(&body).await?;
            }
            NetStep::CreateSegment { key, body } => {
                let created = network.create_segment(&body).await?;
                resolved.network_segments.insert(key.clone(), created.id);
                // The version of **this write's response**: a profile that
                // follows is checked against it (§27.6.2 item 4).
                resolved
                    .network_segment_versions
                    .insert(key, created.version);
            }
            NetStep::ReplaceSegment { key, id, body } => {
                let replaced = network.replace_segment(id, &body).await?;
                resolved
                    .network_segment_versions
                    .insert(key, replaced.version);
            }
            NetStep::CreateProfile { segment, profile } => {
                let segment_id = lookup(&resolved.network_segments, &segment, "network segment")?;
                let segment_version = segment_version(resolved, &segment)?;
                network
                    .create_profile(&CreateNetworkReplyProfileRequest {
                        segment_id,
                        segment_version,
                        profile,
                    })
                    .await?;
            }
            NetStep::ReplaceProfile {
                segment,
                version,
                profile,
            } => {
                let segment_id = lookup(&resolved.network_segments, &segment, "network segment")?;
                let segment_version = segment_version(resolved, &segment)?;
                network
                    .replace_profile(
                        segment_id,
                        &ReplaceNetworkReplyProfileRequest {
                            profile,
                            segment_version,
                            version,
                        },
                    )
                    .await?;
            }
        }
        Ok(Done::Plain)
    }
}

/// The segment's `version` as last known: the read's, or the response of the
/// write this `apply` made to it.
fn segment_version(resolved: &Resolved, key: &str) -> Result<i64, AxiamError> {
    resolved
        .network_segment_versions
        .get(key)
        .copied()
        .ok_or_else(|| {
            AxiamError::network(format!(
                "internal: network segment key {key:?} has no version: it was consumed before \
                 the step that creates it ran"
            ))
        })
}