agentknock 0.2.0

Developer secrets on your phone, provided only to approved commands.
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
use std::{fmt, fs, future::Future, io, path::Path, pin::Pin};

use base64::{
    Engine as _,
    engine::general_purpose::{STANDARD as BASE64_STANDARD, URL_SAFE_NO_PAD as BASE64_URL_SAFE},
};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use ulid::Ulid;

use crate::{
    Client, ConfigurationError, RequestError,
    config::{
        CanonicalUlid, LockedPairing, abort_pending_pairing, current_timestamp,
        ensure_pairing_absent, finish_pending_pairing, lock_pairing_if_rotated_before,
        read_pairing_from, read_pending_pairing, remove_active_pairing,
        remove_pairing as remove_pairing_file, write_pending_pairing,
    },
    crypto::{
        self, PROTOCOL_VERSION, PairingResponse, Session, derive_address_id,
        derive_pairing_commitment, derive_psk_rotation, generate_client_secret, seal_pairing,
    },
    protocol::{self, Method, Response},
    websocket::RelayExchange,
};

const PSK_ROTATION_INTERVAL_SECONDS: u64 = 24 * 60 * 60;

/// A short authentication string for verifying an initial pairing.
///
/// Its [`fmt::Display`] representation contains 12 decimal digits in three
/// groups, such as `1234 5678 9012`. The user must confirm the full displayed
/// value against the value shown by the device before accepting the pairing.
pub struct PairingSas(u64);

/// A stage reported while a pairing operation is running.
///
/// A successful operation reports `Preparing`, `WaitingForDelivery`,
/// optionally one or more `WaitingForResponse` updates, `Completing`, and
/// `Completed`, in that order. An operation that fails stops without reporting
/// `Completed`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum PairingProgress {
    /// Agentknock is reading local state and preparing the protected request.
    Preparing,

    /// The request is waiting to be delivered to the device.
    WaitingForDelivery,

    /// The device has received the request but hasn't returned a response.
    WaitingForResponse,

    /// Agentknock is processing the response and handing off the completion.
    Completing,

    /// The operation has finished successfully.
    Completed,
}

impl fmt::Display for PairingSas {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let sas = self.0;
        write!(
            formatter,
            "{:04} {:04} {:04}",
            sas / 100_000_000,
            sas / 10_000 % 10_000,
            sas % 10_000,
        )
    }
}

impl Client {
    /// Starts pairing with the device displaying `address`.
    ///
    /// `address` must contain one or more lowercase ASCII words separated by
    /// single hyphens. The method creates a pending local pairing and returns
    /// the [`PairingSas`] after the initial exchange is complete. The pairing
    /// remains pending until [`Client::finish_pairing`] succeeds.
    ///
    /// The `progress` callback receives lifecycle updates synchronously and
    /// should return promptly. If `cancellation` resolves before the method
    /// returns, Agentknock stops the exchange, removes any pending state it
    /// created, and returns [`RequestError::Interrupted`]. Pass
    /// [`std::future::pending()`] when the operation doesn't need cancellation.
    ///
    /// # Errors
    ///
    /// Returns an error if the address is invalid, local pairing state already
    /// exists, the state can't be read or written safely, the exchange fails,
    /// or the operation is canceled.
    pub async fn start_pairing<P>(
        &self,
        address: &str,
        cancellation: impl Future<Output = ()>,
        mut progress: P,
    ) -> Result<PairingSas, RequestError>
    where
        P: FnMut(PairingProgress),
    {
        tokio::pin!(cancellation);
        if !is_valid_pairing_address(address) {
            return Err(RequestError::other(
                "pairing address must contain lowercase ASCII words separated by single hyphens",
            ));
        }
        progress(PairingProgress::Preparing);
        let pairing_path = self.pairing_path()?;
        ensure_pairing_absent(&pairing_path)?;
        let client_secret = generate_client_secret().map_err(RequestError::other)?;
        let commitment = derive_pairing_commitment(&client_secret).map_err(RequestError::other)?;
        let request_id = Ulid::generate();
        let client_id = CanonicalUlid::new(request_id);
        let client_token = generate_client_token()?;
        let address_id = derive_address_id(address).map_err(RequestError::other)?;
        let mut relay = RelayExchange::pairing(
            &address_id.to_string(),
            &request_id.to_string(),
            &client_token,
        )?;
        let request = PairingRequest {
            version: PROTOCOL_VERSION,
            commitment: BASE64_STANDARD.encode(commitment),
        };
        progress(PairingProgress::WaitingForDelivery);
        let response: PairingResponse = tokio::select! {
            biased;
            _ = cancellation.as_mut() => return Err(RequestError::Interrupted),
            response = relay.request(&request, || {
                progress(PairingProgress::WaitingForResponse);
            }) => response?,
        };
        progress(PairingProgress::Completing);
        let contents = PairingMetadata {
            platform: std::env::consts::OS,
            architecture: std::env::consts::ARCH,
            hostname: read_trimmed("/etc/hostname"),
            machine_id: read_trimmed("/etc/machine-id"),
            os_version: os_version(),
        };
        let application_plaintext = self.encode(&contents).map_err(RequestError::other)?;
        let (completion, pairing, sas) = seal_pairing(
            client_id,
            client_token,
            response,
            &client_secret,
            &application_plaintext,
        )
        .map_err(RequestError::other)?;
        write_pending_pairing(&pairing_path, &pairing)?;

        let result = tokio::select! {
            biased;
            _ = cancellation.as_mut() => Err(RequestError::Interrupted),
            result = relay.complete(&completion) => result.map_err(RequestError::from),
        };
        if let Err(error) = result {
            let _ = abort_pending_pairing(&pairing_path);
            return Err(error);
        }
        progress(PairingProgress::Completed);
        Ok(PairingSas(sas))
    }
}

fn is_valid_pairing_address(address: &str) -> bool {
    address
        .split('-')
        .all(|word| !word.is_empty() && word.bytes().all(|byte| byte.is_ascii_lowercase()))
}

impl Client {
    /// Activates the pending pairing after the user verifies and accepts it.
    ///
    /// Call this only after the user confirms the complete [`PairingSas`] on
    /// the device and accepts the pairing there. Agentknock requires an
    /// authenticated acceptance response before it marks the local pairing as
    /// active.
    ///
    /// The `progress` callback receives lifecycle updates synchronously and
    /// should return promptly. Cancellation before authenticated acceptance
    /// leaves the pairing pending and returns [`RequestError::Interrupted`].
    /// Once acceptance is authenticated and local activation is durable, the
    /// pairing remains active even if the completion handoff fails.
    /// Cancellation after activation only shortens that handoff and doesn't
    /// undo or report failure. Pass [`std::future::pending()`] when the
    /// operation doesn't need cancellation.
    ///
    /// # Errors
    ///
    /// Returns an error if there is no pending pairing, local state is invalid,
    /// the device rejects the pairing, the operation is canceled before
    /// activation, or the exchange fails. An exchange error during completion
    /// can be returned after the local pairing becomes active.
    pub async fn finish_pairing<P>(
        &self,
        cancellation: impl Future<Output = ()>,
        mut progress: P,
    ) -> Result<(), RequestError>
    where
        P: FnMut(PairingProgress),
    {
        tokio::pin!(cancellation);
        progress(PairingProgress::Preparing);
        let pairing_path = self.pairing_path()?;
        let pairing = read_pending_pairing(&pairing_path)?;
        let request_id = Ulid::generate();
        let plaintext = self
            .encode(&MethodRequest {
                method: Method::PairingFinish,
            })
            .map_err(RequestError::other)?;
        let mut session = Session::new(&pairing, &request_id).map_err(RequestError::other)?;
        let request = session
            .seal_request(&plaintext)
            .map_err(RequestError::other)?;
        let mut relay = RelayExchange::authenticated(&pairing, &request_id.to_string())?;
        progress(PairingProgress::WaitingForDelivery);
        let response = tokio::select! {
            biased;
            _ = cancellation.as_mut() => return Err(RequestError::Interrupted),
            response = relay.request(&request, || {
                progress(PairingProgress::WaitingForResponse);
            }) => response?,
        };
        progress(PairingProgress::Completing);
        let plaintext = session
            .open_response(response)
            .map_err(RequestError::other)?;
        let result: FinishPairingResult =
            match protocol::decode_response(&plaintext).map_err(RequestError::other)? {
                Response::Message(result) => result,
                Response::Error(error) => {
                    if let Some(completion) =
                        protocol::seal_error_completion(self, &mut session, &error)
                    {
                        let _ = relay.complete_briefly(&completion).await;
                    }
                    return Err(RequestError::DeviceRejected {
                        code: error.code,
                        message: error.message,
                    });
                }
            };
        if result == FinishPairingResult::Rejected {
            return Err(RequestError::PairingRejected);
        }

        let plaintext = self
            .encode(&FinishPairingResult::Accepted)
            .map_err(RequestError::other)?;
        let completion = session
            .seal_completion(&plaintext)
            .map_err(RequestError::other)?;
        finish_pending_pairing(&pairing_path)?;
        let interrupted = tokio::select! {
            biased;
            _ = cancellation.as_mut() => true,
            result = relay.complete(&completion) => {
                result?;
                false
            }
        };
        if interrupted {
            let _ = relay.complete_briefly(&completion).await;
        }
        progress(PairingProgress::Completed);

        Ok(())
    }

    /// Deletes a pending local pairing without contacting the device.
    ///
    /// Use this after the user rejects or abandons an initial pairing. This
    /// method refuses to delete an active pairing.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigurationError::NoPairing`] if no pairing exists,
    /// [`ConfigurationError::PairingNotPending`] if the pairing is active, or
    /// another configuration error if the pending state can't be removed.
    pub fn abort_pairing(&self) -> Result<(), ConfigurationError> {
        abort_pending_pairing(&self.pairing_path()?)
    }

    /// Deletes the local pairing without contacting the device.
    ///
    /// This is a recovery operation for state that can't be removed through
    /// [`Client::remove_pairing`]. It can delete either a pending or an active
    /// pairing, and it leaves any corresponding device state unchanged.
    ///
    /// # Errors
    ///
    /// Returns a configuration error if no local pairing exists or the pairing
    /// file can't be removed.
    pub fn force_remove_pairing(&self) -> Result<(), ConfigurationError> {
        remove_pairing_file(&self.pairing_path()?)
    }

    /// Removes an active pairing from both the device and this client.
    ///
    /// Agentknock waits for an authenticated device response before deleting
    /// local state. It then hands off a best-effort completion to tell the
    /// device that local removal succeeded.
    ///
    /// The `progress` callback receives lifecycle updates synchronously and
    /// should return promptly. Cancellation before the authenticated response
    /// leaves local state unchanged. Cancellation after local removal only
    /// shortens the best-effort completion attempt. Pass
    /// [`std::future::pending()`] when the operation doesn't need cancellation.
    ///
    /// # Errors
    ///
    /// Returns [`PairingRemoveError`] if the pairing isn't active, the exchange
    /// fails before authenticated removal, or local deletion fails.
    pub async fn remove_pairing<P>(
        &self,
        cancellation: impl Future<Output = ()>,
        mut progress: P,
    ) -> Result<(), PairingRemoveError>
    where
        P: FnMut(PairingProgress),
    {
        tokio::pin!(cancellation);
        progress(PairingProgress::Preparing);
        let pairing_path = self
            .pairing_path()
            .map_err(PairingRemoveError::Configuration)?;
        let pairing =
            read_pairing_from(&pairing_path).map_err(PairingRemoveError::Configuration)?;
        let device_id = pairing.device_id_bytes();
        let client_id = pairing.client_id_bytes();
        let (mut relay, completion) =
            prepare_pairing_removal(self, &pairing, cancellation.as_mut(), &mut progress)
                .await
                .map_err(PairingRemoveError::Request)?;
        remove_active_pairing(&pairing_path, device_id, client_id)
            .map_err(PairingRemoveError::LocalState)?;
        tokio::select! {
            biased;
            _ = cancellation.as_mut() => {},
            _ = relay.complete_briefly(&completion) => {},
        }
        progress(PairingProgress::Completed);
        Ok(())
    }
}

async fn prepare_pairing_removal<P>(
    client: &Client,
    pairing: &crate::config::Pairing,
    mut cancellation: Pin<&mut impl Future<Output = ()>>,
    progress: &mut P,
) -> Result<(RelayExchange, crypto::Completion), RequestError>
where
    P: FnMut(PairingProgress),
{
    let request_id = Ulid::generate();
    let plaintext = client
        .encode(&MethodRequest {
            method: Method::PairingRemove,
        })
        .map_err(RequestError::other)?;
    let mut session = Session::new(pairing, &request_id).map_err(RequestError::other)?;
    let request = session
        .seal_request(&plaintext)
        .map_err(RequestError::other)?;
    let mut relay = RelayExchange::authenticated(pairing, &request_id.to_string())?;
    progress(PairingProgress::WaitingForDelivery);
    let response = tokio::select! {
        biased;
        _ = cancellation.as_mut() => return Err(RequestError::Interrupted),
        response = relay.request(&request, || {
            progress(PairingProgress::WaitingForResponse);
        }) => response?,
    };
    progress(PairingProgress::Completing);
    let plaintext = session
        .open_response(response)
        .map_err(RequestError::other)?;
    match protocol::decode_response::<EmptyMessage>(&plaintext).map_err(RequestError::other)? {
        Response::Message(_) => {}
        Response::Error(error) => {
            if let Some(completion) = protocol::seal_error_completion(client, &mut session, &error)
            {
                let _ = relay.complete_briefly(&completion).await;
            }
            return Err(RequestError::DeviceRejected {
                code: error.code,
                message: error.message,
            });
        }
    }
    let plaintext = client
        .encode(&EmptyMessage {})
        .map_err(RequestError::other)?;
    let completion = session
        .seal_completion(&plaintext)
        .map_err(RequestError::other)?;

    Ok((relay, completion))
}

impl Client {
    pub(crate) fn maybe_rotate_psk(&self) -> Result<bool, RotationError> {
        maybe_rotate_psk_at(&self.pairing_path()?, current_timestamp()?)
    }
}

fn maybe_rotate_psk_at(path: &Path, now: u64) -> Result<bool, RotationError> {
    let rotated_before = now.saturating_sub(PSK_ROTATION_INTERVAL_SECONDS);
    let pairing = read_pairing_from(path)?;
    if pairing.rotation_key().is_some() || !pairing.rotated_before(rotated_before) {
        return Ok(false);
    }

    let Some(pairing) = lock_pairing_if_rotated_before(path, rotated_before)? else {
        return Ok(false);
    };
    rotate_locked(pairing, now)?;
    Ok(true)
}

fn rotate_locked(pairing: LockedPairing, rotated_at: u64) -> Result<(), RotationError> {
    let rotation = derive_psk_rotation(pairing.pairing()).map_err(io::Error::other)?;
    pairing.write_rotation(&rotation.client_psk, &rotation.rotation_key, rotated_at)?;
    Ok(())
}

#[derive(Debug, Error)]
pub(crate) enum RotationError {
    #[error(transparent)]
    Configuration(#[from] ConfigurationError),

    #[error(transparent)]
    Other(#[from] io::Error),
}

/// An error removing an active pairing.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum PairingRemoveError {
    /// Local state prevented the removal request from starting.
    #[error(transparent)]
    Configuration(ConfigurationError),

    /// The authenticated removal exchange didn't complete successfully.
    #[error(transparent)]
    Request(RequestError),

    /// The device accepted removal, but deleting local state failed.
    #[error("device removed the pairing, but local pairing removal failed: {0}")]
    LocalState(ConfigurationError),
}

#[cfg(test)]
fn format_sas(sas: u64) -> String {
    PairingSas(sas).to_string()
}

#[derive(Serialize)]
struct PairingRequest {
    version: &'static str,
    commitment: String,
}

#[derive(Serialize)]
struct MethodRequest {
    method: Method,
}

#[derive(Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
struct EmptyMessage {}

#[derive(Deserialize, Eq, PartialEq, Serialize)]
#[serde(tag = "result", rename_all = "SCREAMING_SNAKE_CASE")]
enum FinishPairingResult {
    Accepted,
    Rejected,
}

#[derive(Serialize)]
struct PairingMetadata {
    platform: &'static str,
    architecture: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    hostname: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    machine_id: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    os_version: Option<String>,
}

fn read_trimmed(path: impl AsRef<Path>) -> Option<String> {
    let contents = fs::read_to_string(path).ok()?;
    let contents = contents.trim();
    (!contents.is_empty()).then(|| contents.to_owned())
}

fn os_version() -> Option<String> {
    fs::read_to_string("/etc/os-release")
        .ok()?
        .lines()
        .find_map(|line| line.strip_prefix("PRETTY_NAME="))
        .map(|value| value.trim_matches('"'))
        .filter(|value| !value.is_empty())
        .map(str::to_owned)
}

fn generate_client_token() -> io::Result<String> {
    let mut token = [0; 32];
    getrandom::fill(&mut token).map_err(io::Error::other)?;
    Ok(BASE64_URL_SAFE.encode(token))
}

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

    #[cfg(unix)]
    use std::{
        env, fs,
        fs::OpenOptions,
        io::Write as _,
        os::unix::fs::{OpenOptionsExt, PermissionsExt},
        path::PathBuf,
    };

    #[cfg(unix)]
    use base64::{
        Engine as _,
        engine::general_purpose::{
            STANDARD as BASE64_STANDARD, URL_SAFE_NO_PAD as BASE64_URL_SAFE,
        },
    };
    #[cfg(unix)]
    use hpke::{
        Deserializable, Kem as KemTrait, OpModeR, PskBundle, Serializable,
        aead::ChaCha20Poly1305,
        hybrid_array::Array,
        kdf::{HkdfSha256, Kdf as HpkeKdfTrait},
        kem::X25519HkdfSha256,
        setup_receiver,
    };
    #[cfg(unix)]
    use serde_json::{Value, json};
    #[cfg(unix)]
    use ulid::Ulid;

    use super::is_valid_pairing_address;
    #[cfg(unix)]
    use super::{PSK_ROTATION_INTERVAL_SECONDS, maybe_rotate_psk_at};

    #[test]
    fn formats_sas_as_three_groups() {
        assert_eq!(format_sas(123_456_789), "0001 2345 6789");
    }

    #[test]
    fn validates_pairing_addresses() {
        for address in ["free", "yup-its-free"] {
            assert!(is_valid_pairing_address(address));
        }
        for address in ["", "-", "--", "-free", "free-", "yup--its-free"] {
            assert!(!is_valid_pairing_address(address));
        }
    }

    #[cfg(unix)]
    #[test]
    fn rotates_client_psk_locally() {
        type Aead = ChaCha20Poly1305;
        type Kdf = HkdfSha256;
        type Kem = X25519HkdfSha256;
        type KdfSizedBytes = Array<u8, <Kdf as HpkeKdfTrait>::Nh>;

        const DEVICE_ID: &str = "01K2ENXDTW1P3XAR4J7V7C9D0H";
        const CLIENT_ID: &str = "01K2EP16NWNAGJYF8J1Q2V6P3X";
        const OLD_PSK: [u8; 32] = [0x42; 32];
        const PSK_EXPORT_CONTEXT: &[u8] = b"agentknock-v1 psk";
        const NOW: u64 = 2_000_000_000;

        let directory = TestDirectory::new();
        let path = directory.path.join("pairing.json");
        let (device_private_key, device_public_key) = Kem::gen_keypair();
        let mut file = OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o600)
            .open(&path)
            .unwrap();
        serde_json::to_writer_pretty(
            &mut file,
            &json!({
                "device_id": DEVICE_ID,
                "client_id": CLIENT_ID,
                "client_token": BASE64_URL_SAFE.encode([0x24; 32]),
                "client_psk": BASE64_STANDARD.encode(OLD_PSK),
                "device_key": BASE64_STANDARD.encode(device_public_key.to_bytes()),
                "rotated_at": NOW - PSK_ROTATION_INTERVAL_SECONDS,
            }),
        )
        .unwrap();
        file.write_all(b"\n").unwrap();
        drop(file);

        assert!(!maybe_rotate_psk_at(&path, NOW).unwrap());
        assert!(
            serde_json::from_slice::<Value>(&fs::read(&path).unwrap())
                .unwrap()
                .get("rotation_key")
                .is_none()
        );

        let first_path = path.clone();
        let second_path = path.clone();
        let first = std::thread::spawn(move || maybe_rotate_psk_at(&first_path, NOW + 1));
        let second = std::thread::spawn(move || maybe_rotate_psk_at(&second_path, NOW + 1));
        let mut results = [
            first.join().unwrap().unwrap(),
            second.join().unwrap().unwrap(),
        ];
        results.sort_unstable();
        assert_eq!(results, [false, true]);

        let contents = fs::read(&path).unwrap();
        let pairing: Value = serde_json::from_slice(&contents).unwrap();
        assert_eq!(pairing["rotated_at"], NOW + 1);
        let rotation_key = BASE64_STANDARD
            .decode(pairing["rotation_key"].as_str().unwrap())
            .unwrap();
        let encapped_key = <Kem as KemTrait>::EncappedKey::from_bytes(&rotation_key).unwrap();
        let new_psk = BASE64_STANDARD
            .decode(pairing["client_psk"].as_str().unwrap())
            .unwrap();
        assert_ne!(new_psk, OLD_PSK);

        let device_id = DEVICE_ID.parse::<Ulid>().unwrap().to_bytes();
        let client_id = CLIENT_ID.parse::<Ulid>().unwrap().to_bytes();
        let info = [crate::crypto::PROTOCOL_VERSION_INFO, device_id, [0; 16]].concat();
        let psk = PskBundle::new(&OLD_PSK, &client_id).unwrap();
        let receiver_context = setup_receiver::<Aead, Kdf, Kem>(
            &OpModeR::Psk(psk),
            &device_private_key,
            &encapped_key,
            &info,
        )
        .unwrap();
        let mut expected_psk = KdfSizedBytes::default();
        receiver_context
            .export(PSK_EXPORT_CONTEXT, &mut expected_psk)
            .unwrap();
        assert_eq!(new_psk, expected_psk.as_slice());
        assert_eq!(
            fs::metadata(&path).unwrap().permissions().mode() & 0o777,
            0o600
        );

        assert!(!maybe_rotate_psk_at(&path, NOW + 2).unwrap());
        assert_eq!(fs::read(&path).unwrap(), contents);
    }

    #[cfg(unix)]
    struct TestDirectory {
        path: PathBuf,
    }

    #[cfg(unix)]
    impl TestDirectory {
        fn new() -> Self {
            let path = env::temp_dir().join(format!("agentknock-test-{}", Ulid::generate()));
            fs::create_dir(&path).unwrap();
            Self { path }
        }
    }

    #[cfg(unix)]
    impl Drop for TestDirectory {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.path);
        }
    }
}