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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
//! Host-owned provider-auth application operations.

use crate::{AuthProfileResolutionError, ResolvedAuthProfile, lifecycle::AuthVaultLifecycle};
#[cfg(unix)]
mod enrollment;
#[cfg(unix)]
pub use enrollment::{
    CustodyEnrollment, CustodyEnrollmentMode, CustodyEnrollmentReadiness, read_custody_identity,
};
#[cfg(unix)]
pub(crate) mod refresh;
use bcode_provider_auth_models::{
    AUTH_CREDENTIAL_UPDATE_SCHEMA_VERSION, AUTH_SECURITY_INSPECTION_SCHEMA_VERSION,
    AuthCredentialUpdateRequest, AuthCredentialUpdateResponse, AuthDiagnostic,
    AuthDiagnosticSeverity, AuthMethodContribution, AuthSecurityInspectionRequest,
    AuthSecurityInspectionResponse,
};
#[cfg(unix)]
pub use refresh::resolve_refresh_service_request_with_custody;

/// Authorization context bound by the host from an active plugin/provider invocation.
#[derive(Clone, Copy)]
pub struct AuthCredentialUpdateContext<'a> {
    pub caller_plugin_id: &'a str,
    pub provider_id: &'a str,
    pub resolved: &'a ResolvedAuthProfile,
    pub method: &'a AuthMethodContribution,
}

/// Selected host credential custody, invoked only after canonical authorization and mapping.
///
/// Implementations must atomically apply storage-key changes to the resolved profile, preserve
/// unrelated values, enforce its device-seal policy, and return secret-safe errors. This is a
/// trusted host service, never a plugin-supplied authorization hook.
pub trait AuthCredentialCustody: Send + Sync {
    /// Admit a remote refresh only after durable fencing and snapshot comparison.
    ///
    /// # Errors
    /// Unsupported custody and unresolved attempts fail closed.
    fn begin_refresh(
        &self,
        _resolved: &ResolvedAuthProfile,
        _request: bcode_provider_auth_models::AuthRefreshBeginRequest,
    ) -> Result<
        bcode_provider_auth_models::AuthRefreshBeginResponse,
        crate::lifecycle::AuthVaultLifecycleError,
    > {
        Err(crate::lifecycle::AuthVaultLifecycleError::RefreshUnsupported)
    }

    /// Commit the complete record for the matching admitted attempt.
    ///
    /// # Errors
    /// Stale identities, incomplete records, and uncertain publication fail closed.
    fn commit_refresh(
        &self,
        _resolved: &ResolvedAuthProfile,
        _request: bcode_provider_auth_models::AuthRefreshCommitRequest,
    ) -> Result<AuthCredentialUpdateResponse, crate::lifecycle::AuthVaultLifecycleError> {
        Err(crate::lifecycle::AuthVaultLifecycleError::RefreshUnsupported)
    }

    /// Persist validated changes for the host-resolved owner and profile.
    ///
    /// # Errors
    /// Returns an error if ownership, policy, or atomic persistence cannot be satisfied.
    fn persist(
        &self,
        resolved: &ResolvedAuthProfile,
        changes: std::collections::BTreeMap<String, Option<String>>,
    ) -> Result<
        Vec<crate::security::AuthSecurityDiagnostic>,
        crate::lifecycle::AuthVaultLifecycleError,
    >;
}

/// Trusted request-time credential source selected by the host.
///
/// Implementations verify the destination and profile before reading secrets. Errors must be
/// secret-safe; callers must not dispatch with stale request credentials after failure.
pub trait AuthRequestCustody: Send + Sync {
    /// Materialize credentials for the selected destination and request context.
    ///
    /// # Errors
    /// Returns an error when destination ownership, selection, or custody cannot be verified.
    fn materialize(
        &self,
        plugin_id: &str,
        context: &bcode_model::ProviderRequestContext,
    ) -> Result<crate::ResolvedProviderAuth, crate::lifecycle::AuthVaultLifecycleError>;
}

/// Selected device-factor provisioning result. Never log its key.
pub struct AuthProvisionedDeviceFactor {
    /// Stable factor identity.
    pub id: String,
    /// Optional recipient binding.
    pub recipient_fingerprint: Option<String>,
    /// Non-secret backend metadata, validated against configured policy by custody.
    pub parameters: std::collections::BTreeMap<String, String>,
    /// Fresh factor key. Production sources must use cryptographically secure entropy.
    pub key: zeroize::Zeroizing<[u8; 32]>,
}

/// Durable identity of a selected-source provisioning attempt (format version 2).
#[derive(Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct AuthProvisioningIntent {
    /// Compatibility boundary; unsupported versions require maintenance.
    pub version: u32,
    /// Stable source identity, verified on reconciliation.
    pub source: String,
    /// Source-owned unique operation identity; never reused for a different attempt.
    pub operation: String,
    /// SHA-256 binding of the resolved profile and policy; no credential settings are stored.
    pub profile_binding: String,
}

#[cfg(unix)]
pub(crate) fn provisioning_binding(
    profile: &ResolvedAuthProfile,
) -> Result<String, crate::lifecycle::AuthVaultLifecycleError> {
    use sha2::Digest as _;
    let bytes = zeroize::Zeroizing::new(
        serde_json::to_vec(&(
            &profile.profile_name,
            &profile.provider_id,
            &profile.owner_plugin_id,
            &profile.profile,
            matches!(profile.source, crate::AuthProfileSource::Runtime),
        ))
        .map_err(|_| crate::lifecycle::AuthVaultLifecycleError::InvalidCredential)?,
    );
    Ok(hex::encode(sha2::Sha256::digest(bytes.as_slice())))
}

/// Caller-selected retrieval of an existing device factor.
///
/// Parameters are untrusted persisted metadata, not authorization. Implementations must verify
/// factor ownership and backend policy before accessing secrets; no native fallback is implied.
pub trait AuthDeviceFactorSource: Send + Sync {
    /// Provision a factor for an authorized profile. Implementations must verify ownership and
    /// honor configured backend/strictness. Custody independently validates returned metadata.
    /// Failed or interrupted publication may leave an unused factor; implementations must not
    /// destroy or replace existing factors during provisioning.
    ///
    /// # Errors
    /// Returns an error for unsupported provisioning, policy, or backend failure.
    fn provision(
        &self,
        _profile: &ResolvedAuthProfile,
    ) -> Result<AuthProvisionedDeviceFactor, crate::lifecycle::AuthVaultLifecycleError> {
        Err(crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
            "device provisioning unavailable".into(),
        ))
    }
    /// Allocate an identity without performing provisioning effects.
    ///
    /// # Errors
    /// Rejects unsupported recovery. The source must durably prevent operation-ID reuse.
    fn provisioning_identity(
        &self,
        _profile: &ResolvedAuthProfile,
    ) -> Result<(String, String), crate::lifecycle::AuthVaultLifecycleError> {
        Err(crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
            "recoverable provisioning unavailable".into(),
        ))
    }

    /// Provision under a durably recorded identity, idempotently for this exact binding.
    ///
    /// # Errors
    /// Rejects unsupported or conflicting identities without fallback to legacy provisioning.
    fn provision_attempt(
        &self,
        _intent: &AuthProvisioningIntent,
    ) -> Result<AuthProvisionedDeviceFactor, crate::lifecycle::AuthVaultLifecycleError> {
        Err(crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
            "recoverable provisioning unavailable".into(),
        ))
    }

    /// Explicitly reconcile an attempt without deleting or replacing any factor. Success certifies
    /// source/profile ownership, a quiescent operation, and durable retrievability of every factor
    /// that could have been published. An absent operation must be durably fenced against late work.
    ///
    /// # Errors
    /// Ambiguous, foreign, or unsupported attempts remain unresolved.
    fn reconcile_provisioning(
        &self,
        _intent: &AuthProvisioningIntent,
    ) -> Result<(), crate::lifecycle::AuthVaultLifecycleError> {
        Err(crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
            "provisioning reconciliation unavailable".into(),
        ))
    }

    /// Retrieve the key bound to the supplied factor metadata.
    ///
    /// # Errors
    /// Rejects unknown factors, unsupported parameters, or unverifiable device custody.
    fn retrieve(
        &self,
        id: &str,
        recipient_fingerprint: Option<&str>,
        parameters: &std::collections::BTreeMap<String, String>,
    ) -> Result<zeroize::Zeroizing<[u8; 32]>, crate::lifecycle::AuthVaultLifecycleError>;
}

/// Selected source of profile encryption keys for retained custody writes.
///
/// Production implementations must return fresh cryptographically secure keys. Deterministic
/// sources are only appropriate for isolated simulations with no real credentials.
pub trait AuthCustodyKeySource: Send + Sync {
    /// Acquire a fresh encryption key without falling back to another source.
    ///
    /// # Errors
    /// Returns a secret-safe error when key acquisition is unavailable.
    fn generate(
        &self,
    ) -> Result<zeroize::Zeroizing<[u8; 32]>, crate::lifecycle::AuthVaultLifecycleError>;
}

/// Retained encrypted custody for one explicitly bound profile.
///
/// Pools are intentionally unsupported by this single-profile service. Identities are zeroized
/// on release; directory ownership is released with storage. Device factors fail closed and
/// remote-factor limitations remain those of the lifecycle custody reader.
#[cfg(unix)]
pub struct RetainedAuthRequestCustody {
    storage: std::sync::Mutex<Box<dyn crate::custody_storage::AuthCustodyStorage>>,
    resolved: ResolvedAuthProfile,
    method: AuthMethodContribution,
    identities: Vec<zeroize::Zeroizing<String>>,
    passphrase: Option<zeroize::Zeroizing<String>>,
    key_source: Option<std::sync::Arc<dyn AuthCustodyKeySource>>,
    device_source: Option<std::sync::Arc<dyn AuthDeviceFactorSource>>,
    active_refresh: std::sync::Mutex<Option<String>>,
    active_enrollment: std::sync::Mutex<Option<String>>,
}

#[cfg(unix)]
impl RetainedAuthRequestCustody {
    /// Resolve a fenced provisioning attempt after caller authorization for maintenance.
    /// Does not replay credential changes or delete external factors.
    ///
    /// # Errors
    /// Preserves the fence for unsupported intents, mismatched profiles, or failed reconciliation.
    pub fn reconcile_provisioning(&self) -> Result<(), crate::lifecycle::AuthVaultLifecycleError> {
        let failure = || {
            crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
                "provisioning requires maintenance".into(),
            )
        };
        let storage = self.storage.lock().map_err(|_| failure())?;
        let intent = storage.provisioning_intent().map_err(|_| failure())?;
        if intent.profile_binding != provisioning_binding(&self.resolved)? {
            return Err(failure());
        }
        self.device_source
            .as_ref()
            .ok_or_else(failure)?
            .reconcile_provisioning(&intent)
            .map_err(|_| failure())?;
        storage.finish_provisioning().map_err(|_| failure())
    }

    /// Select native operation-scoped macOS custody using this service's validated profile.
    /// No Keychain access occurs until an authorized read, write, or reconciliation request.
    /// Replaces any previously selected device source; no implicit fallback is installed.
    ///
    /// # Errors
    /// Rejects a profile that cannot be encoded for native ownership binding.
    #[cfg(target_os = "macos")]
    pub fn macos_operation_factors(
        self,
    ) -> Result<Self, crate::lifecycle::AuthVaultLifecycleError> {
        let source = crate::native_device::MacosOperationFactorSource::new(self.resolved.clone())?;
        Ok(self.device_source(std::sync::Arc::new(source)))
    }

    /// Select trusted retrieval for existing device factors on credential reads and writes.
    ///
    /// Provisioning remains explicitly source-owned; remote custody is not selected here.
    #[must_use]
    pub fn device_source(mut self, source: std::sync::Arc<dyn AuthDeviceFactorSource>) -> Self {
        self.device_source = Some(source);
        self
    }
    /// Select profile-key acquisition for subsequent writes, with no native fallback.
    ///
    /// The source must meet [`AuthCustodyKeySource`]'s security contract. Other custody effects
    /// are unchanged; selecting this source alone does not establish deterministic execution.
    #[must_use]
    pub fn key_source(mut self, source: std::sync::Arc<dyn AuthCustodyKeySource>) -> Self {
        self.key_source = Some(source);
        self
    }
    /// Bind retained storage and identities to a registered provider/profile owner.
    ///
    /// # Errors
    /// Rejects mismatched provider, plugin, backend, or method ownership.
    pub fn new(
        storage: crate::custody_storage::CredentialCustodyStorage,
        resolved: ResolvedAuthProfile,
        provider_id: &str,
        plugin_id: &str,
        method: AuthMethodContribution,
        identities: Vec<zeroize::Zeroizing<String>>,
        passphrase: Option<zeroize::Zeroizing<String>>,
    ) -> Result<Self, crate::lifecycle::AuthVaultLifecycleError> {
        Self::from_storage(
            Box::new(storage),
            resolved,
            provider_id,
            plugin_id,
            method,
            identities,
            passphrase,
        )
    }

    /// Bind a caller-acquired storage owner without native storage acquisition or fallback.
    ///
    /// The owner must uphold [`crate::custody_storage::AuthCustodyStorage`]'s confinement,
    /// publication, and provisioning-fence contract. Vault policy remains lifecycle-owned.
    ///
    /// # Errors
    /// Rejects mismatched provider, plugin, backend, or method ownership.
    pub fn from_storage(
        storage: Box<dyn crate::custody_storage::AuthCustodyStorage>,
        resolved: ResolvedAuthProfile,
        provider_id: &str,
        plugin_id: &str,
        method: AuthMethodContribution,
        identities: Vec<zeroize::Zeroizing<String>>,
        passphrase: Option<zeroize::Zeroizing<String>>,
    ) -> Result<Self, crate::lifecycle::AuthVaultLifecycleError> {
        AuthVaultLifecycle::new(&resolved, provider_id, plugin_id, &method)?;
        Ok(Self {
            storage: std::sync::Mutex::new(storage),
            resolved,
            method,
            identities,
            passphrase,
            key_source: None,
            device_source: None,
            active_refresh: std::sync::Mutex::new(None),
            active_enrollment: std::sync::Mutex::new(None),
        })
    }
}

#[cfg(unix)]
impl AuthRequestCustody for RetainedAuthRequestCustody {
    fn materialize(
        &self,
        plugin_id: &str,
        context: &bcode_model::ProviderRequestContext,
    ) -> Result<crate::ResolvedProviderAuth, crate::lifecycle::AuthVaultLifecycleError> {
        if plugin_id != self.resolved.owner_plugin_id
            || context.auth_profile.as_deref() != Some(self.resolved.profile_name.as_str())
            || context.auth_pool.is_some()
            || !context.auth_candidates.is_empty()
        {
            return Err(
                crate::lifecycle::AuthVaultLifecycleError::ProfileUnavailable(
                    "request does not match retained credential ownership".into(),
                ),
            );
        }
        let lifecycle = AuthVaultLifecycle::new(
            &self.resolved,
            &self.resolved.provider_id,
            plugin_id,
            &self.method,
        )?;
        let identities = self
            .identities
            .iter()
            .map(|value| value.as_str())
            .collect::<Vec<_>>();
        let storage = self.storage.lock().map_err(|_| {
            crate::lifecycle::AuthVaultLifecycleError::VaultUnavailable(
                "custody owner unavailable".into(),
            )
        })?;
        lifecycle.materialize_from_custody_with_device(
            storage.as_ref(),
            &identities,
            self.passphrase.as_ref().map(|value| value.as_str()),
            self.device_source.as_deref(),
        )
    }
}

#[cfg(unix)]
impl AuthCredentialCustody for RetainedAuthRequestCustody {
    fn begin_refresh(
        &self,
        resolved: &ResolvedAuthProfile,
        request: bcode_provider_auth_models::AuthRefreshBeginRequest,
    ) -> Result<
        bcode_provider_auth_models::AuthRefreshBeginResponse,
        crate::lifecycle::AuthVaultLifecycleError,
    > {
        self.begin_owned_refresh(resolved, &request)
    }

    fn commit_refresh(
        &self,
        resolved: &ResolvedAuthProfile,
        request: bcode_provider_auth_models::AuthRefreshCommitRequest,
    ) -> Result<AuthCredentialUpdateResponse, crate::lifecycle::AuthVaultLifecycleError> {
        self.commit_owned_refresh(resolved, request)
    }

    fn persist(
        &self,
        resolved: &ResolvedAuthProfile,
        changes: std::collections::BTreeMap<String, Option<String>>,
    ) -> Result<
        Vec<crate::security::AuthSecurityDiagnostic>,
        crate::lifecycle::AuthVaultLifecycleError,
    > {
        if resolved.profile_name != self.resolved.profile_name
            || resolved.provider_id != self.resolved.provider_id
            || resolved.owner_plugin_id != self.resolved.owner_plugin_id
            || resolved.profile != self.resolved.profile
        {
            return Err(crate::lifecycle::AuthVaultLifecycleError::InvalidCredential);
        }
        let lifecycle = AuthVaultLifecycle::new(
            &self.resolved,
            &self.resolved.provider_id,
            &self.resolved.owner_plugin_id,
            &self.method,
        )?;
        let identities = self
            .identities
            .iter()
            .map(|value| value.as_str())
            .collect::<Vec<_>>();
        let mut storage = self.storage.lock().map_err(|_| {
            crate::lifecycle::AuthVaultLifecycleError::VaultUnavailable(
                "custody owner unavailable".into(),
            )
        })?;
        lifecycle.persist_to_custody(
            storage.as_mut(),
            &identities,
            self.passphrase.as_ref().map(|value| value.as_str()),
            changes,
            self.key_source.as_deref(),
            self.device_source.as_deref(),
        )
    }
}

/// Host credential-update failure.
#[derive(Debug, thiserror::Error)]
pub enum AuthCredentialUpdateError {
    #[error("invalid credential update request: {0}")]
    InvalidRequest(String),
    #[error(transparent)]
    Ownership(#[from] AuthProfileResolutionError),
    #[error(transparent)]
    Lifecycle(#[from] crate::lifecycle::AuthVaultLifecycleError),
}

/// Persist refreshed credentials through host-owned vault custody.
///
/// The caller cannot provide an owner identity, vault path, storage profile, or backend key.
/// Host-bound ownership and the registered method are validated before vault access.
///
/// # Errors
///
/// Returns an error for invalid payloads, profile mismatch, ownership mismatch, undeclared
/// credentials, damaged vault state, device-seal failure, or write failure.
pub fn update_credentials(
    context: AuthCredentialUpdateContext<'_>,
    request: AuthCredentialUpdateRequest,
) -> Result<AuthCredentialUpdateResponse, AuthCredentialUpdateError> {
    update_credentials_with_custody(context, request, None)
}

/// Update credentials using canonical authorization and optionally selected host custody.
///
/// # Errors
/// Returns payload, ownership, credential-shape, or custody errors before reporting success.
pub fn update_credentials_with_custody(
    context: AuthCredentialUpdateContext<'_>,
    request: AuthCredentialUpdateRequest,
    custody: Option<&dyn AuthCredentialCustody>,
) -> Result<AuthCredentialUpdateResponse, AuthCredentialUpdateError> {
    request
        .validate()
        .map_err(|error| AuthCredentialUpdateError::InvalidRequest(error.to_string()))?;
    if request.provider_id != context.provider_id {
        return Err(AuthCredentialUpdateError::Ownership(
            AuthProfileResolutionError::ProviderMismatch {
                profile: request.profile,
                expected: context.provider_id.to_owned(),
                actual: request.provider_id,
            },
        ));
    }
    if request.profile != context.resolved.profile_name {
        return Err(AuthCredentialUpdateError::Ownership(
            AuthProfileResolutionError::MissingProfile {
                provider_id: context.provider_id.to_owned(),
                profile: request.profile,
            },
        ));
    }
    let mut updated_credentials = request.credentials.keys().cloned().collect::<Vec<_>>();
    updated_credentials.sort();
    let lifecycle = AuthVaultLifecycle::new(
        context.resolved,
        context.provider_id,
        context.caller_plugin_id,
        context.method,
    )?;
    if let Some(custody) = custody {
        lifecycle.update_with(request.credentials, |changes| {
            custody.persist(context.resolved, changes)
        })?;
    } else {
        lifecycle.update(request.credentials)?;
    }
    Ok(AuthCredentialUpdateResponse {
        schema_version: AUTH_CREDENTIAL_UPDATE_SCHEMA_VERSION,
        updated_credentials,
    })
}

/// Registered auth-provider identity bound by the host from its plugin registry.
///
/// The host looks this up by the requested provider ID; the caller cannot supply it.
#[derive(Debug, Clone, Copy)]
pub struct RegisteredAuthProviderOwner<'a> {
    /// Plugin that registered the provider contribution.
    pub plugin_id: &'a str,
    /// Methods the registered contribution declares.
    pub methods: &'a [AuthMethodContribution],
}

/// Host-owned resolution for one `bcode.provider-auth-host` bridge request.
///
/// Both the daemon and the embedded runtime route plugin-initiated
/// [`bcode_provider_auth_models::OP_UPDATE_CREDENTIALS`] requests through this function so the
/// ownership rules stay identical across hosts:
///
/// * The caller plugin must be the plugin that registered the target auth provider.
/// * The requested profile must resolve for that provider and owner.
/// * The resolved profile's scheme must name a method the registration declares.
/// * Vault custody and credential-shape checks are enforced by [`update_credentials`].
///
/// Requests for other interfaces or operations return
/// [`bcode_tool::ToolInvocationServiceResolution::Unsupported`] so hosts can chain resolvers.
#[must_use]
pub fn resolve_credential_update_service_request<'registry>(
    config: &bcode_config::BcodeConfig,
    runtime: &bcode_config::RuntimeAuthSubscriptions,
    caller_plugin_id: &str,
    registered_provider: impl FnOnce(&str) -> Option<RegisteredAuthProviderOwner<'registry>>,
    request: bcode_tool::ToolInvocationServiceRequest,
) -> bcode_tool::ToolInvocationServiceResolution {
    resolve_credential_update_service_request_with_custody(
        config,
        runtime,
        caller_plugin_id,
        registered_provider,
        request,
        None,
    )
}

/// Resolve a plugin credential update with optionally selected trusted host custody.
///
/// Uses the same registry ownership, profile resolution, and credential validation as the
/// native entry point; custody cannot override authorization.
#[must_use]
pub fn resolve_credential_update_service_request_with_custody<'registry>(
    config: &bcode_config::BcodeConfig,
    runtime: &bcode_config::RuntimeAuthSubscriptions,
    caller_plugin_id: &str,
    registered_provider: impl FnOnce(&str) -> Option<RegisteredAuthProviderOwner<'registry>>,
    request: bcode_tool::ToolInvocationServiceRequest,
    custody: Option<&dyn AuthCredentialCustody>,
) -> bcode_tool::ToolInvocationServiceResolution {
    use bcode_provider_auth_models::{AUTH_HOST_INTERFACE_ID, OP_UPDATE_CREDENTIALS};
    use bcode_tool::ToolInvocationServiceResolution as Resolution;

    #[cfg(unix)]
    if request.interface_id == AUTH_HOST_INTERFACE_ID
        && matches!(
            request.operation.as_str(),
            bcode_provider_auth_models::OP_BEGIN_REFRESH
                | bcode_provider_auth_models::OP_COMMIT_REFRESH
        )
    {
        return resolve_refresh_service_request_with_custody(
            config,
            runtime,
            caller_plugin_id,
            registered_provider,
            request,
            custody,
        );
    }
    #[cfg(not(unix))]
    if request.interface_id == AUTH_HOST_INTERFACE_ID
        && matches!(
            request.operation.as_str(),
            bcode_provider_auth_models::OP_BEGIN_REFRESH
                | bcode_provider_auth_models::OP_COMMIT_REFRESH
        )
    {
        return Resolution::Failed {
            code: "auth_refresh_unavailable".into(),
            message: "durable refresh coordination is unavailable on this host".into(),
        };
    }
    if request.interface_id != AUTH_HOST_INTERFACE_ID || request.operation != OP_UPDATE_CREDENTIALS
    {
        return Resolution::Unsupported;
    }
    let Ok(update) = serde_json::from_value::<AuthCredentialUpdateRequest>(request.payload) else {
        return Resolution::Failed {
            code: "invalid_request".to_owned(),
            message: "invalid provider-auth credential update request".to_owned(),
        };
    };
    let provider_id = update.provider_id.clone();
    let Some(registered) = registered_provider(&provider_id) else {
        return Resolution::Failed {
            code: "auth_provider_unregistered".to_owned(),
            message: "authentication provider is not registered".to_owned(),
        };
    };
    if registered.plugin_id != caller_plugin_id {
        return Resolution::Failed {
            code: "auth_owner_mismatch".to_owned(),
            message: "authentication provider is owned by another plugin".to_owned(),
        };
    }
    let resolved = match crate::resolve_auth_provider_profile(
        config,
        &provider_id,
        caller_plugin_id,
        Some(&update.profile),
        runtime,
    ) {
        Ok(resolved) => resolved,
        Err(error) => {
            return credential_update_failure(&AuthCredentialUpdateError::Ownership(error));
        }
    };
    let Some(method) = registered
        .methods
        .iter()
        .find(|method| resolved.profile.scheme.as_deref() == Some(method.method_id()))
    else {
        return Resolution::Failed {
            code: "auth_method_unavailable".to_owned(),
            message: "owned auth profile method is not registered".to_owned(),
        };
    };
    match update_credentials_with_custody(
        AuthCredentialUpdateContext {
            caller_plugin_id,
            provider_id: &provider_id,
            resolved: &resolved,
            method,
        },
        update,
        custody,
    ) {
        Ok(response) => serde_json::to_value(response).map_or_else(
            |_| Resolution::Failed {
                code: "auth_response_encode_failed".to_owned(),
                message: "credential update response could not be encoded".to_owned(),
            },
            |payload| Resolution::Responded { payload },
        ),
        Err(error) => credential_update_failure(&error),
    }
}

fn credential_update_failure(
    error: &AuthCredentialUpdateError,
) -> bcode_tool::ToolInvocationServiceResolution {
    use crate::lifecycle::AuthVaultLifecycleError as Lifecycle;
    let (code, message) = match error {
        AuthCredentialUpdateError::InvalidRequest(_) => {
            ("invalid_request", "invalid credential update request")
        }
        AuthCredentialUpdateError::Ownership(_) => (
            "auth_profile_unavailable",
            "credential update profile is unavailable",
        ),
        AuthCredentialUpdateError::Lifecycle(Lifecycle::VaultUnavailable(_)) => (
            "auth_vault_unavailable",
            "credential custody is unavailable; unlock or reconnect the profile",
        ),
        AuthCredentialUpdateError::Lifecycle(Lifecycle::WriteFailed(_)) => (
            "auth_credential_write_failed",
            "credential custody could not persist the update",
        ),
        AuthCredentialUpdateError::Lifecycle(Lifecycle::DeviceSealRequired(_)) => (
            "auth_device_seal_required",
            "credential custody requires device-seal authorization",
        ),
        AuthCredentialUpdateError::Lifecycle(_) => (
            "auth_credential_update_failed",
            "credential update could not be authorized or persisted",
        ),
    };
    bcode_tool::ToolInvocationServiceResolution::Failed {
        code: code.to_owned(),
        message: message.to_owned(),
    }
}

/// Host security-inspection failure.
#[derive(Debug, thiserror::Error)]
pub enum AuthSecurityInspectionError {
    #[error("invalid security inspection request: {0}")]
    InvalidRequest(String),
    #[error(transparent)]
    Ownership(#[from] AuthProfileResolutionError),
}

/// Inspect security for one already-authorized auth profile.
///
/// The host derives vault location and device-seal policy from `resolved`; callers cannot supply
/// either value.
///
/// # Errors
///
/// Returns an error for invalid payloads, provider/profile mismatch, or plugin ownership mismatch.
pub fn inspect_security(
    caller_plugin_id: &str,
    resolved: &ResolvedAuthProfile,
    request: &AuthSecurityInspectionRequest,
) -> Result<AuthSecurityInspectionResponse, AuthSecurityInspectionError> {
    request
        .validate()
        .map_err(|error| AuthSecurityInspectionError::InvalidRequest(error.to_string()))?;
    validate_resolved_security_owner(caller_plugin_id, resolved, request)?;
    let vault = resolved.profile.settings.get("vault").map_or_else(
        bcode_config::default_auth_vault_path,
        std::path::PathBuf::from,
    );
    let storage_profile = resolved
        .profile
        .settings
        .get("profile")
        .map_or(resolved.profile_name.as_str(), String::as_str);
    let policy = crate::security::device_seal_policy_for_auth_profile(&resolved.profile);
    let status = crate::security::inspect_auth_vault_security(&vault, storage_profile, policy);
    Ok(AuthSecurityInspectionResponse {
        schema_version: AUTH_SECURITY_INSPECTION_SCHEMA_VERSION,
        provider_id: resolved.provider_id.clone(),
        profile: resolved.profile_name.clone(),
        policy: match policy {
            crate::security::AuthDeviceSealPolicy::Off => "off",
            crate::security::AuthDeviceSealPolicy::Preferred => "preferred",
            crate::security::AuthDeviceSealPolicy::Required => "required",
        }
        .to_owned(),
        vault_exists: status.vault_exists,
        profile_keys_enabled: status.profile_keys_enabled,
        profile_exists: status.profile_exists,
        profile_device_sealed: status.profile_device_sealed,
        policy_satisfied: status.policy_satisfied,
        diagnostics: status
            .diagnostics
            .into_iter()
            .map(|diagnostic| AuthDiagnostic {
                message: match diagnostic.code.as_str() {
                    "auth_vault_missing" => "Auth vault does not exist.".to_owned(),
                    "auth_vault_unlock_failed" => {
                        "Auth vault metadata could not be unlocked.".to_owned()
                    }
                    "auth_vault_profile_missing" => "Auth vault profile does not exist.".to_owned(),
                    "auth_vault_device_seal_missing" => {
                        "Auth vault profile is not device-sealed.".to_owned()
                    }
                    _ => "Auth security status requires attention.".to_owned(),
                },
                code: diagnostic.code,
                severity: match diagnostic.severity {
                    crate::security::AuthSecurityDiagnosticSeverity::Info => {
                        AuthDiagnosticSeverity::Info
                    }
                    crate::security::AuthSecurityDiagnosticSeverity::Warning => {
                        AuthDiagnosticSeverity::Warning
                    }
                    crate::security::AuthSecurityDiagnosticSeverity::Error => {
                        AuthDiagnosticSeverity::Error
                    }
                },
                remediation: diagnostic.remediation,
            })
            .collect(),
    })
}

fn validate_resolved_security_owner(
    caller_plugin_id: &str,
    resolved: &ResolvedAuthProfile,
    request: &AuthSecurityInspectionRequest,
) -> Result<(), AuthProfileResolutionError> {
    if request.profile != resolved.profile_name {
        return Err(AuthProfileResolutionError::MissingProfile {
            provider_id: request.provider_id.clone(),
            profile: request.profile.clone(),
        });
    }
    if request.provider_id != resolved.provider_id {
        return Err(AuthProfileResolutionError::ProviderMismatch {
            profile: resolved.profile_name.clone(),
            expected: resolved.provider_id.clone(),
            actual: request.provider_id.clone(),
        });
    }
    if caller_plugin_id != resolved.owner_plugin_id {
        return Err(AuthProfileResolutionError::OwnerMismatch {
            profile: resolved.profile_name.clone(),
            expected: resolved.owner_plugin_id.clone(),
            actual: caller_plugin_id.to_owned(),
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    #[test]
    fn credential_update_boundary_redacts_custody_errors() {
        use super::{AuthCredentialUpdateError, credential_update_failure};
        use crate::lifecycle::AuthVaultLifecycleError;
        for (error, expected) in [
            (
                AuthVaultLifecycleError::VaultUnavailable("private-token".into()),
                "auth_vault_unavailable",
            ),
            (
                AuthVaultLifecycleError::WriteFailed("private-token".into()),
                "auth_credential_write_failed",
            ),
            (
                AuthVaultLifecycleError::ProfileUnavailable("private-token".into()),
                "auth_credential_update_failed",
            ),
        ] {
            let bcode_tool::ToolInvocationServiceResolution::Failed { code, message } =
                credential_update_failure(&AuthCredentialUpdateError::Lifecycle(error))
            else {
                panic!("failure expected")
            };
            assert_eq!(code, expected);
            assert!(!message.contains("private-token"));
        }
    }

    use super::*;
    use bcode_provider_auth_models::{AuthCredentialStorage, AuthMethodContribution};
    use std::collections::BTreeMap;

    fn method() -> AuthMethodContribution {
        AuthMethodContribution::Interactive {
            method_id: "chatgpt".to_owned(),
            display_name: "ChatGPT".to_owned(),
            operation: "flow".to_owned(),
            credentials: [
                ("access_token", "ACCESS_TOKEN"),
                ("refresh_token", "REFRESH_TOKEN"),
                ("expires_at", "EXPIRES_AT"),
                ("id_token", "ID_TOKEN"),
                ("account_id", "ACCOUNT_ID"),
            ]
            .into_iter()
            .map(|(credential_id, storage_key)| AuthCredentialStorage {
                credential_id: credential_id.to_owned(),
                storage_key: storage_key.to_owned(),
            })
            .collect(),
            supports_revocation: false,
        }
    }

    fn resolved(vault: &std::path::Path) -> ResolvedAuthProfile {
        ResolvedAuthProfile {
            profile_name: "openai".to_owned(),
            provider_id: "openai".to_owned(),
            owner_plugin_id: "bcode.openai-compatible".to_owned(),
            profile: bcode_config::AuthProfileConfig {
                backend: "sshenv".to_owned(),
                provider_id: Some("openai".to_owned()),
                owner_plugin_id: Some("bcode.openai-compatible".to_owned()),
                scheme: Some("chatgpt".to_owned()),
                map: [
                    ("access_token", "ACCESS_TOKEN"),
                    ("refresh_token", "REFRESH_TOKEN"),
                    ("expires_at", "EXPIRES_AT"),
                    ("id_token", "ID_TOKEN"),
                    ("account_id", "ACCOUNT_ID"),
                ]
                .into_iter()
                .map(|(credential, key)| {
                    (
                        credential.to_owned(),
                        bcode_config::AuthCredentialMapping {
                            env: None,
                            key: Some(key.to_owned()),
                        },
                    )
                })
                .collect(),
                settings: BTreeMap::from([
                    ("profile".to_owned(), "openai".to_owned()),
                    ("vault".to_owned(), vault.display().to_string()),
                    ("device_seal".to_owned(), "off".to_owned()),
                ]),
            },
            source: crate::AuthProfileSource::Declarative,
        }
    }

    #[test]
    fn semantic_security_inspection_derives_vault_and_denies_other_owner() {
        let temp = tempfile::tempdir().expect("tempdir");
        let vault = temp.path().join("missing-vault");
        let mut resolved = resolved(&vault);
        resolved
            .profile
            .settings
            .insert("device_seal".to_owned(), "required".to_owned());
        let request = AuthSecurityInspectionRequest {
            schema_version: AUTH_SECURITY_INSPECTION_SCHEMA_VERSION,
            provider_id: "openai".to_owned(),
            profile: "openai".to_owned(),
        };
        let response = inspect_security("bcode.openai-compatible", &resolved, &request)
            .expect("owned inspection");
        assert_eq!(response.provider_id, "openai");
        assert_eq!(response.profile, "openai");
        assert_eq!(response.policy, "required");
        assert!(!response.vault_exists);
        assert!(!response.policy_satisfied);
        let encoded = serde_json::to_string(&response).expect("response");
        assert!(!encoded.contains(vault.to_string_lossy().as_ref()));

        assert!(matches!(
            inspect_security("bcode.other", &resolved, &request),
            Err(AuthSecurityInspectionError::Ownership(
                AuthProfileResolutionError::OwnerMismatch { .. }
            ))
        ));
        assert!(!vault.exists());
    }

    #[test]
    fn selected_custody_cannot_bypass_owner_or_credential_validation() {
        struct UnavailableCustody(std::sync::atomic::AtomicUsize);
        impl AuthCredentialCustody for UnavailableCustody {
            fn persist(
                &self,
                resolved: &ResolvedAuthProfile,
                changes: BTreeMap<String, Option<String>>,
            ) -> Result<
                Vec<crate::security::AuthSecurityDiagnostic>,
                crate::lifecycle::AuthVaultLifecycleError,
            > {
                self.0.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                assert_eq!(resolved.profile_name, "openai");
                assert_eq!(changes.len(), 1);
                Err(crate::lifecycle::AuthVaultLifecycleError::WriteFailed(
                    "custody unavailable".into(),
                ))
            }
        }
        let temp = tempfile::tempdir().unwrap();
        let vault = temp.path().join("unused");
        let resolved = resolved(&vault);
        let method = method();
        let custody = UnavailableCustody(std::sync::atomic::AtomicUsize::new(0));
        for (owner, credential) in [
            ("other", "access_token"),
            ("bcode.openai-compatible", "unknown"),
            ("bcode.openai-compatible", "access_token"),
        ] {
            let result = update_credentials_with_custody(
                AuthCredentialUpdateContext {
                    caller_plugin_id: owner,
                    provider_id: "openai",
                    resolved: &resolved,
                    method: &method,
                },
                AuthCredentialUpdateRequest {
                    schema_version: AUTH_CREDENTIAL_UPDATE_SCHEMA_VERSION,
                    provider_id: "openai".into(),
                    profile: "openai".into(),
                    credentials: BTreeMap::from([(credential.into(), Some("value".into()))]),
                },
                Some(&custody),
            );
            assert!(result.is_err());
        }
        assert_eq!(custody.0.load(std::sync::atomic::Ordering::Relaxed), 1);
        assert!(!vault.exists());
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    #[cfg(not(feature = "custody-simulation"))]
    fn update_is_owner_bound_and_rejects_undeclared_credentials_before_mutation() {
        let temp = tempfile::tempdir().expect("tempdir");
        let vault = temp.path().join("vault");
        let owned_resolved = resolved(&vault);
        let method = method();
        let context = AuthCredentialUpdateContext {
            caller_plugin_id: "bcode.openai-compatible",
            provider_id: "openai",
            resolved: &owned_resolved,
            method: &method,
        };
        let response = update_credentials(
            context,
            AuthCredentialUpdateRequest {
                schema_version: AUTH_CREDENTIAL_UPDATE_SCHEMA_VERSION,
                provider_id: "openai".to_owned(),
                profile: "openai".to_owned(),
                credentials: BTreeMap::from([
                    ("access_token".to_owned(), Some("access".to_owned())),
                    ("refresh_token".to_owned(), Some("refresh".to_owned())),
                    ("expires_at".to_owned(), Some("123".to_owned())),
                ]),
            },
        )
        .expect("owned update");
        assert_eq!(
            response.updated_credentials,
            vec!["access_token", "expires_at", "refresh_token"]
        );
        let encoded = serde_json::to_string(&response).expect("response");
        assert!(!encoded.contains("\"access\""));
        assert!(!encoded.contains("\"refresh\""));
        assert!(!encoded.contains("\"123\""));

        let response = update_credentials(
            AuthCredentialUpdateContext {
                caller_plugin_id: "bcode.openai-compatible",
                provider_id: "openai",
                resolved: &owned_resolved,
                method: &method,
            },
            AuthCredentialUpdateRequest {
                schema_version: AUTH_CREDENTIAL_UPDATE_SCHEMA_VERSION,
                provider_id: "openai".to_owned(),
                profile: "openai".to_owned(),
                credentials: BTreeMap::from([
                    ("access_token".to_owned(), Some("next-access".to_owned())),
                    ("id_token".to_owned(), None),
                    ("account_id".to_owned(), None),
                ]),
            },
        )
        .expect("atomic replacement and removal");
        assert_eq!(
            response.updated_credentials,
            vec!["access_token", "account_id", "id_token"]
        );
        let values = AuthVaultLifecycle::new(
            &owned_resolved,
            "openai",
            "bcode.openai-compatible",
            &method,
        )
        .expect("lifecycle")
        .read()
        .expect("read updated credentials");
        assert_eq!(
            values.get("access_token").map(String::as_str),
            Some("next-access")
        );
        assert!(!values.contains_key("id_token"));
        assert!(!values.contains_key("account_id"));
        let rematerialized = crate::resolve_auth_profile("openai", &owned_resolved.profile);
        assert_eq!(
            rematerialized
                .auth
                .credentials
                .get("access_token")
                .map(|credential| credential.value.as_str()),
            Some("next-access")
        );
        assert!(!rematerialized.auth.credentials.contains_key("id_token"));
        assert!(!rematerialized.auth.credentials.contains_key("account_id"));

        let invalid_vault = temp.path().join("must-not-exist");
        let invalid_resolved = resolved(&invalid_vault);
        assert!(
            update_credentials(
                AuthCredentialUpdateContext {
                    caller_plugin_id: "bcode.other",
                    provider_id: "openai",
                    resolved: &invalid_resolved,
                    method: &method,
                },
                AuthCredentialUpdateRequest {
                    schema_version: AUTH_CREDENTIAL_UPDATE_SCHEMA_VERSION,
                    provider_id: "openai".to_owned(),
                    profile: "openai".to_owned(),
                    credentials: BTreeMap::from([(
                        "access_token".to_owned(),
                        Some("secret".to_owned()),
                    )]),
                },
            )
            .is_err()
        );
        assert!(!invalid_vault.exists());

        let mismatched_vault = temp.path().join("provider-mismatch-must-not-exist");
        let mismatched_resolved = resolved(&mismatched_vault);
        assert!(matches!(
            update_credentials(
                AuthCredentialUpdateContext {
                    caller_plugin_id: "bcode.openai-compatible",
                    provider_id: "openai",
                    resolved: &mismatched_resolved,
                    method: &method,
                },
                AuthCredentialUpdateRequest {
                    schema_version: AUTH_CREDENTIAL_UPDATE_SCHEMA_VERSION,
                    provider_id: "xai".to_owned(),
                    profile: "openai".to_owned(),
                    credentials: BTreeMap::from([(
                        "access_token".to_owned(),
                        Some("secret".to_owned()),
                    )]),
                },
            ),
            Err(AuthCredentialUpdateError::Ownership(
                AuthProfileResolutionError::ProviderMismatch { .. }
            ))
        ));
        assert!(!mismatched_vault.exists());

        assert!(
            update_credentials(
                AuthCredentialUpdateContext {
                    caller_plugin_id: "bcode.openai-compatible",
                    provider_id: "openai",
                    resolved: &invalid_resolved,
                    method: &method,
                },
                AuthCredentialUpdateRequest {
                    schema_version: AUTH_CREDENTIAL_UPDATE_SCHEMA_VERSION,
                    provider_id: "openai".to_owned(),
                    profile: "openai".to_owned(),
                    credentials: BTreeMap::from([("other".to_owned(), Some("secret".to_owned()))]),
                },
            )
            .is_err()
        );
        assert!(!invalid_vault.exists());
    }

    fn update_service_request(
        provider_id: &str,
        profile: &str,
        access_token: &str,
    ) -> bcode_tool::ToolInvocationServiceRequest {
        bcode_tool::ToolInvocationServiceRequest {
            invocation_id: "turn-1".to_owned(),
            request_id: "turn-1-credential-refresh".to_owned(),
            route_id: None,
            interface_id: bcode_provider_auth_models::AUTH_HOST_INTERFACE_ID.to_owned(),
            operation: bcode_provider_auth_models::OP_UPDATE_CREDENTIALS.to_owned(),
            payload: serde_json::to_value(AuthCredentialUpdateRequest {
                schema_version: AUTH_CREDENTIAL_UPDATE_SCHEMA_VERSION,
                provider_id: provider_id.to_owned(),
                profile: profile.to_owned(),
                credentials: BTreeMap::from([
                    ("access_token".to_owned(), Some(access_token.to_owned())),
                    (
                        "refresh_token".to_owned(),
                        Some("rotated-refresh".to_owned()),
                    ),
                    ("expires_at".to_owned(), Some("4102444800".to_owned())),
                    ("id_token".to_owned(), None),
                    ("account_id".to_owned(), None),
                ]),
            })
            .expect("update payload"),
        }
    }

    #[test]
    fn credential_update_service_redacts_unresolved_profile() {
        let methods = [method()];
        let result = resolve_credential_update_service_request(
            &bcode_config::BcodeConfig::default(),
            &bcode_config::RuntimeAuthSubscriptions::default(),
            "owner",
            |_| {
                Some(RegisteredAuthProviderOwner {
                    plugin_id: "owner",
                    methods: &methods,
                })
            },
            update_service_request("openai", "private-profile-marker", "private-token-marker"),
        );
        let bcode_tool::ToolInvocationServiceResolution::Failed { code, message } = result else {
            panic!("unresolved profile must fail before custody");
        };
        assert_eq!(code, "auth_profile_unavailable");
        assert_eq!(message, "credential update profile is unavailable");
    }

    #[cfg(not(feature = "custody-simulation"))]
    fn failed_code(resolution: &bcode_tool::ToolInvocationServiceResolution) -> &str {
        match resolution {
            bcode_tool::ToolInvocationServiceResolution::Failed { code, .. } => code,
            other => panic!("expected failed resolution, got {other:?}"),
        }
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    #[cfg(not(feature = "custody-simulation"))]
    fn credential_update_service_request_binds_registry_ownership_and_persists_to_vault() {
        let temp = tempfile::tempdir().expect("tempdir");
        let vault = temp.path().join("vault");
        let resolved = resolved(&vault);
        let method = method();
        let methods = vec![method.clone()];
        let config = bcode_config::BcodeConfig {
            auth: bcode_config::AuthConfig {
                profiles: BTreeMap::from([("openai".to_owned(), resolved.profile.clone())]),
                ..bcode_config::AuthConfig::default()
            },
            ..bcode_config::BcodeConfig::default()
        };
        let runtime = bcode_config::RuntimeAuthSubscriptions::default();
        let registry = |plugin_id: &'static str| {
            let registered = BTreeMap::from([(
                resolved.provider_id.clone(),
                RegisteredAuthProviderOwner {
                    plugin_id,
                    methods: &methods,
                },
            )]);
            move |provider_id: &str| registered.get(provider_id).copied()
        };

        // Foreign interface/operation: hosts must be able to chain resolvers.
        let mut unrelated = update_service_request("openai", "openai", "ignored");
        unrelated.operation = "inspect_security".to_owned();
        assert!(matches!(
            resolve_credential_update_service_request(
                &config,
                &runtime,
                "bcode.openai-compatible",
                registry("bcode.openai-compatible"),
                unrelated,
            ),
            bcode_tool::ToolInvocationServiceResolution::Unsupported
        ));

        // Unregistered provider IDs fail before any profile lookup.
        assert_eq!(
            failed_code(&resolve_credential_update_service_request(
                &config,
                &runtime,
                "bcode.openai-compatible",
                registry("bcode.openai-compatible"),
                update_service_request("xai", "openai", "leak"),
            )),
            "auth_provider_unregistered"
        );

        // The caller must be the plugin that registered the provider.
        assert_eq!(
            failed_code(&resolve_credential_update_service_request(
                &config,
                &runtime,
                "bcode.other",
                registry("bcode.openai-compatible"),
                update_service_request("openai", "openai", "leak"),
            )),
            "auth_owner_mismatch"
        );

        // The profile must resolve for the provider and owner.
        assert_eq!(
            failed_code(&resolve_credential_update_service_request(
                &config,
                &runtime,
                "bcode.openai-compatible",
                registry("bcode.openai-compatible"),
                update_service_request("openai", "missing-profile", "leak"),
            )),
            "auth_profile_unavailable"
        );

        // The resolved profile scheme must name a registered method.
        let api_key_only = vec![AuthMethodContribution::SecretFields {
            method_id: "api_key".to_owned(),
            display_name: "API key".to_owned(),
            fields: Vec::new(),
            supports_verification: false,
            supports_revocation: false,
        }];
        assert_eq!(
            failed_code(&resolve_credential_update_service_request(
                &config,
                &runtime,
                "bcode.openai-compatible",
                |_: &str| Some(RegisteredAuthProviderOwner {
                    plugin_id: "bcode.openai-compatible",
                    methods: &api_key_only,
                }),
                update_service_request("openai", "openai", "leak"),
            )),
            "auth_method_unavailable"
        );
        assert!(
            !vault.exists(),
            "rejected requests must not touch the vault"
        );

        // Owned, well-formed request persists through host custody.
        let resolution = resolve_credential_update_service_request(
            &config,
            &runtime,
            "bcode.openai-compatible",
            registry("bcode.openai-compatible"),
            update_service_request("openai", "openai", "fresh-access"),
        );
        let bcode_tool::ToolInvocationServiceResolution::Responded { payload } = resolution else {
            panic!("expected responded resolution, got {resolution:?}");
        };
        let response: AuthCredentialUpdateResponse =
            serde_json::from_value(payload).expect("update response");
        assert_eq!(
            response.updated_credentials,
            vec![
                "access_token",
                "account_id",
                "expires_at",
                "id_token",
                "refresh_token",
            ]
        );
        let stored =
            AuthVaultLifecycle::new(&resolved, "openai", "bcode.openai-compatible", &method)
                .expect("owned lifecycle")
                .read()
                .expect("read vault");
        assert_eq!(
            stored.get("access_token").map(String::as_str),
            Some("fresh-access")
        );
        assert_eq!(
            stored.get("refresh_token").map(String::as_str),
            Some("rotated-refresh")
        );
        assert_eq!(
            stored.get("expires_at").map(String::as_str),
            Some("4102444800")
        );
        assert!(!stored.contains_key("id_token"));
    }
}