aegis-api 0.2.3

Independent Aegis fleet control plane HTTP service.
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
use aegis_dto::{
    AegisHostMode, HostAlias, HostAliases, HostId,
    v1::{
        AegisAgentStatus, AegisDirectGatewayReport, AegisEnrollmentPhase, AegisEnrollmentSsh,
        AegisHostMessage, AegisNetworkConfig, AegisObservedPublicIps, AegisPrincipalGrant,
        AegisWireGuardAddressPool,
    },
};
use std::net::IpAddr;
use thiserror::Error;

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AegisHostRecordSsh {
    pub port: Option<u16>,
    pub public_key: Option<String>,
    pub external_principals: Vec<String>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AegisHostRecord {
    pub host_id: HostId,
    pub aliases: HostAliases,
    pub ssh: Option<AegisHostRecordSsh>,
    pub egress_public_key: Option<String>,
    pub messages: Vec<AegisHostMessage>,
    pub agent: Option<AegisAgentStatus>,
    pub principal_grants: Vec<AegisPrincipalGrant>,
    pub ssh_lockdown_enabled: Option<bool>,
    pub direct_gateway_report: Option<AegisDirectGatewayReport>,
    pub observed_public_ips: AegisObservedPublicIps,
    pub transient: bool,
    pub pending: bool,
    pub created_unix: i64,
    pub updated_unix: i64,
    pub updated_by_principal: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AegisEnrollmentRecord {
    pub host_id: HostId,
    pub aliases: HostAliases,
    pub network: String,
    pub mode: AegisHostMode,
    pub ssh: Option<AegisEnrollmentSsh>,
    pub transient: bool,
    pub initial_oauth_principal: String,
    pub phase: AegisEnrollmentPhase,
    pub credential_session_id: Option<String>,
    pub created_unix: i64,
    pub expires_unix: i64,
    pub updated_unix: i64,
    pub created_by_principal: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AegisEnrollmentPrepared {
    pub enrollment: AegisEnrollmentRecord,
    pub host: AegisHostRecord,
    pub member: AegisNetworkMemberRecord,
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct AegisEnrollmentPreparation<'a> {
    pub host_public_key: Option<&'a str>,
    pub wireguard_public_key: &'a str,
    pub wireguard_endpoints: &'a [String],
    pub network: &'a AegisNetworkConfig,
    pub updated_unix: i64,
}

pub(crate) fn enrollment_phase_rank(phase: AegisEnrollmentPhase) -> u8 {
    match phase {
        AegisEnrollmentPhase::AwaitingMachine => 0,
        AegisEnrollmentPhase::PreparingMachine => 1,
        AegisEnrollmentPhase::Prepared => 2,
        AegisEnrollmentPhase::InstallingAgent => 3,
        AegisEnrollmentPhase::Activating => 4,
    }
}

pub(crate) fn validate_current_enrollment(
    enrollment: &AegisEnrollmentRecord,
    credential_session_id: &str,
    now_unix: i64,
) -> Result<(), AegisEnrollmentWriteError> {
    if now_unix >= enrollment.expires_unix {
        return Err(AegisEnrollmentWriteError::Expired {
            host_id: enrollment.host_id,
            expires_unix: enrollment.expires_unix,
        });
    }
    match enrollment.credential_session_id.as_deref() {
        None => Err(AegisEnrollmentWriteError::CredentialMissing {
            host_id: enrollment.host_id,
        }),
        Some(current) if current != credential_session_id => {
            Err(AegisEnrollmentWriteError::CredentialMismatch {
                host_id: enrollment.host_id,
            })
        }
        Some(_) => Ok(()),
    }
}

pub(crate) fn prepared_host_matches_enrollment(
    enrollment: &AegisEnrollmentRecord,
    host: &AegisHostRecord,
    member: &AegisNetworkMemberRecord,
) -> bool {
    host.host_id == enrollment.host_id
        && host.aliases == enrollment.aliases
        && host.transient == enrollment.transient
        && member.host_id == enrollment.host_id
        && member.mode == enrollment.mode
        && match (&enrollment.ssh, &host.ssh) {
            (None, None) => true,
            (Some(expected), Some(actual)) => {
                actual.public_key.is_some()
                    && expected.port == actual.port
                    && expected.external_principals == actual.external_principals
            }
            _ => false,
        }
}

pub(crate) fn validate_enrollment_host_public_key(
    enrollment: &AegisEnrollmentRecord,
    host_public_key: Option<&str>,
) -> Result<(), AegisEnrollmentWriteError> {
    match (enrollment.ssh.is_some(), host_public_key.is_some()) {
        (true, false) => Err(AegisEnrollmentWriteError::SshHostPublicKeyRequired {
            host_id: enrollment.host_id,
        }),
        (false, true) => Err(AegisEnrollmentWriteError::SshHostPublicKeyUnexpected {
            host_id: enrollment.host_id,
        }),
        _ => Ok(()),
    }
}

#[derive(Clone, Debug)]
pub(crate) struct AegisHostReportUpdate {
    pub messages: Vec<AegisHostMessage>,
    pub agent: AegisAgentStatus,
    pub principal_grants: Vec<AegisPrincipalGrant>,
    pub ssh_lockdown_enabled: bool,
    pub direct_gateway_report: AegisDirectGatewayReport,
    pub observed_public_ip: Option<(IpAddr, i64)>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AegisUserIdentity {
    pub user_id: String,
    pub disabled: bool,
    pub admin: bool,
}

pub(crate) fn merge_direct_gateway_handshakes(
    previous: Option<&AegisDirectGatewayReport>,
    mut current: AegisDirectGatewayReport,
) -> AegisDirectGatewayReport {
    let previous_handshakes = previous
        .into_iter()
        .flat_map(|report| &report.peers)
        .filter_map(|peer| {
            peer.latest_handshake_unix
                .map(|handshake| (peer.public_key.as_str(), handshake))
        })
        .collect::<std::collections::BTreeMap<_, _>>();
    for peer in &mut current.peers {
        peer.latest_handshake_unix = peer
            .latest_handshake_unix
            .max(previous_handshakes.get(peer.public_key.as_str()).copied());
    }
    current
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AegisNetworkMemberRecord {
    pub host_id: HostId,
    pub mode: AegisHostMode,
    pub wireguard_public_key: Option<String>,
    pub wireguard_ipv4: Option<String>,
    pub wireguard_ipv6: Option<String>,
    pub wireguard_endpoints: Vec<String>,
    pub internal_ipv4: Option<String>,
    pub internal_ipv6: Option<String>,
    pub pending: bool,
    pub created_unix: i64,
    pub updated_unix: i64,
    pub updated_by_principal: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AegisDirectWireGuardRecord {
    pub public_key: String,
    pub ipv4: String,
    pub ipv6: String,
    pub endpoints: Vec<String>,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AegisDirectGatewayRecord {
    pub host_id: HostId,
    pub wireguard: AegisDirectWireGuardRecord,
    pub created_unix: i64,
    pub updated_unix: i64,
    pub updated_by_principal: String,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AegisSatelliteRecord {
    pub slug: String,
    pub credential_id: String,
    pub owner_principal: String,
    pub wireguard: AegisDirectWireGuardRecord,
    pub ssh_public_key: String,
    pub created_unix: i64,
    pub created_by_principal: String,
    pub broker_uses: std::collections::BTreeMap<HostId, AegisSatelliteBrokerUseRecord>,
}

#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct AegisSatelliteBrokerUseRecord {
    pub used_unix: i64,
    pub gateway_host_id: HostId,
    pub target_host_id: HostId,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct AegisDirectLeaseRecord {
    pub id: String,
    pub wireguard: AegisDirectWireGuardRecord,
}

#[derive(Debug, Error)]
pub(crate) enum AegisDirectWriteError {
    #[error("direct resource `{resource}` already exists")]
    AlreadyExists { resource: String },
    #[error("satellite name `{alias}` is already an alias of host `{host_id}`")]
    HostAliasExists { alias: HostAlias, host_id: HostId },
    #[error("WireGuard public key is already assigned to direct resource `{resource}`")]
    DuplicatePublicKey { resource: String },
    #[error("aegis direct-resource write conflicted with another concurrent write")]
    ConcurrentWrite,
    #[error("no direct addresses remain available in `{subnet_ipv4}` / `{subnet_ipv6}`")]
    NoAvailableAddress {
        subnet_ipv4: String,
        subnet_ipv6: String,
    },
    #[error(transparent)]
    Internal(#[from] anyhow::Error),
}

#[derive(Debug, Error)]
pub(crate) enum AegisHostWriteError {
    #[error("host `{host_id}` does not exist")]
    NotFound { host_id: HostId },
    #[error("host `{host_id}` is controlled by an outstanding enrollment")]
    EnrollmentPending { host_id: HostId },
    #[error("aegis host write conflicted with another concurrent write")]
    ConcurrentWrite,
    #[error("host aliases must be changed through the add, promote, and remove alias operations")]
    AliasesChanged,
    #[error("{0}")]
    InvalidWireguardIdentity(String),
    #[error("wireguard_ipv4 `{wireguard_ipv4}` is already assigned to host `{host_id}`")]
    DuplicateWireguardIpv4 {
        host_id: HostId,
        wireguard_ipv4: String,
    },
    #[error("wireguard_ipv6 `{wireguard_ipv6}` is already assigned to host `{host_id}`")]
    DuplicateWireguardIpv6 {
        host_id: HostId,
        wireguard_ipv6: String,
    },
    #[error("egress public key is already assigned to host `{host_id}`")]
    DuplicateEgressPublicKey { host_id: HostId },
    #[error("internal_ipv4 `{internal_ipv4}` is already assigned to host `{host_id}`")]
    DuplicateInternalIpv4 {
        host_id: HostId,
        internal_ipv4: String,
    },
    #[error("internal_ipv6 `{internal_ipv6}` is already assigned to host `{host_id}`")]
    DuplicateInternalIpv6 {
        host_id: HostId,
        internal_ipv6: String,
    },
    #[error("no internal IP pairs remain available in `{subnet_ipv4}` / `{subnet_ipv6}`")]
    NoAvailableInternalIp {
        subnet_ipv4: String,
        subnet_ipv6: String,
    },
    #[error("no WireGuard host ids remain available in `{subnet_ipv4}` / `{subnet_ipv6}`")]
    NoAvailableWireguardHostId {
        subnet_ipv4: String,
        subnet_ipv6: String,
    },
    #[error(transparent)]
    Internal(#[from] anyhow::Error),
}

#[derive(Debug, Error)]
pub(crate) enum AegisEgressWriteError {
    #[error("egress policy `{source_host_id}` does not exist")]
    NotFound { source_host_id: HostId },
    #[error("egress policy `{source_host_id}` changed concurrently")]
    ConcurrentWrite { source_host_id: HostId },
    #[error(transparent)]
    Internal(#[from] anyhow::Error),
}

#[derive(Clone, Debug)]
pub(crate) struct AegisEgressSnapshot {
    pub generation: u64,
    pub policies: Vec<aegis_dto::v1::AegisEgressPolicy>,
}

#[derive(Debug, Error)]
pub(crate) enum AegisHostDeleteError {
    #[error(
        "host `{host_id}` is controlled by an outstanding enrollment; cancel the enrollment instead"
    )]
    EnrollmentPending { host_id: HostId },
    #[error("host `{host_id}` is still selected as egress by: {source_host_ids:?}")]
    EgressTargetInUse {
        host_id: HostId,
        source_host_ids: Vec<HostId>,
    },
    #[error("host deletion changed concurrently")]
    ConcurrentWrite,
    #[error(transparent)]
    Internal(#[from] anyhow::Error),
}

#[derive(Debug, Error)]
pub(crate) enum AegisAliasWriteError {
    #[error("host `{host_id}` does not exist")]
    HostNotFound { host_id: HostId },
    #[error("host `{host_id}` aliases are controlled by an outstanding enrollment")]
    EnrollmentPending { host_id: HostId },
    #[error("host alias `{alias}` is already assigned to host `{host_id}`")]
    AlreadyAssigned { alias: HostAlias, host_id: HostId },
    #[error("host alias `{alias}` is already assigned to a satellite")]
    AssignedToSatellite { alias: HostAlias },
    #[error("host `{host_id}` does not have alias `{alias}`")]
    AliasNotFound { host_id: HostId, alias: HostAlias },
    #[error("{0}")]
    InvalidAliases(#[from] aegis_dto::InvalidHostAliases),
    #[error("host alias update changed concurrently")]
    ConcurrentWrite,
    #[error(transparent)]
    Internal(#[from] anyhow::Error),
}

#[derive(Debug, Error)]
pub(crate) enum AegisEnrollmentWriteError {
    #[error("enrollment for host `{host_id}` already exists")]
    AlreadyExists { host_id: HostId },
    #[error("enrollment for host `{host_id}` does not exist")]
    NotFound { host_id: HostId },
    #[error("host `{host_id}` is already enrolled")]
    HostAlreadyExists { host_id: HostId },
    #[error("enrollment for host `{host_id}` expired at {expires_unix}")]
    Expired { host_id: HostId, expires_unix: i64 },
    #[error("enrollment for host `{host_id}` has no issued credential")]
    CredentialMissing { host_id: HostId },
    #[error("the enrollment credential for host `{host_id}` is not the current credential")]
    CredentialMismatch { host_id: HostId },
    #[error("host alias `{alias}` is already assigned to host `{host_id}`")]
    AliasAlreadyAssigned { alias: HostAlias, host_id: HostId },
    #[error("host alias `{alias}` is already assigned to a satellite")]
    AliasAssignedToSatellite { alias: HostAlias },
    #[error("enrollment for host `{host_id}` has not prepared its machine identity")]
    NotPrepared { host_id: HostId },
    #[error("enrollment for host `{host_id}` requires an SSH host public key")]
    SshHostPublicKeyRequired { host_id: HostId },
    #[error("enrollment for host `{host_id}` does not permit an SSH host public key")]
    SshHostPublicKeyUnexpected { host_id: HostId },
    #[error("prepared host `{host_id}` is inconsistent with its enrollment")]
    InconsistentPreparedHost { host_id: HostId },
    #[error("aegis enrollment changed concurrently")]
    ConcurrentWrite,
    #[error(transparent)]
    Host(#[from] AegisHostWriteError),
    #[error(transparent)]
    Internal(#[from] anyhow::Error),
}

#[async_trait::async_trait]
pub(crate) trait AegisStore {
    async fn fetch_aegis_user_by_id(
        &self,
        user_id: &str,
    ) -> anyhow::Result<Option<AegisUserIdentity>>;

    async fn list_aegis_enrollments(&self) -> anyhow::Result<Vec<AegisEnrollmentRecord>>;
    async fn fetch_aegis_enrollment(
        &self,
        host_id: &HostId,
    ) -> anyhow::Result<Option<AegisEnrollmentRecord>>;
    async fn create_aegis_enrollment(
        &self,
        enrollment: &AegisEnrollmentRecord,
    ) -> Result<AegisEnrollmentRecord, AegisEnrollmentWriteError>;
    async fn replace_aegis_enrollment_credential(
        &self,
        host_id: &HostId,
        expected_session_id: Option<&str>,
        next_session_id: &str,
        updated_unix: i64,
    ) -> Result<AegisEnrollmentRecord, AegisEnrollmentWriteError>;
    async fn update_aegis_enrollment_phase(
        &self,
        host_id: &HostId,
        credential_session_id: &str,
        phase: AegisEnrollmentPhase,
        updated_unix: i64,
    ) -> Result<AegisEnrollmentRecord, AegisEnrollmentWriteError>;
    async fn prepare_aegis_enrollment(
        &self,
        host_id: &HostId,
        credential_session_id: &str,
        preparation: AegisEnrollmentPreparation<'_>,
    ) -> Result<AegisEnrollmentPrepared, AegisEnrollmentWriteError>;
    async fn activate_aegis_enrollment(
        &self,
        host_id: &HostId,
        credential_session_id: &str,
        updated_unix: i64,
    ) -> Result<AegisEnrollmentPrepared, AegisEnrollmentWriteError>;
    async fn cancel_aegis_enrollment(
        &self,
        host_id: &HostId,
    ) -> Result<Option<AegisEnrollmentRecord>, AegisEnrollmentWriteError>;

    async fn read_aegis_egress_snapshot(&self) -> anyhow::Result<AegisEgressSnapshot>;

    async fn fetch_aegis_egress_policy(
        &self,
        source_host_id: &HostId,
    ) -> anyhow::Result<Option<aegis_dto::v1::AegisEgressPolicy>>;

    async fn compare_and_set_aegis_egress_policy(
        &self,
        source_host_id: &HostId,
        expected_generation: u64,
        expected_revision: Option<u64>,
        replacement: Option<&aegis_dto::v1::AegisEgressPolicy>,
    ) -> Result<(), AegisEgressWriteError>;

    async fn list_aegis_direct_gateways(&self) -> anyhow::Result<Vec<AegisDirectGatewayRecord>>;
    async fn fetch_aegis_direct_gateway(
        &self,
        host_id: &HostId,
    ) -> anyhow::Result<Option<AegisDirectGatewayRecord>>;
    async fn put_aegis_direct_gateway(
        &self,
        gateway: &AegisDirectGatewayRecord,
    ) -> Result<AegisDirectGatewayRecord, AegisDirectWriteError>;
    async fn delete_aegis_direct_gateway(&self, host_id: &HostId) -> anyhow::Result<bool>;
    async fn list_aegis_satellites(&self) -> anyhow::Result<Vec<AegisSatelliteRecord>>;
    async fn create_aegis_satellite(
        &self,
        satellite: &AegisSatelliteRecord,
        pool: &AegisWireGuardAddressPool,
    ) -> Result<AegisSatelliteRecord, AegisDirectWriteError>;
    async fn fetch_aegis_satellite(
        &self,
        slug: &str,
    ) -> anyhow::Result<Option<AegisSatelliteRecord>>;
    async fn record_aegis_satellite_broker_use(
        &self,
        slug: &str,
        activity: &AegisSatelliteBrokerUseRecord,
    ) -> anyhow::Result<bool>;
    async fn delete_aegis_satellite(&self, slug: &str) -> anyhow::Result<bool>;
    async fn list_aegis_hosts(&self) -> anyhow::Result<Vec<AegisHostRecord>>;
    async fn fetch_aegis_host(&self, host_id: &HostId) -> anyhow::Result<Option<AegisHostRecord>>;
    async fn fetch_host_id_by_alias(&self, alias: &HostAlias) -> anyhow::Result<Option<HostId>>;
    async fn resolve_enrolled_host_alias(
        &self,
        alias: &HostAlias,
    ) -> anyhow::Result<Option<HostId>>;
    async fn add_host_alias(
        &self,
        host_id: &HostId,
        alias: &HostAlias,
        updated_by_principal: &str,
        updated_unix: i64,
    ) -> Result<AegisHostRecord, AegisAliasWriteError>;
    async fn promote_host_alias(
        &self,
        host_id: &HostId,
        alias: &HostAlias,
        updated_by_principal: &str,
        updated_unix: i64,
    ) -> Result<AegisHostRecord, AegisAliasWriteError>;
    async fn remove_host_alias(
        &self,
        host_id: &HostId,
        alias: &HostAlias,
        updated_by_principal: &str,
        updated_unix: i64,
    ) -> Result<AegisHostRecord, AegisAliasWriteError>;
    async fn list_aegis_network_members(
        &self,
        network: &str,
    ) -> anyhow::Result<Vec<AegisNetworkMemberRecord>>;
    async fn fetch_aegis_network_member(
        &self,
        network: &str,
        host_id: &HostId,
    ) -> anyhow::Result<Option<AegisNetworkMemberRecord>>;
    async fn update_aegis_host(
        &self,
        host: &AegisHostRecord,
    ) -> Result<AegisHostRecord, AegisHostWriteError>;
    async fn update_aegis_network_member(
        &self,
        network: &str,
        member: &AegisNetworkMemberRecord,
        config: &AegisNetworkConfig,
    ) -> Result<AegisNetworkMemberRecord, AegisHostWriteError>;
    async fn update_aegis_host_report(
        &self,
        host_id: &HostId,
        update: AegisHostReportUpdate,
    ) -> anyhow::Result<bool>;
    async fn delete_aegis_host(
        &self,
        host_id: &HostId,
        networks: &[String],
    ) -> Result<bool, AegisHostDeleteError>;
}

#[cfg(test)]
mod tests {
    use aegis_dto::v1::{AegisDirectGatewayReport, AegisDirectPeerObservation};

    use super::merge_direct_gateway_handshakes;

    #[test]
    fn direct_gateway_handshakes_survive_restart_only_for_current_peers() {
        let previous = AegisDirectGatewayReport {
            observed_unix: 100,
            peers: vec![
                AegisDirectPeerObservation {
                    public_key: "retained".to_string(),
                    latest_handshake_unix: Some(90),
                },
                AegisDirectPeerObservation {
                    public_key: "removed".to_string(),
                    latest_handshake_unix: Some(80),
                },
            ],
        };
        let current = AegisDirectGatewayReport {
            observed_unix: 110,
            peers: vec![
                AegisDirectPeerObservation {
                    public_key: "retained".to_string(),
                    latest_handshake_unix: None,
                },
                AegisDirectPeerObservation {
                    public_key: "new".to_string(),
                    latest_handshake_unix: Some(105),
                },
            ],
        };

        let merged = merge_direct_gateway_handshakes(Some(&previous), current);

        assert_eq!(110, merged.observed_unix);
        assert_eq!(Some(90), merged.peers[0].latest_handshake_unix);
        assert_eq!(Some(105), merged.peers[1].latest_handshake_unix);
        assert!(merged.peers.iter().all(|peer| peer.public_key != "removed"));
    }
}