vtc-service 0.9.5

Service for Verifiable Trust Communities
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
//! `vtc admin emergency-bootstrap` — destructive operator recovery
//! via the VTA's `AdminRotated` flow.
//!
//! Implements **M0.10** rework per
//! `tasks/vtc-mvp/vta-driven-keys.md` §4. Used when every admin
//! passkey is lost: the operator runs this command on a stopped
//! daemon, authenticates against the VTA with a fresh ephemeral
//! DID the VTA's ACL was just pre-authorized to accept, and the
//! VTC accepts the recovery only if the VTA does.
//!
//! ## Trust root
//!
//! The VTC has no locally-held recovery secret (no BIP-39 mnemonic,
//! no backup-derived password). Authority for "reset admin access"
//! lives in the operator's PNM admin credential at the VTA: if they
//! can `pnm acl create` an admin DID against the VTC's context,
//! they can recover. Losing PNM admin access at the VTA means
//! losing the community — by design.
//!
//! ## What gets cleared
//!
//! - Every `Role::Admin` ACL entry.
//! - Every `admin:<did>` sister record (M0.6.1 metadata).
//! - The full set of `PasskeyUser` + credential mapping records
//!   for admin DIDs.
//!
//! The earlier "install carve-out closed" marker is no longer
//! emitted (the carve-out concept is gone); no cleanup needed.
//!
//! ## What persists
//!
//! - The community profile (§5.1).
//! - The audit log — emergency bootstrap is audited via the
//!   pending marker; you can't quietly erase tracks.
//! - The `VtcKeyBundle` — the VTC's DID + integration keys stay
//!   put, only the admin ACL state resets.

use crate::store::keyspaces;
use std::path::PathBuf;
use std::pin::Pin;
use std::sync::Arc;

use crate::acl::{VtcRole, delete_acl_entry, list_acl_entries};
use async_trait::async_trait;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use tracing::{info, warn};
use vti_common::auth::session::{delete_session, list_sessions};
use vti_common::config::StoreConfig;
use vti_common::error::AppError;
use vti_common::store::Store;

use vta_sdk::provision_client::{
    EphemeralSetupKey, OperatorMessages, ProvisionAsk, ProvisionError, VtaIntent, VtaReply,
    run_provision,
};

use crate::acl::admin::list_admin_entries;
use crate::config::AppConfig;
use crate::install::{
    INSTALL_TOKEN_DEFAULT_TTL_SECS, InstallTokenSigner, InstallTokenStore,
    PendingEmergencyBootstrap, mint_install_token,
};
use crate::keys::seed_store::{SecretStore, create_secret_store};
use crate::setup::VtcKeyBundle;

/// CLI args. Mirrors the `Commands::Admin::EmergencyBootstrap`
/// clap surface; the `context` override is plumbed through here so
/// operators with a non-`default` VTA context can recover without
/// editing `config.toml` first.
pub struct EmergencyBootstrapArgs {
    pub config_path: Option<PathBuf>,
    pub context: Option<String>,
}

/// Outcome of a successful run.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmergencyBootstrapOutcome {
    pub install_url: String,
    /// Out-of-band claim code the operator types alongside the
    /// install URL. Printed by the CLI; never persisted.
    pub claim_code: String,
    pub admin_entries_cleared: usize,
    pub admin_records_cleared: usize,
}

/// Trait used by [`run_emergency_bootstrap_with_store`] to drive the
/// VTA's `AdminRotated` flow. Production uses
/// [`RunProvisionProver`]; tests inject a mock.
#[async_trait]
pub trait VtaRecoveryProver: Send + Sync {
    /// Prove to the VTA that the operator currently holds admin
    /// authority at `vta_did`'s `context`. Returns `Ok(())` on
    /// successful round-trip; `Err(AppError::Unauthorized)` if the
    /// VTA rejects the ephemeral DID (operator forgot the ACL
    /// step, or no longer has access at the VTA).
    async fn prove(
        &self,
        vta_did: &str,
        ephemeral_did: &str,
        ephemeral_privkey_mb: &str,
        context: &str,
    ) -> Result<(), AppError>;
}

/// Production prover — drives `vta_sdk::provision_client::run_provision`
/// with `VtaIntent::AdminRotated` and discards the returned admin
/// credential (the recovery flow doesn't keep it; only proof of
/// access matters).
pub struct RunProvisionProver;

#[async_trait]
impl VtaRecoveryProver for RunProvisionProver {
    async fn prove(
        &self,
        vta_did: &str,
        ephemeral_did: &str,
        ephemeral_privkey_mb: &str,
        context: &str,
    ) -> Result<(), AppError> {
        let ask = ProvisionAsk::vta_admin_rotated(context).with_label("vtc emergency-bootstrap");
        let (event_tx, mut event_rx) = mpsc::unbounded_channel();
        let drain = tokio::spawn(async move { while event_rx.recv().await.is_some() {} });
        let reply = run_provision(
            VtaIntent::AdminRotated,
            vta_did.to_string(),
            ephemeral_did.to_string(),
            ephemeral_privkey_mb.to_string(),
            ask,
            None,
            Arc::new(VtcRecoveryMessages),
            event_tx,
        )
        .await
        .map_err(translate_provision_err)?;
        drain.abort();
        match reply {
            VtaReply::AdminOnly(_) => Ok(()),
            VtaReply::Full(_) => Err(AppError::Internal(
                "VTA returned a Full reply but emergency-bootstrap asked for AdminRotated".into(),
            )),
        }
    }
}

fn translate_provision_err(e: ProvisionError) -> AppError {
    let msg = e.to_string();
    if msg.to_ascii_lowercase().contains("auth") || msg.to_ascii_lowercase().contains("forbidden") {
        AppError::Unauthorized(format!(
            "VTA rejected the recovery DID: {msg}. \
             Make sure `pnm acl create` ran for this context against this VTA."
        ))
    } else {
        AppError::Internal(format!("VTA recovery call failed: {msg}"))
    }
}

struct VtcRecoveryMessages;

impl OperatorMessages for VtcRecoveryMessages {
    fn integration_label(&self) -> &str {
        "VTC"
    }
    fn integration_label_lower(&self) -> &str {
        "vtc"
    }
    fn pnm_admin_command_hint(&self, context_id: &str, setup_did: &str) -> String {
        format!(
            "pnm acl create --did {setup_did} --role admin --contexts {context_id} \\\n  \
             --expires 1h"
        )
    }
}

/// The CLI subcommand's entry point.
pub async fn run_emergency_bootstrap(
    args: EmergencyBootstrapArgs,
) -> Result<EmergencyBootstrapOutcome, AppError> {
    let config = AppConfig::load(args.config_path)?;
    let store = Store::open(&StoreConfig {
        data_dir: config.store.data_dir.clone(),
    })
    .map_err(|e| {
        AppError::Config(format!(
            "failed to open fjall store at '{}': {e}. Is the daemon still running? \
             Stop it before running emergency-bootstrap.",
            config.store.data_dir.display()
        ))
    })?;
    let secret_store = create_secret_store(&config)
        .map_err(|e| AppError::Config(format!("failed to construct secret store: {e}")))?;
    let setup_key = EphemeralSetupKey::generate()
        .map_err(|e| AppError::Internal(format!("ephemeral key gen: {e}")))?;
    let prover = RunProvisionProver;
    run_emergency_bootstrap_with_store(
        &config,
        &store,
        secret_store.as_ref(),
        &setup_key,
        &prover,
        args.context,
    )
    .await
}

/// Inner driver split from [`run_emergency_bootstrap`] so tests can
/// compose their own `Store` + `SecretStore` + recovery prover
/// without touching the filesystem or a live VTA.
pub async fn run_emergency_bootstrap_with_store(
    config: &AppConfig,
    store: &Store,
    secret_store: &dyn SecretStore,
    setup_key: &EphemeralSetupKey,
    prover: &dyn VtaRecoveryProver,
    context_override: Option<String>,
) -> Result<EmergencyBootstrapOutcome, AppError> {
    let bundle_bytes = secret_store
        .get()
        .await
        .map_err(|e| AppError::SecretStore(e.to_string()))?
        .ok_or_else(|| {
            AppError::Config(
                "no key material in the secret store — has this VTC ever been set up?".into(),
            )
        })?;
    let bundle = VtcKeyBundle::from_secret_store_bytes(&bundle_bytes)?;

    let vta_did = config.vta_did.as_deref().ok_or_else(|| {
        AppError::Config(
            "config.vta_did not set — emergency-bootstrap recovery requires the VTA's DID. \
             Re-run `vtc setup` against the same VTA to populate it."
                .into(),
        )
    })?;
    let context = context_override
        .or_else(|| derive_context_from_config(config))
        .unwrap_or_else(|| "default".to_string());

    // The "is this operator legitimately recovering?" check.
    prover
        .prove(
            vta_did,
            &setup_key.did,
            setup_key.private_key_multibase(),
            &context,
        )
        .await?;

    let acl_ks = store.keyspace(keyspaces::ACL)?;
    let passkey_ks = store.keyspace(keyspaces::PASSKEY)?;
    let install_ks = store.keyspace(keyspaces::INSTALL)?;
    let sessions_ks = store.keyspace(keyspaces::SESSIONS)?;
    let install_store = InstallTokenStore::new(install_ks);

    // --- pending audit marker (BEFORE the wipe) ---------------------
    //
    // Stamp the marker first and flush it to disk so a crash mid-wipe
    // still leaves a durable record that an emergency bootstrap was
    // invoked (the marker is consumed-on-read at the next boot). If we
    // stamped it after the deletes, a mid-loop crash would leave the
    // wipe unaudited.
    let operator_hostname = gethostname::gethostname().to_string_lossy().into_owned();
    install_store
        .mark_emergency_pending(PendingEmergencyBootstrap {
            operator_hostname: operator_hostname.clone(),
            invoked_at: Utc::now(),
        })
        .await?;
    store.persist().await?;

    // --- destructive cleanup ----------------------------------------
    let mut admin_entries_cleared = 0;
    for entry in list_acl_entries(&acl_ks).await? {
        if entry.role == VtcRole::Admin {
            delete_acl_entry(&acl_ks, &entry.did).await?;
            admin_entries_cleared += 1;
        }
    }

    let admin_records = list_admin_entries(&passkey_ks).await?;
    let admin_records_cleared = admin_records.len();
    for entry in admin_records {
        passkey_ks
            .remove(format!("admin:{}", entry.did).into_bytes())
            .await?;
        if let Some(user) =
            vti_common::auth::passkey::store::get_passkey_user_by_did(&passkey_ks, &entry.did)
                .await?
        {
            passkey_ks
                .remove(format!("pk_user:{}", user.user_uuid).into_bytes())
                .await?;
            passkey_ks
                .remove(format!("pk_did:{}", entry.did).into_bytes())
                .await?;
            for cred in user.credentials {
                let cred_id_hex = hex::encode(<_ as AsRef<[u8]>>::as_ref(cred.cred_id()));
                passkey_ks
                    .remove(format!("pk_cred:{cred_id_hex}").into_bytes())
                    .await?;
            }
        }
    }

    // Clear ALL sessions — refresh tokens for the presumed-compromised
    // admins must not survive the wipe (without this, a stolen refresh
    // token keeps minting access tokens after recovery). Break-glass
    // recovery treats every live session as suspect.
    let mut sessions_cleared = 0;
    for session in list_sessions(&sessions_ks).await? {
        delete_session(&sessions_ks, &session.session_id).await?;
        sessions_cleared += 1;
    }

    // --- mint a fresh install token ---------------------------------
    //
    // The earlier "carve-out reopen" step is gone — install tokens
    // are gated per-row by the out-of-band claim secret, so emergency
    // recovery just mints a fresh URL + code pair the operator types
    // alongside.
    let ed25519 = bundle.ed25519_private_bytes()?;
    let signer = InstallTokenSigner::from_master_seed(&*ed25519)?;
    let issuer = bundle.integration_did.clone();
    // Reuse the recovery DID as the new admin — the operator already
    // proved control of it via the VTA recovery context, and it's the
    // identity they currently hold private keys for. Operators who
    // want a different admin DID can rotate via the regular flow
    // after the emergency bootstrap completes.
    let minted = mint_install_token(
        &signer,
        &issuer,
        &setup_key.did,
        INSTALL_TOKEN_DEFAULT_TTL_SECS,
    )?;
    let claim_code = crate::install::claim_secret::generate();
    let claim_code_hash = crate::install::claim_secret::hash(&claim_code)?;
    let exp = Utc::now() + chrono::Duration::seconds(INSTALL_TOKEN_DEFAULT_TTL_SECS as i64);
    install_store
        .record_issued(
            &minted.jti,
            minted.cnonce_bytes,
            *minted.ephemeral_signing_key,
            exp,
            Some(claim_code_hash),
            Some(setup_key.did.clone()),
        )
        .await?;

    // --- install URL ------------------------------------------------
    // `/admin/install` so the embedded admin SPA picks the request
    // up and runs the install-claim ceremony in-browser. The bare
    // `/install` path would hit the website fallback, which has no
    // install page. The `vtc://install?token=…` fallback (when
    // `public_url` is unset) intentionally keeps the bare-path shape
    // because nothing renders it; it's a sentinel for ops scripts.
    let install_url = match &config.public_url {
        Some(base) => format!(
            "{}/admin/install?token={}",
            base.trim_end_matches('/'),
            minted.jwt
        ),
        None => format!("vtc://install?token={}", minted.jwt),
    };

    info!(
        operator_hostname = %operator_hostname,
        admin_entries_cleared,
        admin_records_cleared,
        sessions_cleared,
        "emergency bootstrap completed; install URL minted"
    );
    if admin_entries_cleared == 0 {
        warn!(
            "emergency bootstrap cleared no admin entries — was the daemon already in a \
             fresh-install state?"
        );
    }

    // Flush the destructive cleanup + the freshly-minted install-token row to
    // disk before handing the URL back — without this a crash could leave the
    // old admins half-deleted or the new token row non-durable, handing the
    // operator a dead recovery URL (P2.5).
    store.persist().await?;

    Ok(EmergencyBootstrapOutcome {
        install_url,
        claim_code,
        admin_entries_cleared,
        admin_records_cleared,
    })
}

/// VTC config has no `context` field today (the wizard records it
/// indirectly via the integration DID's webvh path). For now we
/// fall back to `"default"` and rely on the CLI's `--context` flag
/// for non-default deployments. A first-class `vtc_context` field
/// can land in a follow-up once Phase 1 surfaces it elsewhere.
fn derive_context_from_config(_config: &AppConfig) -> Option<String> {
    None
}

/// Convenience for `main.rs` — used when the wizard rework is not
/// gated on a successful prover round-trip.
pub fn emergency_bootstrap_unavailable() -> AppError {
    AppError::Internal("vtc admin emergency-bootstrap requires the `setup` feature".into())
}

// ---------------------------------------------------------------------------
// Helpers re-exported for tests
// ---------------------------------------------------------------------------

/// Construct a `Pin<Box<...>>` future signature in async-trait-friendly
/// form for downstream test mocks that don't want to depend on
/// `async-trait` themselves. The trait above uses `#[async_trait]`
/// so impls can use plain `async fn`; the type alias is here for
/// out-of-crate mocks that prefer manual `dyn Future`.
pub type RecoveryProverFuture<'a> =
    Pin<Box<dyn std::future::Future<Output = Result<(), AppError>> + Send + 'a>>;