bcode_provider_auth 0.0.1-alpha.0

Provider auth materialization helpers for bcode
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
//! Explicit storage for encrypted credential custody, separate from subscription state.

use std::io::{Read as _, Write as _};
use std::path::Path;

#[cfg(feature = "simulation")]
pub mod simulation;

const MAGIC: &[u8] = b"BCODE-CUSTODY\0\x01";
const MAX_BYTES: usize = 4 * 1024 * 1024;

/// Secret-safe custody storage failure.
#[derive(Debug, thiserror::Error)]
pub enum CustodyStorageError {
    /// Ownership cannot be verified.
    #[error("credential custody ownership unavailable")]
    Ownership,
    /// Preserve unsupported, damaged, or interrupted state for maintenance.
    #[error("credential custody requires maintenance")]
    MaintenanceRequired,
    /// The caller's ciphertext no longer matches stored state.
    #[error("credential custody changed; reload before retrying")]
    Conflict,
    /// Publication may have occurred if its final durability barrier failed.
    #[error("credential custody storage failed")]
    Io(#[source] std::io::Error),
}

/// Retained ownership of encrypted credential state and its provisioning fence.
///
/// Implementations must confine access to an exclusively acquired location, bound reads,
/// preserve unsupported state, and release all ownership on drop. Publication must compare
/// expected ciphertext and atomically replace it under that ownership. Native implementations
/// must durably publish both ciphertext and provisioning intents; simulated implementations
/// must explicitly document their durability limits. Errors must never trigger native fallback.
/// This contract selects storage effects only, not vault policy or credential mapping.
pub trait AuthCustodyStorage: Send {
    /// Read bounded, validated current-format vault ciphertext without mutation or repair.
    ///
    /// # Errors
    /// Returns errors for unavailable, damaged, or unsupported state.
    fn read(&self) -> Result<Vec<u8>, CustodyStorageError>;

    /// Compare and publish validated ciphertext, preserving unrelated state.
    ///
    /// # Errors
    /// Rejects stale expected bytes or invalid state. Failure after publication is uncertain
    /// and must not be interpreted as rollback.
    fn compare_and_publish(
        &mut self,
        expected: &[u8],
        ciphertext: &[u8],
    ) -> Result<(), CustodyStorageError>;

    /// Verify no unresolved provisioning fence exists before admitting mutation.
    ///
    /// # Errors
    /// Fails closed if absence cannot be verified.
    fn ensure_no_provisioning(&self) -> Result<(), CustodyStorageError>;

    /// Exclusively publish an intent before invoking external provisioning effects.
    ///
    /// # Errors
    /// Rejects existing, unsupported, or unpublishable intents without replacing a fence.
    fn begin_provisioning(
        &self,
        intent: &crate::operations::AuthProvisioningIntent,
    ) -> Result<(), CustodyStorageError>;

    /// Read a bounded current-format intent without guessing historical representations.
    ///
    /// # Errors
    /// Returns errors for missing, damaged, or unsupported intents.
    fn provisioning_intent(
        &self,
    ) -> Result<crate::operations::AuthProvisioningIntent, CustodyStorageError>;

    /// Clear a fence only after caller-verified publication or source reconciliation.
    ///
    /// # Errors
    /// Returns storage errors; failed removal must not be treated as acknowledged completion.
    /// Verify that no remote refresh has an unresolved outcome.
    ///
    /// # Errors
    /// Unsupported storage fails closed rather than admitting a remote exchange.
    fn ensure_no_refresh(&self) -> Result<(), CustodyStorageError> {
        Err(CustodyStorageError::MaintenanceRequired)
    }

    /// Durably admit exactly one profile-bound remote exchange.
    ///
    /// # Errors
    /// Rejects an existing fence, unsupported storage, and uncertain publication.
    fn begin_refresh(&self, _intent: &AuthRefreshIntent) -> Result<(), CustodyStorageError> {
        Err(CustodyStorageError::MaintenanceRequired)
    }

    /// Read the unresolved refresh identity without clearing or replaying it.
    ///
    /// # Errors
    /// Rejects missing, damaged, or unsupported state.
    fn refresh_intent(&self) -> Result<AuthRefreshIntent, CustodyStorageError> {
        Err(CustodyStorageError::MaintenanceRequired)
    }

    /// Clear only the matching fence after durable rotation or owner-verified re-enrollment.
    ///
    /// # Errors
    /// Rejects stale attempts; failed durability must block further use by this owner.
    fn finish_refresh(&self, _intent: &AuthRefreshIntent) -> Result<(), CustodyStorageError> {
        Err(CustodyStorageError::MaintenanceRequired)
    }

    /// Clear the device-provisioning fence after verified completion.
    ///
    /// # Errors
    /// Failed removal or durability remains unresolved.
    fn finish_provisioning(&self) -> Result<(), CustodyStorageError>;
}

/// Non-secret, owner-protected durable refresh fence. Device provisioning is independent.
#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AuthRefreshIntent {
    /// Independently versioned on-disk record.
    pub version: u16,
    /// Opaque random identity; never log it.
    pub attempt: String,
    /// Hash of the canonical custody/profile ownership binding.
    pub profile_binding: String,
}

impl AuthRefreshIntent {
    fn validate(&self) -> Result<(), CustodyStorageError> {
        if self.version != 1
            || self.attempt.len() != 64
            || self.profile_binding.len() != 64
            || !self.attempt.bytes().all(|byte| byte.is_ascii_hexdigit())
            || !self
                .profile_binding
                .bytes()
                .all(|byte| byte.is_ascii_hexdigit())
        {
            return Err(CustodyStorageError::MaintenanceRequired);
        }
        Ok(())
    }
}

/// An exclusively owned Unix custody directory containing only encrypted vault data.
///
/// Callers must control the directory's ancestors and exclude hostile same-user filesystem
/// mutation. The retained directory and lock confine operations after acquisition. This is
/// not an import API: ordinary sshenv files are rejected, never converted or overwritten.
#[cfg(unix)]
#[derive(Debug)]
pub struct CredentialCustodyStorage {
    directory: std::fs::File,
    _lock: std::fs::File,
    refresh_poisoned: std::cell::Cell<bool>,
}

#[cfg(unix)]
impl CredentialCustodyStorage {
    /// Acquire an existing private custody directory without repair or initialization.
    ///
    /// # Errors
    /// Returns ownership, representation, or I/O errors, preserving existing state.
    pub fn open(path: &Path) -> Result<Self, CustodyStorageError> {
        let store = Self::acquire(path, false)?;
        store.read()?;
        Ok(store)
    }

    /// Create a fresh private directory and publish validated encrypted vault bytes.
    ///
    /// # Errors
    /// Rejects existing/relative paths or invalid vault bytes. Failed initialization is
    /// preserved for explicit maintenance, not silently retried.
    pub fn create(path: &Path, ciphertext: &[u8]) -> Result<Self, CustodyStorageError> {
        use std::os::unix::fs::DirBuilderExt as _;
        validate(ciphertext)?;
        if !path.is_absolute() {
            return Err(CustodyStorageError::Ownership);
        }
        std::fs::DirBuilder::new()
            .mode(0o700)
            .create(path)
            .map_err(CustodyStorageError::Io)?;
        let store = Self::acquire(path, true)?;
        store.publish(ciphertext)?;
        // The directory entry itself must survive a crash before remote enrollment is admitted.
        let parent = path.parent().ok_or(CustodyStorageError::Ownership)?;
        std::fs::File::open(parent)
            .and_then(|directory| directory.sync_all())
            .map_err(CustodyStorageError::Io)?;
        Ok(store)
    }

    /// Acquire durable refresh coordination for an existing native vault, without copying
    /// its ciphertext or changing its storage format. The caller controls the parent.
    /// Durable refresh coordination is acquired only for authorized credential operations.
    /// No vault conversion or credential materialization is performed by this coordinator.
    /// Errors preserve existing state for explicit maintenance.
    pub(crate) fn native_coordinator(vault: &Path) -> Result<Self, CustodyStorageError> {
        use std::os::unix::fs::DirBuilderExt as _;
        if !vault.is_absolute()
            || std::fs::symlink_metadata(vault)
                .map_err(CustodyStorageError::Io)?
                .file_type()
                .is_symlink()
        {
            return Err(CustodyStorageError::Ownership);
        }
        let mut name = vault.as_os_str().to_os_string();
        name.push(".refresh");
        let path = std::path::PathBuf::from(name);
        match std::fs::DirBuilder::new().mode(0o700).create(&path) {
            Ok(()) => {
                let store = Self::acquire(&path, true)?;
                store
                    .directory
                    .sync_all()
                    .map_err(CustodyStorageError::Io)?;
                std::fs::File::open(path.parent().ok_or(CustodyStorageError::Ownership)?)
                    .and_then(|parent| parent.sync_all())
                    .map_err(CustodyStorageError::Io)?;
                Ok(store)
            }
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {
                Self::acquire(&path, false)
            }
            Err(error) => Err(CustodyStorageError::Io(error)),
        }
    }

    fn acquire(path: &Path, create: bool) -> Result<Self, CustodyStorageError> {
        use std::os::unix::fs::{MetadataExt as _, OpenOptionsExt as _};
        if !path.is_absolute() {
            return Err(CustodyStorageError::Ownership);
        }
        let directory = std::fs::OpenOptions::new()
            .read(true)
            .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC)
            .open(path)
            .map_err(CustodyStorageError::Io)?;
        let metadata = directory.metadata().map_err(CustodyStorageError::Io)?;
        // SAFETY: geteuid has no preconditions.
        if metadata.uid() != unsafe { libc::geteuid() } || metadata.mode() & 0o077 != 0 {
            return Err(CustodyStorageError::Ownership);
        }
        let lock = crate::store::open_owned_entry(
            &directory,
            c"owner.lock",
            libc::O_RDWR
                | if create {
                    libc::O_CREAT | libc::O_EXCL
                } else {
                    0
                },
        )
        .map_err(CustodyStorageError::Io)?;
        lock.try_lock()
            .map_err(|_| CustodyStorageError::Ownership)?;
        // A pending publication cannot be guessed to have succeeded or failed.
        match crate::store::open_owned_entry(&directory, c"pending", libc::O_RDONLY) {
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            _ => return Err(CustodyStorageError::MaintenanceRequired),
        }
        Ok(Self {
            directory,
            _lock: lock,
            refresh_poisoned: std::cell::Cell::new(false),
        })
    }

    /// Read bounded encrypted vault bytes; never unlock, repair, or select another location.
    ///
    /// # Errors
    /// Returns storage or maintenance errors for missing/unsupported/damaged data.
    pub fn read(&self) -> Result<Vec<u8>, CustodyStorageError> {
        if self.refresh_poisoned.get() {
            return Err(CustodyStorageError::MaintenanceRequired);
        }
        match crate::store::open_owned_entry(&self.directory, c"pending", libc::O_RDONLY) {
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            _ => return Err(CustodyStorageError::MaintenanceRequired),
        }
        let file = crate::store::open_owned_entry(&self.directory, c"custody", libc::O_RDONLY)
            .map_err(CustodyStorageError::Io)?;
        let mut bytes = Vec::new();
        file.take((MAX_BYTES + MAGIC.len() + 1) as u64)
            .read_to_end(&mut bytes)
            .map_err(CustodyStorageError::Io)?;
        let ciphertext = bytes
            .strip_prefix(MAGIC)
            .ok_or(CustodyStorageError::MaintenanceRequired)?;
        validate(ciphertext)?;
        Ok(ciphertext.to_vec())
    }

    /// Compare current ciphertext and publish its replacement under retained ownership.
    ///
    /// # Errors
    /// Rejects stale expected bytes, invalid replacements, or interrupted publication. An
    /// error after rename is uncertain: read state before retrying, never assume rollback.
    pub fn compare_and_publish(
        &mut self,
        expected: &[u8],
        ciphertext: &[u8],
    ) -> Result<(), CustodyStorageError> {
        validate(ciphertext)?;
        if self.read()? != expected {
            return Err(CustodyStorageError::Conflict);
        }
        self.publish(ciphertext)
    }

    /// Reject unresolved external provisioning before any further credential mutation.
    pub(crate) fn ensure_no_provisioning(&self) -> Result<(), CustodyStorageError> {
        match crate::store::open_owned_entry(&self.directory, c"provisioning-v1", libc::O_RDONLY) {
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
            _ => Err(CustodyStorageError::MaintenanceRequired),
        }
    }

    /// Durably fence external provisioning before dispatch. Any failure preserves the fence.
    pub(crate) fn begin_provisioning(
        &self,
        intent: &crate::operations::AuthProvisioningIntent,
    ) -> Result<(), CustodyStorageError> {
        self.ensure_no_provisioning()?;
        let bytes =
            serde_json::to_vec(intent).map_err(|_| CustodyStorageError::MaintenanceRequired)?;
        if intent.version != 2
            || intent.source.is_empty()
            || intent.operation.is_empty()
            || bytes.len() > 65536
        {
            return Err(CustodyStorageError::MaintenanceRequired);
        }
        let mut intent = crate::store::open_owned_entry(
            &self.directory,
            c"provisioning-v1",
            libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL,
        )
        .map_err(CustodyStorageError::Io)?;
        intent
            .write_all(&bytes)
            .and_then(|()| intent.sync_all())
            .map_err(CustodyStorageError::Io)?;
        self.directory.sync_all().map_err(CustodyStorageError::Io)
    }

    /// Read a bounded current-format intent; legacy markers are never guessed.
    pub(crate) fn provisioning_intent(
        &self,
    ) -> Result<crate::operations::AuthProvisioningIntent, CustodyStorageError> {
        let file =
            crate::store::open_owned_entry(&self.directory, c"provisioning-v1", libc::O_RDONLY)
                .map_err(CustodyStorageError::Io)?;
        let mut bytes = Vec::new();
        file.take(65537)
            .read_to_end(&mut bytes)
            .map_err(CustodyStorageError::Io)?;
        if bytes.len() > 65536 {
            return Err(CustodyStorageError::MaintenanceRequired);
        }
        let intent: crate::operations::AuthProvisioningIntent =
            serde_json::from_slice(&bytes).map_err(|_| CustodyStorageError::MaintenanceRequired)?;
        if intent.version != 2 || intent.source.is_empty() || intent.operation.is_empty() {
            return Err(CustodyStorageError::MaintenanceRequired);
        }
        Ok(intent)
    }

    /// Clear the fence only after verified factor binding and durable custody publication.
    pub(crate) fn finish_provisioning(&self) -> Result<(), CustodyStorageError> {
        use std::os::fd::AsRawFd as _;
        // SAFETY: the static relative name and retained directory descriptor are valid.
        if unsafe { libc::unlinkat(self.directory.as_raw_fd(), c"provisioning-v1".as_ptr(), 0) }
            != 0
        {
            return Err(CustodyStorageError::Io(std::io::Error::last_os_error()));
        }
        self.directory.sync_all().map_err(CustodyStorageError::Io)
    }

    fn publish(&self, ciphertext: &[u8]) -> Result<(), CustodyStorageError> {
        use std::os::fd::AsRawFd as _;
        let mut pending = crate::store::open_owned_entry(
            &self.directory,
            c"pending",
            libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL,
        )
        .map_err(CustodyStorageError::Io)?;
        pending
            .write_all(MAGIC)
            .and_then(|()| pending.write_all(ciphertext))
            .and_then(|()| pending.sync_all())
            .map_err(CustodyStorageError::Io)?;
        // SAFETY: both static C names are relative to the live retained directory descriptor.
        if unsafe {
            libc::renameat(
                self.directory.as_raw_fd(),
                c"pending".as_ptr(),
                self.directory.as_raw_fd(),
                c"custody".as_ptr(),
            )
        } != 0
        {
            return Err(CustodyStorageError::Io(std::io::Error::last_os_error()));
        }
        self.directory.sync_all().map_err(CustodyStorageError::Io)
    }
}

#[cfg(unix)]
impl AuthCustodyStorage for CredentialCustodyStorage {
    fn read(&self) -> Result<Vec<u8>, CustodyStorageError> {
        Self::read(self)
    }

    fn compare_and_publish(
        &mut self,
        expected: &[u8],
        ciphertext: &[u8],
    ) -> Result<(), CustodyStorageError> {
        Self::compare_and_publish(self, expected, ciphertext)
    }

    fn ensure_no_provisioning(&self) -> Result<(), CustodyStorageError> {
        Self::ensure_no_provisioning(self)
    }

    fn begin_provisioning(
        &self,
        intent: &crate::operations::AuthProvisioningIntent,
    ) -> Result<(), CustodyStorageError> {
        Self::begin_provisioning(self, intent)
    }

    fn provisioning_intent(
        &self,
    ) -> Result<crate::operations::AuthProvisioningIntent, CustodyStorageError> {
        Self::provisioning_intent(self)
    }

    fn ensure_no_refresh(&self) -> Result<(), CustodyStorageError> {
        if self.refresh_poisoned.get() {
            return Err(CustodyStorageError::MaintenanceRequired);
        }
        match crate::store::open_owned_entry(&self.directory, c"refresh-v1", libc::O_RDONLY) {
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
            _ => Err(CustodyStorageError::MaintenanceRequired),
        }
    }

    fn begin_refresh(&self, intent: &AuthRefreshIntent) -> Result<(), CustodyStorageError> {
        intent.validate()?;
        self.ensure_no_refresh()?;
        self.ensure_no_provisioning()?;
        let bytes =
            serde_json::to_vec(intent).map_err(|_| CustodyStorageError::MaintenanceRequired)?;
        let mut file = crate::store::open_owned_entry(
            &self.directory,
            c"refresh-v1",
            libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL,
        )
        .map_err(CustodyStorageError::Io)?;
        file.write_all(&bytes).map_err(CustodyStorageError::Io)?;
        file.sync_all().map_err(CustodyStorageError::Io)?;
        self.directory.sync_all().map_err(CustodyStorageError::Io)
    }

    fn refresh_intent(&self) -> Result<AuthRefreshIntent, CustodyStorageError> {
        if self.refresh_poisoned.get() {
            return Err(CustodyStorageError::MaintenanceRequired);
        }
        let file = crate::store::open_owned_entry(&self.directory, c"refresh-v1", libc::O_RDONLY)
            .map_err(CustodyStorageError::Io)?;
        let mut bytes = Vec::new();
        file.take(1025)
            .read_to_end(&mut bytes)
            .map_err(CustodyStorageError::Io)?;
        if bytes.len() > 1024 {
            return Err(CustodyStorageError::MaintenanceRequired);
        }
        let intent: AuthRefreshIntent =
            serde_json::from_slice(&bytes).map_err(|_| CustodyStorageError::MaintenanceRequired)?;
        intent.validate()?;
        Ok(intent)
    }

    fn finish_refresh(&self, intent: &AuthRefreshIntent) -> Result<(), CustodyStorageError> {
        use std::os::fd::AsRawFd as _;
        if self.refresh_intent()? != *intent {
            return Err(CustodyStorageError::Conflict);
        }
        // SAFETY: the static relative name and retained directory descriptor are valid.
        if unsafe { libc::unlinkat(self.directory.as_raw_fd(), c"refresh-v1".as_ptr(), 0) } != 0 {
            return Err(CustodyStorageError::Io(std::io::Error::last_os_error()));
        }
        if let Err(error) = self.directory.sync_all() {
            self.refresh_poisoned.set(true);
            return Err(CustodyStorageError::Io(error));
        }
        Ok(())
    }

    fn finish_provisioning(&self) -> Result<(), CustodyStorageError> {
        Self::finish_provisioning(self)
    }
}

fn validate(ciphertext: &[u8]) -> Result<(), CustodyStorageError> {
    if ciphertext.len() > MAX_BYTES {
        return Err(CustodyStorageError::MaintenanceRequired);
    }
    sshenv_vault::Vault::decode_ciphertext(ciphertext)
        .map_err(|_| CustodyStorageError::MaintenanceRequired)?;
    Ok(())
}

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

    #[test]
    fn uncertain_publication_blocks_reads_without_clearing_refresh() {
        let temp = tempfile::tempdir().unwrap();
        #[cfg(not(feature = "custody-simulation"))]
        let public =
            crate::security::ensure_vault_recipient_key(&temp.path().join("source")).unwrap();
        #[cfg(feature = "custody-simulation")]
        let public = "sim-age:uncertain-owner".to_owned();
        let (vault, key) = sshenv_vault::Vault::create(&public).unwrap();
        let mut ciphertext = Vec::new();
        vault
            .save_with_storage(&key, |bytes, _| {
                ciphertext = bytes.to_vec();
                Ok(())
            })
            .unwrap();
        let path = temp.path().join("owned");
        let mut storage = CredentialCustodyStorage::create(&path, &ciphertext).unwrap();
        let intent = AuthRefreshIntent {
            version: 1,
            attempt: "a".repeat(64),
            profile_binding: "b".repeat(64),
        };
        storage.begin_refresh(&intent).unwrap();
        // A crash/interrupted writer can leave this ownership-confined publication marker.
        std::fs::write(path.join("pending"), b"interrupted").unwrap();
        assert!(
            storage
                .compare_and_publish(&ciphertext, &ciphertext)
                .is_err()
        );
        assert!(storage.read().is_err());
        assert!(storage.ensure_no_refresh().is_err());
        assert!(storage.refresh_intent().unwrap() == intent);
        drop(storage);
        assert!(CredentialCustodyStorage::open(&path).is_err());
        assert!(path.join("refresh-v1").exists());
        assert_eq!(
            std::fs::read(path.join("custody")).unwrap()[MAGIC.len()..],
            ciphertext
        );
    }

    #[test]
    fn encrypted_owner_conflicts_release_and_incompatible_envelope() {
        let temp = tempfile::tempdir().unwrap();
        #[cfg(not(feature = "custody-simulation"))]
        let public =
            crate::security::ensure_vault_recipient_key(&temp.path().join("source")).unwrap();
        #[cfg(feature = "custody-simulation")]
        let public = "sim-age:storage-owner".to_owned();
        let (vault, key) = sshenv_vault::Vault::create(&public).unwrap();
        let mut ciphertext = Vec::new();
        vault
            .save_with_storage(&key, |bytes, _| {
                ciphertext = bytes.to_vec();
                Ok(())
            })
            .unwrap();
        let path = temp.path().join("owned");
        let mut storage = CredentialCustodyStorage::create(&path, &ciphertext).unwrap();
        assert!(CredentialCustodyStorage::open(&path).is_err());
        assert!(sshenv_vault::Vault::load_ciphertext(&path.join("custody")).is_err());
        assert!(matches!(
            storage.compare_and_publish(b"stale", &ciphertext),
            Err(CustodyStorageError::Conflict)
        ));
        assert_eq!(storage.read().unwrap(), ciphertext);
        storage
            .compare_and_publish(&ciphertext, &ciphertext)
            .unwrap();
        let refresh = AuthRefreshIntent {
            version: 1,
            attempt: "a".repeat(64),
            profile_binding: "b".repeat(64),
        };
        storage.begin_refresh(&refresh).unwrap();
        assert!(storage.ensure_no_refresh().is_err());
        assert!(storage.begin_refresh(&refresh).is_err());
        let stale = AuthRefreshIntent {
            attempt: "c".repeat(64),
            ..refresh.clone()
        };
        assert!(storage.finish_refresh(&stale).is_err());
        drop(storage);
        let storage = CredentialCustodyStorage::open(&path).unwrap();
        assert!(storage.refresh_intent().unwrap() == refresh);
        assert!(storage.ensure_no_refresh().is_err());
        storage.finish_refresh(&refresh).unwrap();
        storage.ensure_no_refresh().unwrap();
        let intent = crate::operations::AuthProvisioningIntent {
            version: 2,
            source: "test".into(),
            operation: "attempt-1".into(),
            profile_binding: "test-binding".into(),
        };
        storage.begin_provisioning(&intent).unwrap();
        drop(storage);
        let reopened = CredentialCustodyStorage::open(&path).unwrap();
        assert!(matches!(
            reopened.ensure_no_provisioning(),
            Err(CustodyStorageError::MaintenanceRequired)
        ));
        assert!(reopened.provisioning_intent().unwrap() == intent);
        assert!(reopened.begin_provisioning(&intent).is_err());
        reopened.finish_provisioning().unwrap();
        reopened.ensure_no_provisioning().unwrap();
        assert_eq!(reopened.read().unwrap(), ciphertext);
        drop(reopened);
        std::fs::write(path.join("custody"), &ciphertext).unwrap();
        assert!(matches!(
            CredentialCustodyStorage::open(&path),
            Err(CustodyStorageError::MaintenanceRequired)
        ));
        assert_eq!(std::fs::read(path.join("custody")).unwrap(), ciphertext);
    }
}