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
//! Renderer-independent preparation and publication of owned enrollment profiles.
//!
//! Preparation is read-only. Credential custody and interactive provider effects
//! are separate operations; callers publish metadata only after successful enrollment.

mod pooling;
pub use pooling::{
    EnrollmentPlan, EnrollmentResult, PoolEnrollment, complete, complete_with_config, plan,
};

use crate::{AuthProfileResolutionError, AuthProfileSource, ResolvedAuthProfile};
use bcode_config::{
    AuthCredentialMapping, AuthProfileConfig, BcodeConfig, RuntimeAuthSubscriptions,
};
use bcode_provider_auth_models::{AuthMethodContribution, AuthProviderContribution};
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;

/// Explicit enrollment destination, resolved after frontend review.
#[derive(Debug, Clone, Default)]
pub struct EnrollmentDestination {
    /// Profile already selected through the shared authentication resolution path.
    pub profile: Option<String>,
    /// Explicit vault override.
    pub vault: Option<PathBuf>,
    /// Optional SSH recipient public key.
    pub recipient_key: Option<String>,
}

/// Prepared profile and whether successful enrollment requires publishing metadata.
pub struct PreparedEnrollment {
    /// Ownership-checked profile, containing only credential references.
    pub resolved: ResolvedAuthProfile,
    /// Whether this operation created a new profile blueprint.
    pub publish_runtime: bool,
}

/// Enrollment preparation failure. No secret values are included.
#[derive(Debug, thiserror::Error)]
pub enum EnrollmentError {
    /// Registration or requested method is inconsistent.
    #[error("Authentication registration or method is invalid")]
    InvalidMethod,
    /// Pool ownership, membership or intent is inconsistent or ambiguous.
    #[error("Authentication pool is ambiguous or incompatible; existing metadata preserved")]
    PoolConflict,
    /// New context accounts require a declared destination until context registration is available.
    #[error(
        "Declare this context's authentication profile before enrollment; unscoped account creation is not permitted"
    )]
    ContextProfileRequired,
    /// Reusing a profile cannot silently change its credential destination.
    #[error(
        "Existing account uses a different vault; choose a new profile or explicitly migrate the account"
    )]
    DestinationConflict,
    /// Existing profile ownership cannot be established.
    #[error(transparent)]
    Profile(#[from] AuthProfileResolutionError),
}

/// Prepare an owned profile without creating files, reading secrets, or prompting.
///
/// # Errors
/// Returns an error for invalid registration/method or incompatible existing profile ownership.
pub fn prepare(
    config: &BcodeConfig,
    runtime: &RuntimeAuthSubscriptions,
    provider: &AuthProviderContribution,
    owner_plugin_id: &str,
    method_id: &str,
    destination: EnrollmentDestination,
) -> Result<PreparedEnrollment, EnrollmentError> {
    provider
        .validate()
        .map_err(|_| EnrollmentError::InvalidMethod)?;
    let method = provider
        .methods
        .iter()
        .find(|method| method.method_id() == method_id)
        .ok_or(EnrollmentError::InvalidMethod)?;
    let EnrollmentDestination {
        profile,
        vault,
        recipient_key,
    } = destination;
    match crate::resolve_auth_provider_profile(
        config,
        &provider.provider_id,
        owner_plugin_id,
        profile.as_deref(),
        runtime,
    ) {
        Ok(mut resolved) => {
            crate::lifecycle::AuthVaultLifecycle::new(
                &resolved,
                &provider.provider_id,
                owner_plugin_id,
                method,
            )
            .map_err(|_| EnrollmentError::InvalidMethod)?;
            if let Some(vault) = vault {
                let existing_vault = resolved
                    .profile
                    .settings
                    .get("vault")
                    .map_or_else(bcode_config::default_auth_vault_path, PathBuf::from);
                if vault != existing_vault {
                    return Err(EnrollmentError::DestinationConflict);
                }
                resolved
                    .profile
                    .settings
                    .insert("vault".to_owned(), vault.display().to_string());
            }
            if let Some(recipient) = recipient_key {
                resolved
                    .profile
                    .settings
                    .insert("recipient_key".to_owned(), recipient);
            }
            Ok(PreparedEnrollment {
                resolved,
                publish_runtime: false,
            })
        }
        Err(AuthProfileResolutionError::MissingProfile { .. }) => {
            if config.active_context.is_some() {
                return Err(EnrollmentError::ContextProfileRequired);
            }
            let name = profile.unwrap_or_else(|| provider.provider_id.clone());
            validate_enrollment_binding(runtime, &provider.provider_id, owner_plugin_id, &name)?;
            let vault = vault.unwrap_or_else(bcode_config::default_auth_vault_path);
            let mut settings = BTreeMap::from([
                ("profile".to_owned(), name.clone()),
                ("vault".to_owned(), vault.display().to_string()),
            ]);
            if let Some(recipient) = recipient_key {
                settings.insert("recipient_key".to_owned(), recipient);
            }
            let map = match method {
                AuthMethodContribution::SecretFields { fields, .. } => fields
                    .iter()
                    .map(|field| (field.credential_id.clone(), mapping(&field.storage_key)))
                    .collect(),
                AuthMethodContribution::Interactive { credentials, .. } => credentials
                    .iter()
                    .map(|field| (field.credential_id.clone(), mapping(&field.storage_key)))
                    .collect(),
            };
            Ok(PreparedEnrollment {
                resolved: ResolvedAuthProfile {
                    profile_name: name,
                    provider_id: provider.provider_id.clone(),
                    owner_plugin_id: owner_plugin_id.to_owned(),
                    profile: AuthProfileConfig {
                        backend: "sshenv".to_owned(),
                        provider_id: Some(provider.provider_id.clone()),
                        owner_plugin_id: Some(owner_plugin_id.to_owned()),
                        scheme: Some(method_id.to_owned()),
                        map,
                        settings,
                    },
                    source: AuthProfileSource::Runtime,
                },
                publish_runtime: true,
            })
        }
        Err(error) => Err(error.into()),
    }
}

fn validate_enrollment_binding(
    runtime: &RuntimeAuthSubscriptions,
    provider_id: &str,
    owner: &str,
    name: &str,
) -> Result<(), EnrollmentError> {
    if let Some(binding) = runtime.bindings.get(provider_id)
        && binding.owner_plugin_id != owner
    {
        return Err(AuthProfileResolutionError::OwnerMismatch {
            profile: name.to_owned(),
            expected: owner.to_owned(),
            actual: binding.owner_plugin_id.clone(),
        }
        .into());
    }
    Ok(())
}

/// Plan an explicit context account declaration using the registered provider method.
/// No provider calls, vault reads, credential writes, or binding changes occur.
///
/// # Errors
/// Returns an error for invalid provider/method ownership or conflicting configuration.
pub fn plan_context_account(
    path: PathBuf,
    context: &str,
    local: &str,
    provider: &AuthProviderContribution,
    owner: &str,
    method: &str,
    vault: PathBuf,
) -> Result<bcode_config::edit::ConfigEdit, String> {
    let prepared = prepare(
        &BcodeConfig::default(),
        &RuntimeAuthSubscriptions::default(),
        provider,
        owner,
        method,
        EnrollmentDestination {
            profile: Some(local.to_owned()),
            vault: Some(vault),
            recipient_key: None,
        },
    )
    .map_err(|error| error.to_string())?;
    let mut profile = prepared.resolved.profile;
    profile.settings.remove("profile");
    bcode_config::edit::plan_context_auth_profile(path, context, local, &profile)
        .map_err(|error| error.to_string())
}

/// Allocate a default name for a new account without reusing existing metadata.
/// Selection is advisory: enrollment must still verify ownership at commit time.
#[must_use]
pub fn new_profile_name(
    config: &BcodeConfig,
    runtime: &RuntimeAuthSubscriptions,
    provider_id: &str,
) -> String {
    if let Some(context) = config.active_context.as_deref()
        && let Some(definition) = config
            .contexts
            .as_ref()
            .and_then(|contexts| contexts.entries.get(context))
    {
        let local_config = BcodeConfig {
            auth: definition.auth.clone(),
            ..BcodeConfig::default()
        };
        return new_profile_name(
            &local_config,
            &RuntimeAuthSubscriptions::default(),
            provider_id,
        );
    }
    let mut occupied: BTreeSet<&str> = config
        .auth
        .profiles
        .keys()
        .map(String::as_str)
        .chain(runtime.profiles.keys().map(String::as_str))
        .collect();
    occupied.extend(
        config
            .auth
            .bindings
            .values()
            .filter_map(|binding| binding.profile.as_deref()),
    );
    occupied.extend(
        runtime
            .bindings
            .values()
            .map(|binding| binding.profile.as_str()),
    );
    occupied.extend(
        config
            .auth
            .pools
            .values()
            .flat_map(|pool| pool.profiles.iter().map(String::as_str)),
    );
    occupied.extend(runtime.pools.values().flat_map(|pool| {
        pool.profiles
            .iter()
            .map(|profile| profile.auth_profile.as_str())
    }));
    if !occupied.contains(provider_id) {
        return provider_id.to_owned();
    }
    for index in 2_u64.. {
        let candidate = format!("{provider_id}-{index}");
        if !occupied.contains(candidate.as_str()) {
            return candidate;
        }
    }
    unreachable!("profile name space exhausted")
}

fn mapping(key: &str) -> AuthCredentialMapping {
    AuthCredentialMapping {
        env: None,
        key: Some(key.to_owned()),
    }
}

/// Publish the non-secret runtime profile after credential enrollment succeeds.
///
/// # Errors
/// Returns an error for invalid ownership metadata or persistence failures.
pub fn publish(resolved: &ResolvedAuthProfile) -> Result<(), bcode_config::ConfigError> {
    bcode_config::register_runtime_auth_profile(
        &resolved.profile_name,
        bcode_config::RuntimeAuthProfile {
            provider_id: resolved.provider_id.clone(),
            owner_plugin_id: resolved.owner_plugin_id.clone(),
            backend: resolved.profile.backend.clone(),
            scheme: resolved.profile.scheme.clone().unwrap_or_default(),
            storage_profile: resolved
                .profile
                .settings
                .get("profile")
                .cloned()
                .unwrap_or_else(|| resolved.profile_name.clone()),
            vault: resolved
                .profile
                .settings
                .get("vault")
                .map_or_else(bcode_config::default_auth_vault_path, PathBuf::from),
            map: resolved.profile.map.clone(),
            device_seal: resolved.profile.settings.get("device_seal").cloned(),
        },
    )?;
    Ok(())
}

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

    #[test]
    fn context_enrollment_declaration_resolves_local_name_without_global_binding() {
        let temp = tempfile::tempdir().unwrap();
        let path = temp.path().join("bcode.toml");
        std::fs::write(
            &path,
            "[contexts]\nactive = 'alpha'\n[contexts.entries.alpha]\n[contexts.entries.beta]\n",
        )
        .unwrap();
        let provider = AuthProviderContribution {
            schema_version: bcode_provider_auth_models::AUTH_PROVIDER_CONTRIBUTION_SCHEMA_VERSION,
            provider_id: "example".to_owned(),
            display_name: "Example".to_owned(),
            methods: vec![AuthMethodContribution::Interactive {
                method_id: "browser".to_owned(),
                display_name: "Browser".to_owned(),
                operation: "auth.browser".to_owned(),
                credentials: Vec::new(),
                supports_revocation: false,
            }],
        };
        let vault = temp.path().join("vault");
        let edit = plan_context_account(
            path.clone(),
            "alpha",
            "example",
            &provider,
            "example.plugin",
            "browser",
            vault.clone(),
        )
        .unwrap();
        assert!(!vault.exists());
        edit.apply().unwrap();
        let config = bcode_config::load_config_from_paths(std::slice::from_ref(&path)).unwrap();
        assert_eq!(
            new_profile_name(&config, &RuntimeAuthSubscriptions::default(), "example"),
            "example-2"
        );
        let prepared = prepare(
            &config,
            &RuntimeAuthSubscriptions::default(),
            &provider,
            "example.plugin",
            "browser",
            EnrollmentDestination {
                profile: Some("example".to_owned()),
                vault: Some(vault.clone()),
                recipient_key: None,
            },
        )
        .unwrap();
        let identity = bcode_config::contexts::qualify("alpha", "example").unwrap();
        assert_eq!(prepared.resolved.profile_name, identity);
        assert_eq!(prepared.resolved.profile.settings["profile"], identity);
        assert!(!prepared.publish_runtime);
        assert!(!vault.exists());
        let beta = bcode_config::load_config_from_paths_with_overrides(
            &[path],
            &bcode_config::ConfigLoadOverrides::default()
                .with_cli_config_toml(Some("[contexts]\nactive = 'beta'".to_owned())),
        )
        .unwrap();
        assert_eq!(
            new_profile_name(&beta, &RuntimeAuthSubscriptions::default(), "example"),
            "example"
        );
        assert!(
            prepare(
                &beta,
                &RuntimeAuthSubscriptions::default(),
                &provider,
                "example.plugin",
                "browser",
                EnrollmentDestination {
                    profile: Some("example".to_owned()),
                    ..Default::default()
                }
            )
            .is_err()
        );
    }

    #[test]
    fn new_account_names_do_not_reuse_pool_members_or_dangling_bindings() {
        let mut config = BcodeConfig::default();
        let mut runtime = RuntimeAuthSubscriptions::default();
        assert_eq!(new_profile_name(&config, &runtime, "custom"), "custom");
        config.auth.bindings.insert(
            "provider".to_owned(),
            bcode_config::AuthBindingConfig {
                profile: Some("custom".to_owned()),
            },
        );
        runtime.bindings.insert(
            "provider".to_owned(),
            bcode_config::RuntimeAuthBinding {
                profile: "custom-2".to_owned(),
                owner_plugin_id: "example.plugin".to_owned(),
            },
        );
        config.auth.pools.insert(
            "declared".to_owned(),
            bcode_config::AuthPoolConfig {
                profiles: vec!["custom-3".to_owned()],
                ..Default::default()
            },
        );
        runtime.pools.insert(
            "runtime".to_owned(),
            bcode_config::RuntimeAuthSubscriptionPool {
                profiles: vec![bcode_config::RuntimeAuthSubscriptionProfile {
                    auth_profile: "custom-4".to_owned(),
                    ..Default::default()
                }],
                ..Default::default()
            },
        );
        assert_eq!(new_profile_name(&config, &runtime, "custom"), "custom-5");
        assert_eq!(runtime.profiles.len(), 0);
        assert!(config.auth.profiles.is_empty());
    }

    #[test]
    fn existing_account_method_is_checked_before_interactive_effects() {
        let provider = AuthProviderContribution {
            schema_version: bcode_provider_auth_models::AUTH_PROVIDER_CONTRIBUTION_SCHEMA_VERSION,
            provider_id: "example".to_owned(),
            display_name: "Example".to_owned(),
            methods: vec![AuthMethodContribution::Interactive {
                method_id: "browser".to_owned(),
                display_name: "Browser".to_owned(),
                operation: "auth.browser".to_owned(),
                credentials: Vec::new(),
                supports_revocation: false,
            }],
        };
        let mut config = BcodeConfig::default();
        config.auth.profiles.insert(
            "account".to_owned(),
            AuthProfileConfig {
                backend: "sshenv".to_owned(),
                provider_id: Some("example".to_owned()),
                owner_plugin_id: Some("bcode.example".to_owned()),
                scheme: Some("different-method".to_owned()),
                map: BTreeMap::new(),
                settings: BTreeMap::new(),
            },
        );
        let destination = EnrollmentDestination {
            profile: Some("account".to_owned()),
            ..EnrollmentDestination::default()
        };
        assert!(matches!(
            prepare(
                &config,
                &RuntimeAuthSubscriptions::default(),
                &provider,
                "bcode.example",
                "browser",
                destination.clone(),
            ),
            Err(EnrollmentError::InvalidMethod)
        ));
        config.auth.profiles.get_mut("account").unwrap().scheme = Some("browser".to_owned());
        let prepared = prepare(
            &config,
            &RuntimeAuthSubscriptions::default(),
            &provider,
            "bcode.example",
            "browser",
            destination,
        )
        .expect("matching owned method");
        assert!(!prepared.publish_runtime);
        let conflict = prepare(
            &config,
            &RuntimeAuthSubscriptions::default(),
            &provider,
            "bcode.example",
            "browser",
            EnrollmentDestination {
                profile: Some("account".to_owned()),
                vault: Some(PathBuf::from("different-vault")),
                recipient_key: None,
            },
        );
        assert!(matches!(
            conflict,
            Err(EnrollmentError::DestinationConflict)
        ));
        let runtime = RuntimeAuthSubscriptions {
            bindings: BTreeMap::from([(
                "example".to_owned(),
                bcode_config::RuntimeAuthBinding {
                    profile: "foreign-account".to_owned(),
                    owner_plugin_id: "foreign.plugin".to_owned(),
                },
            )]),
            ..Default::default()
        };
        assert!(
            prepare(
                &config,
                &runtime,
                &provider,
                "bcode.example",
                "browser",
                EnrollmentDestination {
                    profile: Some("new-account".to_owned()),
                    ..Default::default()
                },
            )
            .is_err()
        );
    }
}