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
//! Validated enrollment plans and post-custody atomic completion.

#[cfg(test)]
mod tests;
use super::{EnrollmentDestination, EnrollmentError, PreparedEnrollment, prepare};
use bcode_config::{
    BcodeConfig, RuntimeAuthProfile, RuntimeAuthSubscriptionPool, RuntimeAuthSubscriptionProfile,
    RuntimeAuthSubscriptions,
};
use bcode_provider_auth_models::{AuthPoolCompatibility, AuthProviderContribution};

/// Enrollment intent; explicit pools always take precedence over automatic routing.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub enum PoolEnrollment {
    /// Join/create an explicitly marked compatible default pool, if supported by the plugin.
    #[default]
    Automatic,
    /// Join exactly this pool, never an inferred default.
    Explicit(String),
    /// Register only this account; no pool membership changes.
    Standalone,
}

/// Read-only plan; callers must save credentials before invoking completion.
pub struct EnrollmentPlan {
    /// Ownership-checked custody destination.
    pub prepared: PreparedEnrollment,
    expected: RuntimeAuthSubscriptions,
    metadata: RuntimeAuthProfile,
    original: crate::ResolvedAuthProfile,
    pool: Option<(String, RuntimeAuthSubscriptionPool)>,
    result: EnrollmentResult,
    context: bool,
    authorization: serde_json::Value,
}

/// Non-secret publication outcome suitable for all frontends.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnrollmentResult {
    /// Enrolled account.
    pub profile: String,
    /// Selected pool, if any.
    pub pool: Option<String>,
    /// Whether automatic/default intent selected this pool.
    pub automatic: bool,
    /// Whether completion adds previously absent membership.
    pub joined: bool,
}

fn metadata(resolved: &crate::ResolvedAuthProfile) -> RuntimeAuthProfile {
    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,
            std::path::PathBuf::from,
        ),
        map: resolved.profile.map.clone(),
        device_seal: resolved.profile.settings.get("device_seal").cloned(),
    }
}

fn metadata_for_primary(resolved: &crate::ResolvedAuthProfile) -> RuntimeAuthSubscriptionProfile {
    let value = metadata(resolved);
    RuntimeAuthSubscriptionProfile {
        auth_profile: resolved.profile_name.clone(),
        storage_profile: value.storage_profile,
        vault: value.vault,
        provider: value.provider_id,
        scheme: value.scheme,
        owner_plugin_id: Some(value.owner_plugin_id),
        map: value.map,
        device_seal: value.device_seal,
    }
}

/// Validate all pool/account decisions before OAuth. Capability must come from the enabled owner.
///
/// # Errors
/// Returns an error for ambiguous, incompatible, or unowned destinations without modifying state.
#[allow(clippy::too_many_arguments)]
pub fn plan(
    config: &BcodeConfig,
    runtime: &RuntimeAuthSubscriptions,
    provider: &AuthProviderContribution,
    owner_plugin_id: &str,
    method_id: &str,
    destination: EnrollmentDestination,
    pooling: PoolEnrollment,
    compatibility: Option<&AuthPoolCompatibility>,
) -> Result<EnrollmentPlan, EnrollmentError> {
    let prepared = prepare(
        config,
        runtime,
        provider,
        owner_plugin_id,
        method_id,
        destination,
    )?;
    let metadata = metadata(&prepared.resolved);
    let mut result = EnrollmentResult {
        profile: prepared.resolved.profile_name.clone(),
        pool: None,
        automatic: false,
        joined: false,
    };
    let context = config.active_context.is_some();
    if context && matches!(&pooling, PoolEnrollment::Explicit(_)) {
        return Err(EnrollmentError::PoolConflict);
    }
    let eligible = if let Some(capability) = compatibility {
        crate::managed_pool::validate_compatibility(provider, capability)?;
        capability.methods.iter().any(|method| method == method_id)
    } else {
        false
    };
    let automatic = matches!(pooling, PoolEnrollment::Automatic);
    let planner = PoolPlanner {
        config,
        runtime,
        provider,
        owner_plugin_id,
    };
    let pool_name = planner.select(pooling, context, eligible, compatibility)?;
    let pool = if let Some(name) = pool_name {
        let pool = planner.pool(&name, automatic, compatibility, &metadata, &mut result)?;
        result.pool = Some(name.clone());
        result.automatic = automatic;
        Some((name, pool))
    } else {
        None
    };
    if runtime
        .profiles
        .get(&result.profile)
        .is_some_and(|old| old != &metadata)
        || runtime
            .bindings
            .get(&provider.provider_id)
            .is_some_and(|binding| binding.owner_plugin_id != owner_plugin_id)
    {
        return Err(EnrollmentError::PoolConflict);
    }
    let original = prepared.resolved.clone();
    Ok(EnrollmentPlan {
        original,
        prepared,
        expected: runtime.clone(),
        metadata,
        pool,
        result,
        context,
        authorization: authorization(config)?,
    })
}

struct PoolPlanner<'a> {
    config: &'a BcodeConfig,
    runtime: &'a RuntimeAuthSubscriptions,
    provider: &'a AuthProviderContribution,
    owner_plugin_id: &'a str,
}

impl PoolPlanner<'_> {
    fn select(
        &self,
        pooling: PoolEnrollment,
        context: bool,
        eligible: bool,
        compatibility: Option<&AuthPoolCompatibility>,
    ) -> Result<Option<String>, EnrollmentError> {
        let Self {
            config,
            runtime,
            provider,
            owner_plugin_id,
        } = *self;
        Ok(match pooling {
            PoolEnrollment::Standalone => None,
            PoolEnrollment::Automatic if context || !eligible => None,
            PoolEnrollment::Automatic => {
                let capability = compatibility.ok_or(EnrollmentError::InvalidMethod)?;
                let existing = crate::managed_pool::managed_pool(
                    config,
                    runtime,
                    &provider.provider_id,
                    owner_plugin_id,
                    &capability.group,
                )?;
                if let Some(name) = existing {
                    Some(name)
                } else {
                    let name = format!("{}-{}-default", provider.provider_id, capability.group);
                    if runtime.pools.contains_key(&name) || config.auth.pools.contains_key(&name) {
                        return Err(EnrollmentError::PoolConflict);
                    }
                    Some(name)
                }
            }
            PoolEnrollment::Explicit(name) => {
                if name.trim().is_empty() || !eligible {
                    return Err(EnrollmentError::PoolConflict);
                }
                Some(name)
            }
        })
    }
    fn pool(
        &self,
        name: &str,
        automatic: bool,
        compatibility: Option<&AuthPoolCompatibility>,
        metadata: &RuntimeAuthProfile,
        result: &mut EnrollmentResult,
    ) -> Result<RuntimeAuthSubscriptionPool, EnrollmentError> {
        let Self {
            config,
            runtime,
            provider,
            owner_plugin_id,
        } = *self;
        let declared_marker = config
            .auth
            .pools
            .get(name)
            .and_then(|pool| pool.automatic_group.as_deref());
        let runtime_marker = runtime
            .pools
            .get(name)
            .and_then(|pool| pool.automatic_group.as_deref());
        if [declared_marker, runtime_marker]
            .into_iter()
            .flatten()
            .any(|marker| Some(marker) != compatibility.map(|capability| capability.group.as_str()))
        {
            return Err(EnrollmentError::PoolConflict);
        }
        let group = if automatic || declared_marker.is_some() || runtime_marker.is_some() {
            compatibility.map(|capability| capability.group.as_str())
        } else {
            None
        };
        if let Some(declared) = config.auth.pools.get(name)
            && (declared.provider_plugin_id.as_deref() != Some(owner_plugin_id)
                || (declared.automatic_group.is_some()
                    && declared.automatic_provider.as_deref()
                        != Some(provider.provider_id.as_str()))
                || (automatic && declared.automatic_group.as_deref() != group))
        {
            return Err(EnrollmentError::PoolConflict);
        }
        let mut pool = if let Some(existing) = runtime.pools.get(name) {
            let declared_opt_in = config.auth.pools.get(name).is_some_and(|pool| {
                pool.automatic_provider.as_deref() == Some(provider.provider_id.as_str())
                    && pool.automatic_group.as_deref() == group
                    && pool.provider_plugin_id.as_deref() == Some(owner_plugin_id)
            });
            crate::managed_pool::validate_pool(
                existing,
                &provider.provider_id,
                owner_plugin_id,
                if declared_opt_in && existing.automatic_group.is_none() {
                    None
                } else {
                    group
                },
            )?;
            let mut existing = existing.clone();
            if declared_opt_in {
                existing.automatic_group = group.map(str::to_owned);
            }
            existing
        } else {
            RuntimeAuthSubscriptionPool {
                provider_plugin_id: Some(owner_plugin_id.to_owned()),
                provider_id: Some(provider.provider_id.clone()),
                owner_plugin_id: Some(owner_plugin_id.to_owned()),
                automatic_group: group.map(str::to_owned),
                ..RuntimeAuthSubscriptionPool::default()
            }
        };
        self.validate_members(name, compatibility.ok_or(EnrollmentError::PoolConflict)?)?;
        if automatic {
            self.include_primary(
                &mut pool,
                &result.profile,
                compatibility.ok_or(EnrollmentError::PoolConflict)?,
            )?;
        }
        self.include_target(name, &mut pool, metadata, result)?;
        Ok(pool)
    }
    fn validate_members(
        &self,
        name: &str,
        capability: &AuthPoolCompatibility,
    ) -> Result<(), EnrollmentError> {
        let Self {
            config,
            runtime,
            provider,
            owner_plugin_id,
        } = *self;
        // Validate every effective member before permitting publication, not merely the new account.
        for member in bcode_config::effective_auth_pool_order(config, runtime, name, None).profiles
        {
            let existing = crate::resolve_auth_provider_profile(
                config,
                &provider.provider_id,
                owner_plugin_id,
                Some(&member),
                runtime,
            )?;
            if !capability
                .methods
                .iter()
                .any(|method| Some(method.as_str()) == existing.profile.scheme.as_deref())
            {
                return Err(EnrollmentError::PoolConflict);
            }
        }
        Ok(())
    }
    fn include_primary(
        &self,
        pool: &mut RuntimeAuthSubscriptionPool,
        target: &str,
        capability: &AuthPoolCompatibility,
    ) -> Result<(), EnrollmentError> {
        let Self {
            config,
            runtime,
            provider,
            owner_plugin_id,
        } = *self;
        // Only the canonical provider binding/default may join alongside the target.
        let primary = crate::resolve_auth_provider_profile(
            config,
            &provider.provider_id,
            owner_plugin_id,
            None,
            runtime,
        );
        match primary {
            Ok(primary)
                if primary.profile_name != target
                    && capability.methods.iter().any(|method| {
                        Some(method.as_str()) == primary.profile.scheme.as_deref()
                    }) =>
            {
                if primary.profile.backend != "sshenv" {
                    return Err(EnrollmentError::PoolConflict);
                }
                let primary_metadata = metadata_for_primary(&primary);
                if let Some(existing) = pool
                    .profiles
                    .iter()
                    .find(|member| member.auth_profile == primary.profile_name)
                {
                    if existing != &primary_metadata {
                        return Err(EnrollmentError::PoolConflict);
                    }
                } else {
                    pool.profiles.push(primary_metadata);
                }
            }
            Ok(_) => {}
            Err(crate::AuthProfileResolutionError::MissingProfile { .. })
                if !config.auth.bindings.contains_key(&provider.provider_id)
                    && !config.auth.profiles.contains_key(&provider.provider_id)
                    && !runtime.bindings.contains_key(&provider.provider_id) => {}
            Err(error) => return Err(error.into()),
        }
        Ok(())
    }
    fn include_target(
        &self,
        name: &str,
        pool: &mut RuntimeAuthSubscriptionPool,
        metadata: &RuntimeAuthProfile,
        result: &mut EnrollmentResult,
    ) -> Result<(), EnrollmentError> {
        let config = self.config;
        let mut seen = std::collections::BTreeSet::new();
        if pool
            .profiles
            .iter()
            .any(|member| !seen.insert(&member.auth_profile))
        {
            return Err(EnrollmentError::PoolConflict);
        }
        let member = RuntimeAuthSubscriptionProfile {
            auth_profile: result.profile.clone(),
            storage_profile: metadata.storage_profile.clone(),
            vault: metadata.vault.clone(),
            provider: metadata.provider_id.clone(),
            scheme: metadata.scheme.clone(),
            owner_plugin_id: Some(metadata.owner_plugin_id.clone()),
            map: metadata.map.clone(),
            device_seal: metadata.device_seal.clone(),
        };
        if let Some(existing) = pool
            .profiles
            .iter()
            .find(|existing| existing.auth_profile == result.profile)
        {
            if existing != &member {
                return Err(EnrollmentError::PoolConflict);
            }
        } else {
            result.joined = !config
                .auth
                .pools
                .get(name)
                .is_some_and(|declared| declared.profiles.contains(&result.profile));
            pool.profiles.push(member);
        }
        Ok(())
    }
}

/// Atomically publish non-secret metadata and membership only AFTER credentials are saved.
/// Existing standalone accounts can use this after a fresh plan without redoing OAuth.
///
/// # Errors
/// Returns an error if registry changed since planning, ownership conflicts, or persistence fails.
fn authorization(config: &BcodeConfig) -> Result<serde_json::Value, EnrollmentError> {
    serde_json::to_value((&config.auth, &config.active_context))
        .map_err(|_| EnrollmentError::PoolConflict)
}

/// Validate the plan against current configuration without filesystem or publication effects.
///
/// # Errors
/// Returns an error for configuration drift or post-plan identity/destination/policy changes.
pub fn complete_with_config(
    plan: &EnrollmentPlan,
    current_config: &BcodeConfig,
) -> Result<EnrollmentResult, bcode_config::ConfigError> {
    validate_completion(plan, current_config)?;
    Ok(plan.result.clone())
}

fn validate_completion(
    plan: &EnrollmentPlan,
    current_config: &BcodeConfig,
) -> Result<(), bcode_config::ConfigError> {
    if authorization(current_config).ok().as_ref() != Some(&plan.authorization) {
        return Err(bcode_config::ConfigError::Composition { message: "Authentication configuration changed during enrollment; credentials saved but metadata not published. Replan before attaching.".to_owned() });
    }
    let mut current = plan.prepared.resolved.clone();
    let device_seal = current.profile.settings.get("device_seal").cloned();
    if device_seal.as_deref() != Some("disabled")
        && device_seal != plan.original.profile.settings.get("device_seal").cloned()
    {
        return Err(bcode_config::ConfigError::Composition {
            message: "Enrollment policy changed after planning".to_owned(),
        });
    }
    current.profile.settings.remove("device_seal");
    let mut original = plan.original.clone();
    original.profile.settings.remove("device_seal");
    if current != original {
        return Err(bcode_config::ConfigError::Composition {
            message: "Enrollment destination changed after planning".to_owned(),
        });
    }
    Ok(())
}

/// Reload effective configuration, validate authorization, then atomically publish after custody.
///
/// # Errors
/// Returns an error for configuration/registry drift, changed policy or failed persistence.
pub fn complete(plan: &EnrollmentPlan) -> Result<EnrollmentResult, bcode_config::ConfigError> {
    let config = bcode_config::load_config()?;
    validate_completion(plan, &config)?;
    let device_seal = plan
        .prepared
        .resolved
        .profile
        .settings
        .get("device_seal")
        .cloned();
    let mut metadata = plan.metadata.clone();
    metadata.device_seal = device_seal;
    let mut pool = plan.pool.clone();
    if let Some((_, pool)) = &mut pool {
        for member in &mut pool.profiles {
            if member.auth_profile == plan.result.profile {
                member.device_seal.clone_from(&metadata.device_seal);
            }
        }
    }
    if !plan.context {
        bcode_config::publish_auth_enrollment(
            &plan.expected,
            &plan.result.profile,
            &metadata,
            pool.as_ref().map(|(name, pool)| (name.as_str(), pool)),
        )?;
    }
    Ok(plan.result.clone())
}