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
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
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
use bcode_plugin_sdk::path::display_from_current_dir;
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};

use base64::Engine as _;
use serde::{Deserialize, Serialize};
use sha2::{Digest as _, Sha256};
use ssh_key::{Algorithm, LineEnding, PrivateKey, rand_core::OsRng};
use sshenv_vault::models::{ProfileFactorRequirement, UnlockFactorKindV2, VERSION_V2};

const BCODE_VAULT_KEY_DIR_SUFFIX: &str = "keys";
const BCODE_VAULT_PRIVATE_KEY_FILE_NAME: &str = "bcode_sshenv_ed25519";
const BCODE_VAULT_PUBLIC_KEY_FILE_NAME: &str = "bcode_sshenv_ed25519.pub";
const BCODE_VAULT_KEY_COMMENT: &str = "bcode sshenv vault key";

/// Error returned when Bcode-managed auth vault identity material cannot be used.
#[derive(Debug)]
pub enum AuthIdentityError {
    /// Identity material exists only partially and must be repaired manually.
    IncompleteIdentity {
        private_key: PathBuf,
        public_key: PathBuf,
    },
    /// Filesystem or SSH key operation failed.
    OperationFailed { message: String },
}

impl fmt::Display for AuthIdentityError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IncompleteIdentity {
                private_key,
                public_key,
            } => write!(
                formatter,
                "Bcode-managed auth vault identity is incomplete; expected both {} and {}. Remove the incomplete key files and run `bcode login` again.",
                display_from_current_dir(private_key),
                display_from_current_dir(public_key)
            ),
            Self::OperationFailed { message } => formatter.write_str(message),
        }
    }
}

impl std::error::Error for AuthIdentityError {}

/// Return the Bcode-managed key directory for an sshenv vault path.
#[must_use]
pub fn vault_identity_dir(vault_path: &Path) -> PathBuf {
    let mut dir = vault_path.as_os_str().to_os_string();
    dir.push(".");
    dir.push(BCODE_VAULT_KEY_DIR_SUFFIX);
    PathBuf::from(dir)
}

/// Return the Bcode-managed private key path for an sshenv vault path.
#[must_use]
pub fn vault_private_key_path(vault_path: &Path) -> PathBuf {
    vault_identity_dir(vault_path).join(BCODE_VAULT_PRIVATE_KEY_FILE_NAME)
}

/// Return the Bcode-managed public key path for an sshenv vault path.
#[must_use]
pub fn vault_public_key_path(vault_path: &Path) -> PathBuf {
    vault_identity_dir(vault_path).join(BCODE_VAULT_PUBLIC_KEY_FILE_NAME)
}

/// Return private-key paths Bcode may use to unlock an auth vault.
#[must_use]
pub fn vault_private_key_paths(vault_path: &Path) -> Vec<PathBuf> {
    vec![vault_private_key_path(vault_path)]
}

/// Read the Bcode-managed auth vault recipient key if the complete keypair exists.
///
/// # Errors
///
/// Returns an error when only part of the managed keypair exists or the public
/// key cannot be read.
pub fn read_vault_recipient_key(vault_path: &Path) -> Result<Option<String>, AuthIdentityError> {
    let private_key = vault_private_key_path(vault_path);
    let public_key = vault_public_key_path(vault_path);
    match (private_key.exists(), public_key.exists()) {
        (true, true) => read_public_key_file(&public_key).map(Some),
        (false, false) => Ok(None),
        _ => Err(AuthIdentityError::IncompleteIdentity {
            private_key,
            public_key,
        }),
    }
}

/// Create or reuse the Bcode-managed auth vault recipient key for a vault.
///
/// # Errors
///
/// Returns an error when key generation, filesystem writes, or reading the
/// resulting public key fails.
pub fn ensure_vault_recipient_key(vault_path: &Path) -> Result<String, AuthIdentityError> {
    if let Some(key) = read_vault_recipient_key(vault_path)? {
        return Ok(key);
    }

    let identity_dir = vault_identity_dir(vault_path);
    fs::create_dir_all(&identity_dir).map_err(|error| AuthIdentityError::OperationFailed {
        message: format!(
            "failed to create Bcode auth vault key directory {}: {error}",
            display_from_current_dir(&identity_dir)
        ),
    })?;
    restrict_dir_permissions(&identity_dir)?;

    let private_key_path = vault_private_key_path(vault_path);
    let public_key_path = vault_public_key_path(vault_path);
    let mut private_key = PrivateKey::random(&mut OsRng, Algorithm::Ed25519).map_err(|error| {
        AuthIdentityError::OperationFailed {
            message: format!("failed to generate Bcode auth vault key: {error}"),
        }
    })?;
    private_key.set_comment(BCODE_VAULT_KEY_COMMENT);

    let private_key_text = private_key.to_openssh(LineEnding::LF).map_err(|error| {
        AuthIdentityError::OperationFailed {
            message: format!("failed to encode Bcode auth vault private key: {error}"),
        }
    })?;
    let public_key_text = private_key.public_key().to_openssh().map_err(|error| {
        AuthIdentityError::OperationFailed {
            message: format!("failed to encode Bcode auth vault public key: {error}"),
        }
    })?;

    write_private_key_file(&private_key_path, private_key_text.as_str())?;
    write_public_key_file(&public_key_path, &public_key_text)?;
    read_public_key_file(&public_key_path)
}

fn read_public_key_file(path: &Path) -> Result<String, AuthIdentityError> {
    let contents =
        fs::read_to_string(path).map_err(|error| AuthIdentityError::OperationFailed {
            message: format!(
                "failed to read Bcode auth vault public key {}: {error}",
                display_from_current_dir(path)
            ),
        })?;
    contents
        .lines()
        .map(str::trim)
        .find(|line| !line.is_empty() && !line.starts_with('#'))
        .map(ToOwned::to_owned)
        .ok_or_else(|| AuthIdentityError::OperationFailed {
            message: format!(
                "Bcode auth vault public key {} does not contain a public key line",
                display_from_current_dir(path)
            ),
        })
}

fn write_private_key_file(path: &Path, contents: &str) -> Result<(), AuthIdentityError> {
    fs::write(path, contents).map_err(|error| AuthIdentityError::OperationFailed {
        message: format!(
            "failed to write Bcode auth vault private key {}: {error}",
            display_from_current_dir(path)
        ),
    })?;
    restrict_private_key_permissions(path)
}

fn write_public_key_file(path: &Path, contents: &str) -> Result<(), AuthIdentityError> {
    fs::write(path, format!("{contents}\n")).map_err(|error| {
        AuthIdentityError::OperationFailed {
            message: format!(
                "failed to write Bcode auth vault public key {}: {error}",
                display_from_current_dir(path)
            ),
        }
    })?;
    restrict_public_key_permissions(path)
}

#[cfg(unix)]
fn restrict_dir_permissions(path: &Path) -> Result<(), AuthIdentityError> {
    use std::os::unix::fs::PermissionsExt as _;
    fs::set_permissions(path, fs::Permissions::from_mode(0o700)).map_err(|error| {
        AuthIdentityError::OperationFailed {
            message: format!(
                "failed to restrict Bcode auth vault key directory permissions {}: {error}",
                display_from_current_dir(path)
            ),
        }
    })
}

#[cfg(not(unix))]
#[allow(
    clippy::unnecessary_wraps,
    reason = "same fallible interface as Unix permission enforcement"
)]
const fn restrict_dir_permissions(_path: &Path) -> Result<(), AuthIdentityError> {
    Ok(())
}

#[cfg(unix)]
fn restrict_private_key_permissions(path: &Path) -> Result<(), AuthIdentityError> {
    use std::os::unix::fs::PermissionsExt as _;
    fs::set_permissions(path, fs::Permissions::from_mode(0o600)).map_err(|error| {
        AuthIdentityError::OperationFailed {
            message: format!(
                "failed to restrict Bcode auth vault private key permissions {}: {error}",
                display_from_current_dir(path)
            ),
        }
    })
}

#[cfg(not(unix))]
#[allow(
    clippy::unnecessary_wraps,
    reason = "same fallible interface as Unix permission enforcement"
)]
const fn restrict_private_key_permissions(_path: &Path) -> Result<(), AuthIdentityError> {
    Ok(())
}

#[cfg(unix)]
fn restrict_public_key_permissions(path: &Path) -> Result<(), AuthIdentityError> {
    use std::os::unix::fs::PermissionsExt as _;
    fs::set_permissions(path, fs::Permissions::from_mode(0o644)).map_err(|error| {
        AuthIdentityError::OperationFailed {
            message: format!(
                "failed to set Bcode auth vault public key permissions {}: {error}",
                display_from_current_dir(path)
            ),
        }
    })
}

#[cfg(not(unix))]
#[allow(
    clippy::unnecessary_wraps,
    reason = "same fallible interface as Unix permission enforcement"
)]
const fn restrict_public_key_permissions(_path: &Path) -> Result<(), AuthIdentityError> {
    Ok(())
}

/// Severity for auth vault security diagnostics.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum AuthSecurityDiagnosticSeverity {
    /// Informational diagnostic.
    Info,
    /// Warning diagnostic; auth can continue but security policy is not fully satisfied.
    Warning,
    /// Error diagnostic; auth cannot satisfy required security policy.
    Error,
}

impl AuthSecurityDiagnosticSeverity {
    /// String label for this severity.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Info => "info",
            Self::Warning => "warning",
            Self::Error => "error",
        }
    }
}

/// Structured auth vault security diagnostic.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthSecurityDiagnostic {
    /// Severity level.
    pub severity: AuthSecurityDiagnosticSeverity,
    /// Stable diagnostic code.
    pub code: String,
    /// Human-readable diagnostic message.
    pub message: String,
    /// Optional remediation guidance.
    #[serde(default)]
    pub remediation: Option<String>,
}

impl AuthSecurityDiagnostic {
    #[must_use]
    pub(crate) fn info(code: &str, message: impl Into<String>) -> Self {
        Self {
            severity: AuthSecurityDiagnosticSeverity::Info,
            code: code.to_string(),
            message: message.into(),
            remediation: None,
        }
    }

    #[must_use]
    pub(crate) fn warning(
        code: &str,
        message: impl Into<String>,
        remediation: impl Into<String>,
    ) -> Self {
        Self {
            severity: AuthSecurityDiagnosticSeverity::Warning,
            code: code.to_string(),
            message: message.into(),
            remediation: Some(remediation.into()),
        }
    }

    #[must_use]
    pub(crate) fn error(
        code: &str,
        message: impl Into<String>,
        remediation: impl Into<String>,
    ) -> Self {
        Self {
            severity: AuthSecurityDiagnosticSeverity::Error,
            code: code.to_string(),
            message: message.into(),
            remediation: Some(remediation.into()),
        }
    }
}

/// Result of an auth vault security reconciliation attempt.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AuthSecurityReconcileReport {
    /// Structured diagnostics to surface through CLI/TUI/status channels.
    pub diagnostics: Vec<AuthSecurityDiagnostic>,
}

/// Read-only auth vault security status.
#[allow(clippy::struct_excessive_bools)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthSecurityStatus {
    /// Vault path inspected.
    pub vault_path: PathBuf,
    /// Auth profile inspected inside the vault.
    pub profile: String,
    /// Configured device-seal policy.
    pub policy: AuthDeviceSealPolicy,
    /// Whether the vault file exists.
    pub vault_exists: bool,
    /// Vault format version when readable.
    #[serde(default)]
    pub vault_version: Option<u8>,
    /// Whether profile-key mode is enabled.
    pub profile_keys_enabled: bool,
    /// Whether the named profile exists in plaintext or profile-entry form.
    pub profile_exists: bool,
    /// Whether the profile policy requires device seal.
    pub profile_device_sealed: bool,
    /// Device-seal factor backend recorded in profile metadata.
    #[serde(default)]
    pub device_seal_backend: Option<String>,
    /// Device-seal policy recorded in profile metadata.
    #[serde(default)]
    pub device_seal_mode: Option<String>,
    /// Strictness recorded in profile metadata.
    #[serde(default)]
    pub device_seal_strict: Option<bool>,
    /// macOS Keychain service recorded in profile metadata when applicable.
    #[serde(default)]
    pub device_seal_keychain_service: Option<String>,
    /// Whether the current config policy is satisfied by this vault state.
    pub policy_satisfied: bool,
    /// Structured diagnostics for this status.
    pub diagnostics: Vec<AuthSecurityDiagnostic>,
}

/// Inspect auth vault security state without mutating the vault.
#[must_use]
pub fn inspect_auth_vault_security(
    vault_path: &Path,
    profile: &str,
    policy: AuthDeviceSealPolicy,
) -> AuthSecurityStatus {
    let mut status = AuthSecurityStatus {
        vault_path: vault_path.to_path_buf(),
        profile: profile.to_string(),
        policy,
        vault_exists: vault_path.exists(),
        vault_version: None,
        profile_keys_enabled: false,
        profile_exists: false,
        profile_device_sealed: false,
        device_seal_backend: None,
        device_seal_mode: None,
        device_seal_strict: None,
        device_seal_keychain_service: None,
        policy_satisfied: policy != AuthDeviceSealPolicy::Required,
        diagnostics: Vec::new(),
    };
    if !status.vault_exists {
        status.diagnostics.push(AuthSecurityDiagnostic::warning(
            "auth_vault_missing",
            format!(
                "Auth vault does not exist: {}",
                display_from_current_dir(vault_path)
            ),
            "Run `bcode login` for the selected provider.",
        ));
        return status;
    }

    if let Ok(ciphertext) = sshenv_vault::Vault::load_ciphertext(vault_path) {
        status.vault_version = Some(ciphertext.header.version);
    }

    let Ok((mut vault, data_key)) = load_auth_vault_metadata(vault_path) else {
        status.diagnostics.push(AuthSecurityDiagnostic::warning(
            "auth_vault_unlock_failed",
            format!(
                "Auth vault metadata could not be unlocked: {}",
                display_from_current_dir(vault_path)
            ),
            "Ensure the SSH identity used for this vault is available, then retry.",
        ));
        return status;
    };

    status.vault_version = Some(vault.header.version);
    status.profile_keys_enabled = vault.profile_keys_enabled();
    status.profile_exists = vault.profiles.profiles.contains_key(profile)
        || vault.profiles.profile_entries.contains_key(profile);
    populate_device_seal_status(&vault, profile, &mut status);
    let profile_unlockable = if status.profile_exists
        && vault.profiles.get(profile).is_none()
        && vault.profiles.profile_entries.contains_key(profile)
    {
        match vault.unlock_profile_with_passphrase(profile, &data_key, None) {
            Ok(()) => true,
            Err(error) => {
                status.diagnostics.push(AuthSecurityDiagnostic::warning(
                    "auth_vault_profile_unlock_failed",
                    format!("Auth vault profile {profile} could not be unlocked: {error}"),
                    "Restore this device's seal secret, re-login to reset the auth profile, or remove/rebind the profile seal from a device that can unlock it.",
                ));
                false
            }
        }
    } else {
        true
    };
    status.policy_satisfied = match policy {
        AuthDeviceSealPolicy::Off | AuthDeviceSealPolicy::Preferred => true,
        AuthDeviceSealPolicy::Required => status.profile_device_sealed && profile_unlockable,
    };

    if !status.profile_exists {
        status.diagnostics.push(AuthSecurityDiagnostic::warning(
            "auth_vault_profile_missing",
            format!("Auth vault profile {profile} does not exist."),
            "Run `bcode login` for this auth profile.",
        ));
    } else if policy != AuthDeviceSealPolicy::Off && !status.profile_device_sealed {
        let severity = if policy == AuthDeviceSealPolicy::Required {
            AuthSecurityDiagnosticSeverity::Error
        } else {
            AuthSecurityDiagnosticSeverity::Warning
        };
        status.diagnostics.push(AuthSecurityDiagnostic {
            severity,
            code: "auth_vault_device_seal_missing".to_string(),
            message: format!("Auth vault profile {profile} is not device-sealed."),
            remediation: Some(
                "Add settings.recipient_key for the auth profile if migration is needed, then run `bcode auth status` or `bcode login`.".to_string(),
            ),
        });
    } else if policy == AuthDeviceSealPolicy::Off && status.profile_device_sealed {
        status.diagnostics.push(AuthSecurityDiagnostic::info(
            "auth_vault_stronger_than_config",
            format!(
                "Auth vault profile {profile} is device-sealed even though config sets device_seal=off; stronger vault policy is unchanged."
            ),
        ));
    }

    status
}

pub(crate) fn read_auth_vault_profile(
    vault_path: &Path,
    profile: &str,
) -> Result<Option<BTreeMap<String, String>>, String> {
    #[cfg(unix)]
    let _guard = crate::operations::refresh::native::read_guard(vault_path)
        .map_err(|error| error.to_string())?;
    read_auth_vault_profile_uncoordinated(vault_path, profile)
}

pub(crate) fn read_auth_vault_profile_uncoordinated(
    vault_path: &Path,
    profile: &str,
) -> Result<Option<BTreeMap<String, String>>, String> {
    let (mut vault, data_key) = load_auth_vault_metadata(vault_path).map_err(|error| {
        format!(
            "failed to unlock auth vault metadata at {}: {error}",
            display_from_current_dir(vault_path)
        )
    })?;
    if vault.profiles.get(profile).is_none() && vault.profiles.profile_entries.contains_key(profile)
    {
        vault
            .unlock_profile_with_passphrase(profile, &data_key, None)
            .map_err(|error| format!("failed to unlock auth vault profile {profile}: {error}"))?;
    }
    Ok(vault.profiles.get(profile).cloned())
}

fn load_auth_vault_metadata(
    vault_path: &Path,
) -> Result<(sshenv_vault::Vault, sshenv_vault::DataKey), String> {
    let ciphertext = sshenv_vault::Vault::load_ciphertext(vault_path)
        .map_err(|error| format!("failed to load auth vault: {error}"))?;
    let fingerprints: HashSet<String> = ciphertext
        .recipients
        .iter()
        .map(|recipient| recipient.fingerprint.clone())
        .collect();
    let private_key_paths = vault_private_key_paths(vault_path);
    let identities = sshenv_vault::identity::load_identities_for_vault_from_paths(
        &private_key_paths,
        &fingerprints,
    )
    .map_err(|error| format!("failed to load Bcode auth vault SSH identity: {error}"))?;
    if identities.is_empty() {
        return Err(
            "no Bcode-managed auth vault private key matches an auth vault recipient; run `bcode login` to recreate this profile"
                .to_string(),
        );
    }
    sshenv_vault::Vault::unlock_metadata_with_passphrase(ciphertext, &identities, None)
        .map_err(|error| format!("failed to unlock auth vault metadata: {error}"))
}

/// Desired device-seal policy for an sshenv-backed auth profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuthDeviceSealPolicy {
    /// Do not add a device seal automatically.
    Off,
    /// Add a device seal when the local host can support it, but continue on failure.
    Preferred,
    /// Add a device seal and treat failure as a policy violation.
    Required,
}

/// Complete device-seal configuration for an sshenv-backed auth profile.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AuthDeviceSealOptions {
    /// Whether Bcode should reconcile a profile device seal.
    pub policy: AuthDeviceSealPolicy,
    /// Concrete sshenv device-seal selection and strictness.
    pub seal: sshenv_vault::device::DeviceSealOptions,
}

impl AuthDeviceSealOptions {
    /// Default Bcode auth-vault device-seal behavior.
    #[must_use]
    pub const fn preferred_prompt_free() -> Self {
        Self {
            policy: AuthDeviceSealPolicy::Preferred,
            seal: sshenv_vault::device::DeviceSealOptions {
                selection: sshenv_vault::device::DeviceSealSelection::Backend(
                    sshenv_vault::device::DeviceSealBackendSelection::LocalFile,
                ),
                strict: false,
            },
        }
    }

    /// Required Bcode auth-vault device-seal behavior.
    #[must_use]
    pub const fn required_transparent_device_only() -> Self {
        Self {
            policy: AuthDeviceSealPolicy::Required,
            seal: sshenv_vault::device::DeviceSealOptions {
                selection: sshenv_vault::device::DeviceSealSelection::Policy(
                    sshenv_vault::device::DeviceSealPolicy::TransparentDeviceOnly,
                ),
                strict: true,
            },
        }
    }

    /// Build options from the legacy policy-only API.
    #[must_use]
    pub const fn from_policy(policy: AuthDeviceSealPolicy) -> Self {
        match policy {
            AuthDeviceSealPolicy::Required => Self::required_transparent_device_only(),
            AuthDeviceSealPolicy::Off | AuthDeviceSealPolicy::Preferred => Self {
                policy,
                ..Self::preferred_prompt_free()
            },
        }
    }
}

/// Parse an auth profile's `settings.device_seal` value.
#[must_use]
pub fn device_seal_policy_for_auth_profile(
    auth_profile: &bcode_config::AuthProfileConfig,
) -> AuthDeviceSealPolicy {
    auth_profile
        .settings
        .get("device_seal")
        .map_or(AuthDeviceSealPolicy::Preferred, |value| {
            match value.trim().to_ascii_lowercase().as_str() {
                "off" | "false" | "disabled" | "never" => AuthDeviceSealPolicy::Off,
                "required" | "require" | "true" | "on" => AuthDeviceSealPolicy::Required,
                _ => AuthDeviceSealPolicy::Preferred,
            }
        })
}

/// Parse an auth profile's device-seal settings.
#[must_use]
pub fn device_seal_options_for_auth_profile(
    auth_profile: &bcode_config::AuthProfileConfig,
) -> AuthDeviceSealOptions {
    let policy = device_seal_policy_for_auth_profile(auth_profile);
    let default_options = AuthDeviceSealOptions::from_policy(policy);
    let selection = auth_profile
        .settings
        .get("device_seal_backend")
        .and_then(|value| parse_device_seal_backend(value))
        .map_or_else(
            || {
                auth_profile
                    .settings
                    .get("device_seal_mode")
                    .and_then(|value| parse_device_seal_policy(value))
                    .map_or(default_options.seal.selection, |mode| {
                        sshenv_vault::device::DeviceSealSelection::Policy(mode)
                    })
            },
            sshenv_vault::device::DeviceSealSelection::Backend,
        );
    let strict = auth_profile
        .settings
        .get("device_seal_strict")
        .map_or(default_options.seal.strict, |value| {
            parse_bool_setting(value, default_options.seal.strict)
        });
    AuthDeviceSealOptions {
        policy,
        seal: sshenv_vault::device::DeviceSealOptions { selection, strict },
    }
}

fn parse_device_seal_policy(value: &str) -> Option<sshenv_vault::device::DeviceSealPolicy> {
    match normalize_setting(value).as_str() {
        "default" | "legacy" => Some(sshenv_vault::device::DeviceSealPolicy::Default),
        "transparentdeviceonly" | "transparentlocaldevice" | "devicelocaltransparent" => {
            Some(sshenv_vault::device::DeviceSealPolicy::TransparentDeviceOnly)
        }
        _ => None,
    }
}

fn parse_device_seal_backend(
    value: &str,
) -> Option<sshenv_vault::device::DeviceSealBackendSelection> {
    match normalize_setting(value).as_str() {
        "macoskeychain" => Some(sshenv_vault::device::DeviceSealBackendSelection::MacosKeychain),
        "macoskeychaindeviceonly" => {
            Some(sshenv_vault::device::DeviceSealBackendSelection::MacosKeychainDeviceOnly)
        }
        "windowsdpapi" | "windowsdpapicurrentuser" => {
            Some(sshenv_vault::device::DeviceSealBackendSelection::WindowsDpapiCurrentUser)
        }
        "linuxtpm" | "tpm" => Some(sshenv_vault::device::DeviceSealBackendSelection::LinuxTpm),
        "linuxsecretservice" | "secretservice" => {
            Some(sshenv_vault::device::DeviceSealBackendSelection::LinuxSecretService)
        }
        "secureenclave" => Some(sshenv_vault::device::DeviceSealBackendSelection::SecureEnclave),
        "localfile" => Some(sshenv_vault::device::DeviceSealBackendSelection::LocalFile),
        _ => None,
    }
}

fn parse_bool_setting(value: &str, default: bool) -> bool {
    match value.trim().to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" | "strict" => true,
        "0" | "false" | "no" | "off" | "relaxed" => false,
        _ => default,
    }
}

fn normalize_setting(value: &str) -> String {
    value
        .chars()
        .filter(char::is_ascii_alphanumeric)
        .flat_map(char::to_lowercase)
        .collect()
}

/// Safely reconcile an sshenv auth profile and return structured diagnostics.
#[must_use]
pub fn reconcile_auth_vault_security_report(
    vault_path: &Path,
    profile: &str,
    policy: AuthDeviceSealPolicy,
    explicit_recipient_key: Option<&str>,
) -> AuthSecurityReconcileReport {
    reconcile_auth_vault_security_report_with_options(
        vault_path,
        profile,
        AuthDeviceSealOptions::from_policy(policy),
        explicit_recipient_key,
    )
}

/// Safely reconcile an sshenv auth profile with explicit device-seal options and
/// return structured diagnostics.
#[must_use]
pub fn reconcile_auth_vault_security_report_with_options(
    vault_path: &Path,
    profile: &str,
    options: AuthDeviceSealOptions,
    explicit_recipient_key: Option<&str>,
) -> AuthSecurityReconcileReport {
    match reconcile_auth_vault_security_with_options(
        vault_path,
        profile,
        options,
        explicit_recipient_key,
    ) {
        Ok(actions) => AuthSecurityReconcileReport {
            diagnostics: actions
                .into_iter()
                .map(|action| AuthSecurityDiagnostic::info("auth_vault_security_refreshed", action))
                .collect(),
        },
        Err(error) => {
            let severity = if options.policy == AuthDeviceSealPolicy::Required {
                AuthSecurityDiagnosticSeverity::Error
            } else {
                AuthSecurityDiagnosticSeverity::Warning
            };
            let diagnostic = match severity {
                AuthSecurityDiagnosticSeverity::Info => {
                    AuthSecurityDiagnostic::info("auth_vault_security_refresh_skipped", error)
                }
                AuthSecurityDiagnosticSeverity::Warning => AuthSecurityDiagnostic::warning(
                    "auth_vault_security_refresh_skipped",
                    format!(
                        "Auth vault security refresh skipped for profile {profile}; device seal is preferred but not active: {error}"
                    ),
                    "Run `bcode login` to recreate credentials with the Bcode-managed per-vault key.",
                ),
                AuthSecurityDiagnosticSeverity::Error => AuthSecurityDiagnostic::error(
                    "auth_vault_security_required_unsatisfied",
                    format!(
                        "Auth vault security requirement is not satisfied for profile {profile}: {error}"
                    ),
                    "Run `bcode login` to recreate credentials with the Bcode-managed per-vault key.",
                ),
            };
            AuthSecurityReconcileReport {
                diagnostics: vec![diagnostic],
            }
        }
    }
}

/// Safely reconcile an sshenv auth profile with the requested device-seal policy.
///
/// This only performs non-destructive upgrades. It may migrate a vault to v2,
/// enable profile-key mode, and add a per-profile device seal. It will not
/// remove an existing device seal when policy is [`AuthDeviceSealPolicy::Off`].
///
/// # Errors
///
/// Returns an error when the requested policy cannot be applied. Callers using
/// [`AuthDeviceSealPolicy::Preferred`] may convert the error into a warning.
pub fn reconcile_auth_vault_security(
    vault_path: &Path,
    profile: &str,
    policy: AuthDeviceSealPolicy,
    explicit_recipient_key: Option<&str>,
) -> Result<Vec<String>, String> {
    reconcile_auth_vault_security_with_options(
        vault_path,
        profile,
        AuthDeviceSealOptions::from_policy(policy),
        explicit_recipient_key,
    )
}

/// Safely reconcile an sshenv auth profile with explicit device-seal options.
///
/// This only performs non-destructive upgrades. It may migrate a vault to v2,
/// enable profile-key mode, and add a per-profile device seal. It will not
/// remove an existing device seal when policy is [`AuthDeviceSealPolicy::Off`].
///
/// # Errors
///
/// Returns an error when the requested policy/options cannot be applied.
pub fn reconcile_auth_vault_security_with_options(
    vault_path: &Path,
    profile: &str,
    options: AuthDeviceSealOptions,
    explicit_recipient_key: Option<&str>,
) -> Result<Vec<String>, String> {
    if !vault_path.exists() {
        return Ok(Vec::new());
    }

    let (mut vault, data_key) = load_auth_vault_metadata(vault_path)
        .map_err(|error| format!("failed to unlock auth vault metadata: {error}"))?;

    let (actions, changed) = prepare_auth_vault_security(
        &mut vault,
        &data_key,
        vault_path,
        profile,
        options,
        explicit_recipient_key,
    )?;
    if changed {
        vault
            .save(vault_path, &data_key)
            .map_err(|error| format!("failed to save reconciled auth vault: {error}"))?;
    }
    Ok(actions)
}

/// Prepare security changes on the caller's loaded vault without publishing credentials.
/// The caller must discard this vault on failure and retain ownership through publication.
pub(crate) fn prepare_auth_vault_security(
    vault: &mut sshenv_vault::Vault,
    data_key: &[u8; 32],
    vault_path: &Path,
    profile: &str,
    options: AuthDeviceSealOptions,
    explicit_recipient_key: Option<&str>,
) -> Result<(Vec<String>, bool), String> {
    let mut actions = Vec::new();
    if matches!(options.policy, AuthDeviceSealPolicy::Off) {
        if profile_has_device_seal(vault, profile) {
            actions.push(format!(
                "auth profile {profile} is device-sealed even though config sets device_seal=off; leaving stronger vault policy unchanged"
            ));
        }
        return Ok((actions, false));
    }

    if !vault.profiles.profiles.contains_key(profile)
        && !vault.profiles.profile_entries.contains_key(profile)
    {
        return Ok((actions, false));
    }

    if profile_has_device_seal(vault, profile)
        && profile_device_seal_matches_options(vault, profile, options.seal)
    {
        return Ok((actions, false));
    }

    if vault.profiles.get(profile).is_none() && vault.profiles.profile_entries.contains_key(profile)
    {
        vault
            .unlock_profile_with_passphrase(profile, data_key, None)
            .map_err(|error| format!("failed to unlock auth profile {profile}: {error}"))?;
    }

    if vault.header.version != VERSION_V2 {
        let recipient_keys = recipient_keys_for_vault(vault_path, vault, explicit_recipient_key)?;
        vault
            .migrate_to_v2(&recipient_keys)
            .map_err(|error| format!("failed to migrate auth vault to v2: {error}"))?;
        actions.push("migrated auth vault to sshenv v2".to_string());
    }

    if !vault.profile_keys_enabled() {
        vault
            .enable_profile_keys()
            .map_err(|error| format!("failed to enable auth profile keys: {error}"))?;
        actions.push("enabled per-profile auth vault encryption".to_string());
    }

    let rebinding_existing_seal = profile_has_device_seal(vault, profile);
    vault
        .require_profile_device_seal_with_options(profile, options.seal)
        .map_err(|error| {
            format!("failed to bind auth profile {profile} to this device: {error}")
        })?;
    actions.push(if rebinding_existing_seal {
        format!("rebound auth profile {profile} to configured device seal")
    } else {
        format!("bound auth profile {profile} to this device")
    });
    Ok((actions, true))
}

/// Prepare current-format retained policy without native factor effects or format conversion.
#[cfg(unix)]
pub(crate) fn prepare_retained_device_policy(
    vault: &mut sshenv_vault::Vault,
    resolved: &crate::ResolvedAuthProfile,
    profile: &str,
    source: Option<&dyn crate::operations::AuthDeviceFactorSource>,
    intent: Option<&crate::operations::AuthProvisioningIntent>,
) -> Result<Vec<AuthSecurityDiagnostic>, crate::lifecycle::AuthVaultLifecycleError> {
    let options = device_seal_options_for_auth_profile(&resolved.profile);
    if validate_retained_device_policy(vault, profile, options).is_ok() {
        return Ok(Vec::new());
    }
    let mut prepared = vault.clone();
    let result = (|| {
        if prepared.header.version != VERSION_V2 {
            return Err(crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
                "explicit vault migration required".into(),
            ));
        }
        let source = source.ok_or_else(|| {
            crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
                "device provisioning unavailable".into(),
            )
        })?;
        prepared.enable_profile_keys().map_err(|_| {
            crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
                "profile encryption unavailable".into(),
            )
        })?;
        let intent = intent.ok_or_else(|| {
            crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
                "recoverable provisioning unavailable".into(),
            )
        })?;
        let factor = source.provision_attempt(intent)?;
        // Verify the selected custody source can recover the exact key before binding it.
        // This is not a durability guarantee; the source still owns durable factor retention.
        let recovered = source
            .retrieve(
                &factor.id,
                factor.recipient_fingerprint.as_deref(),
                &factor.parameters,
            )
            .map_err(|_| {
                crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
                    "provisioned device factor unavailable".into(),
                )
            })?;
        if *recovered != *factor.key {
            return Err(crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
                "provisioned device factor mismatch".into(),
            ));
        }
        prepared
            .require_profile_device_seal_with(profile, || {
                Ok((
                    sshenv_vault::models::UnlockFactorV2 {
                        id: factor.id,
                        kind: sshenv_vault::models::UnlockFactorKindV2::DeviceSeal,
                        recipient_fingerprint: factor.recipient_fingerprint,
                        params: factor.parameters,
                    },
                    factor.key,
                ))
            })
            .map_err(|_| {
                crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
                    "device binding failed".into(),
                )
            })?;
        validate_retained_device_policy(&prepared, profile, options)
    })();
    if result.is_ok() {
        *vault = prepared;
        return Ok(Vec::new());
    }
    if options.policy == AuthDeviceSealPolicy::Required {
        result?;
    }
    Ok(vec![AuthSecurityDiagnostic::warning(
        "auth_vault_security_refresh_skipped",
        "Preferred device provisioning failed; existing policy preserved",
        "Restore selected device custody to enable the preferred seal",
    )])
}

/// Verify that retained custody can preserve an already-satisfied device policy.
/// No migration, factor creation, or native discovery occurs here.
#[cfg(unix)]
pub(crate) fn validate_retained_device_policy(
    vault: &sshenv_vault::Vault,
    profile: &str,
    options: AuthDeviceSealOptions,
) -> Result<(), crate::lifecycle::AuthVaultLifecycleError> {
    if options.policy == AuthDeviceSealPolicy::Off
        || (profile_has_device_seal(vault, profile)
            && profile_device_seal_matches_options(vault, profile, options.seal))
    {
        return Ok(());
    }
    Err(crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
        "retained device policy requires explicit factor provisioning before update".into(),
    ))
}

fn populate_device_seal_status(
    vault: &sshenv_vault::Vault,
    profile: &str,
    status: &mut AuthSecurityStatus,
) {
    status.profile_device_sealed = profile_has_device_seal(vault, profile);
    if let Some(metadata) = profile_device_seal_metadata(vault, profile) {
        status.device_seal_backend = metadata.params.get("backend").cloned();
        status.device_seal_mode = metadata.params.get("policy").cloned();
        status.device_seal_strict = metadata
            .params
            .get("strict")
            .map(|value| parse_bool_setting(value, true));
        status.device_seal_keychain_service = metadata.params.get("keychain-service").cloned();
    }
}

fn profile_has_device_seal(vault: &sshenv_vault::Vault, profile: &str) -> bool {
    profile_device_seal_metadata(vault, profile).is_some_and(|_| {
        vault
            .profiles
            .profile_policy(profile)
            .is_some_and(|policy| {
                policy
                    .required_factors
                    .contains(&ProfileFactorRequirement::DeviceSeal)
            })
    })
}

fn profile_device_seal_matches_options(
    vault: &sshenv_vault::Vault,
    profile: &str,
    options: sshenv_vault::device::DeviceSealOptions,
) -> bool {
    profile_device_seal_metadata(vault, profile)
        .is_some_and(|metadata| sshenv_vault::device::factor_matches_options(metadata, options))
}

fn profile_device_seal_metadata<'a>(
    vault: &'a sshenv_vault::Vault,
    profile: &str,
) -> Option<&'a sshenv_vault::models::UnlockFactorV2> {
    vault.profiles.profile_policy(profile).and_then(|policy| {
        policy
            .factor_metadata
            .iter()
            .find(|factor| factor.kind == UnlockFactorKindV2::DeviceSeal)
    })
}

fn recipient_keys_for_vault(
    vault_path: &Path,
    vault: &sshenv_vault::Vault,
    explicit_recipient_key: Option<&str>,
) -> Result<Vec<String>, String> {
    let expected: BTreeSet<_> = vault
        .recipients
        .iter()
        .map(|recipient| recipient.fingerprint.clone())
        .collect();
    let candidates = recipient_key_candidates(vault_path, explicit_recipient_key);
    let by_fingerprint: BTreeMap<_, _> = candidates
        .into_iter()
        .filter_map(|line| {
            fingerprint_for_public_key_line(&line).map(|fingerprint| (fingerprint, line))
        })
        .collect();

    let mut keys = Vec::new();
    let mut missing = Vec::new();
    for fingerprint in expected {
        if let Some(line) = by_fingerprint.get(&fingerprint) {
            keys.push(line.clone());
        } else {
            missing.push(fingerprint);
        }
    }
    if missing.is_empty() {
        Ok(keys)
    } else {
        Err(format!(
            "cannot migrate existing auth vault to v2 because recipient public keys were not found for: {}. Run `bcode login` to recreate credentials with the Bcode-managed per-vault key, or pass --recipient-key if this vault intentionally uses a custom key.",
            missing.join(", ")
        ))
    }
}

fn recipient_key_candidates(
    vault_path: &Path,
    explicit_recipient_key: Option<&str>,
) -> Vec<String> {
    let mut candidates = Vec::new();
    if let Some(key) = explicit_recipient_key.and_then(read_public_key_arg) {
        candidates.push(key);
    } else if let Ok(Some(key)) = read_vault_recipient_key(vault_path) {
        candidates.push(key);
    }
    candidates
}

fn read_public_key_arg(value: &str) -> Option<String> {
    let trimmed = value.trim();
    if trimmed.starts_with("ssh-") {
        return Some(trimmed.to_string());
    }
    fs::read_to_string(trimmed).ok()
}

fn fingerprint_for_public_key_line(line: &str) -> Option<String> {
    let body = line.split_whitespace().nth(1)?;
    let decoded = base64::engine::general_purpose::STANDARD
        .decode(body)
        .ok()?;
    let hash = Sha256::digest(decoded);
    let encoded = base64::engine::general_purpose::STANDARD_NO_PAD.encode(hash);
    Some(format!("SHA256:{encoded}"))
}

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

    #[test]
    #[cfg(windows)]
    fn windows_dpapi_device_seal_round_trips_for_current_user() {
        let options = sshenv_vault::device::DeviceSealOptions {
            selection: sshenv_vault::device::DeviceSealSelection::Backend(
                sshenv_vault::device::DeviceSealBackendSelection::WindowsDpapiCurrentUser,
            ),
            strict: true,
        };
        let (metadata, created) =
            sshenv_vault::device::create_factor_with_options(options).expect("create DPAPI seal");
        let loaded = sshenv_vault::device::derive_factor_from_metadata(&metadata)
            .expect("load DPAPI seal for current user");
        assert_eq!(&*created, &*loaded);
        assert_eq!(
            metadata.params.get("backend").map(String::as_str),
            Some("windows-dpapi")
        );
    }

    #[test]
    fn explicit_windows_dpapi_backend_is_parsed_without_secret_data() {
        assert_eq!(
            parse_device_seal_backend("windows-dpapi-current-user"),
            Some(sshenv_vault::device::DeviceSealBackendSelection::WindowsDpapiCurrentUser)
        );
    }
}