vta-service 0.13.10

Service for Verifiable Trust Agents operating in Verifiable Trust Communities
Documentation
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
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};

use affinidi_did_resolver_cache_sdk::{DIDCacheClient, config::DIDCacheConfigBuilder};
use affinidi_tdk::common::TDKSharedState;
use affinidi_tdk::common::config::TDKConfig;
use affinidi_tdk::messaging::ATM;
use affinidi_tdk::messaging::config::ATMConfig;
use affinidi_tdk::messaging::profiles::ATMProfile;
use affinidi_tdk::messaging::protocols::trust_ping::TrustPing;
use affinidi_tdk::secrets_resolver::SecretsResolver;
use ed25519_dalek_bip32::ExtendedSigningKey;

use crate::acl::{self, Role};
use crate::auth::session::{self, SessionState};
use crate::cli_store::{CliStore, load_storage_key_for_cli};
use crate::config::AppConfig;
use crate::contexts;
use crate::keys::derivation::Bip32Extension;
use crate::keys::seed_store::create_seed_store;
use crate::keys::{KeyRecord, KeyStatus, KeyType};
use crate::store::Store;

const BOLD: &str = "\x1b[1m";
const DIM: &str = "\x1b[2m";
const GREEN: &str = "\x1b[32m";
const RED: &str = "\x1b[31m";
const CYAN: &str = "\x1b[36m";
const YELLOW: &str = "\x1b[33m";
const RESET: &str = "\x1b[0m";

fn section(title: &str) {
    let pad = 46usize.saturating_sub(title.len());
    eprintln!(
        "\n{DIM}──{RESET} {BOLD}{title}{RESET} {DIM}{}{RESET}",
        "".repeat(pad)
    );
}

pub async fn run_status(config_path: Option<PathBuf>) -> Result<(), Box<dyn std::error::Error>> {
    // 1. Check setup completion
    let config = match AppConfig::load(config_path) {
        Ok(c) => c,
        Err(e) => {
            section("VTA Status");
            eprintln!("  {CYAN}{:<13}{RESET} {RED}{RESET} not complete", "Setup");
            eprintln!("  {CYAN}{:<13}{RESET} {e}", "Error");
            eprintln!();
            eprintln!("Run `vta setup` to configure this instance.");
            return Ok(());
        }
    };

    section("VTA Status");
    let name = config.vta_name.as_deref().unwrap_or("(not set)");
    eprintln!(
        "  {CYAN}{:<13}{RESET} {}",
        "Name",
        if name == "(not set)" {
            format!("{DIM}{name}{RESET}")
        } else {
            name.to_string()
        }
    );
    eprintln!("  {CYAN}{:<13}{RESET} {GREEN}{RESET} complete", "Setup");
    let mut svc_list = Vec::new();
    if config.services.rest {
        svc_list.push("REST");
    }
    if config.services.didcomm {
        svc_list.push("DIDComm");
    }
    let svc_display = if svc_list.is_empty() {
        format!("{DIM}(none){RESET}")
    } else {
        svc_list.join(", ")
    };
    eprintln!("  {CYAN}{:<13}{RESET} {svc_display}", "Services");
    eprintln!(
        "  {CYAN}{:<13}{RESET} {}",
        "Config",
        config.config_path.display()
    );

    // 2. DID resolver for resolution checks (created early, reused for contexts)
    let did_resolver = DIDCacheClient::new(DIDCacheConfigBuilder::default().build())
        .await
        .ok();

    // 3. VTA DID + resolution check → extract mediator DID from DIDCommMessaging
    let mut discovered_mediator: Option<String> = None;
    if let Some(ref did) = config.vta_did {
        eprintln!("  {CYAN}{:<13}{RESET} {did}", "VTA DID");
        if let Some(ref resolver) = did_resolver {
            match resolver.resolve(did).await {
                Ok(resolved) => {
                    let method = did
                        .strip_prefix("did:")
                        .and_then(|s| s.split(':').next())
                        .unwrap_or("?");
                    eprintln!("                {GREEN}{RESET} resolves ({method})");

                    // Look for mediator DID in DIDCommMessaging service
                    for svc in &resolved.doc.service {
                        if svc.type_.iter().any(|t| t == "DIDCommMessaging")
                            && discovered_mediator.is_none()
                        {
                            // get_uris() wraps Map-sourced values in JSON quotes
                            discovered_mediator = svc
                                .service_endpoint
                                .get_uris()
                                .into_iter()
                                .map(|u| u.trim_matches('"').to_string())
                                .find(|u| u.starts_with("did:"));
                        }
                    }
                }
                Err(e) => eprintln!("                {RED}✗ resolution failed: {e}{RESET}"),
            }
        }
    } else {
        eprintln!("  {CYAN}{:<13}{RESET} {DIM}(not set){RESET}", "VTA DID");
    }

    // 4. URL + Store path
    let url = config.public_url.as_deref().unwrap_or("(not set)");
    eprintln!(
        "  {CYAN}{:<13}{RESET} {}",
        "URL",
        if url == "(not set)" {
            format!("{DIM}{url}{RESET}")
        } else {
            url.to_string()
        }
    );
    eprintln!(
        "  {CYAN}{:<13}{RESET} {}",
        "Store",
        config.store.data_dir.display()
    );

    // 5. Mediator section (grouped: display + resolution + trust-ping)
    section("Mediator");
    let mediator_did = discovered_mediator
        .as_deref()
        .or(config.messaging.as_ref().map(|m| m.mediator_did.as_str()));

    if let Some(ref msg) = config.messaging {
        eprintln!("  {CYAN}{:<13}{RESET} {}", "URL", msg.mediator_url);
        eprintln!(
            "  {CYAN}{:<13}{RESET} {}",
            "DID",
            mediator_did.unwrap_or("(unknown)")
        );
        if let Some(ref resolver) = did_resolver
            && let Some(did) = mediator_did
        {
            match resolver.resolve(did).await {
                Ok(_) => {
                    let method = did
                        .strip_prefix("did:")
                        .and_then(|s| s.split(':').next())
                        .unwrap_or("?");
                    eprintln!("                {GREEN}{RESET} resolves ({method})");
                }
                Err(e) => eprintln!("                {RED}✗ resolution failed: {e}{RESET}"),
            }
        }
    } else {
        eprintln!("  {DIM}Not configured{RESET}");
    }

    // 6. Open store (may fail if VTA is already running)
    //
    // `status` is a diagnostic and degrades rather than exiting — it already
    // tolerates the store being locked by a running daemon. But it must not
    // silently treat "could not reach the secret store" as "encryption is off":
    // that reads every encrypted keyspace through a bare handle and reports
    // confident nonsense. Say what happened and carry on.
    let enc_key = match load_storage_key_for_cli(&config).await {
        Ok(k) => k,
        Err(e) => {
            eprintln!();
            eprintln!(
                "  {YELLOW}Note:{RESET} Could not derive the storage-encryption key ({e}). \
                 Encrypted keyspaces below will read as unavailable."
            );
            None
        }
    };
    let store = match Store::open(&config.store) {
        Ok(s) => s,
        Err(_) => {
            eprintln!();
            eprintln!(
                "  {YELLOW}Note:{RESET} Could not open the data store (is VTA already running?)."
            );
            eprintln!("        Stop the VTA service and re-run `vta status` for full diagnostics.");
            eprintln!();
            return Ok(());
        }
    };
    let cs = CliStore::from_store(store, enc_key);

    // 7. Trust-ping to mediator (needs key records from store)
    if let (Some(vta_did), Some(mediator)) = (&config.vta_did, mediator_did) {
        match tokio::time::timeout(
            Duration::from_secs(10),
            send_trust_ping(&config, &cs, vta_did, mediator),
        )
        .await
        {
            Ok(Ok(latency)) => {
                eprintln!("                {GREEN}{RESET} pong ({latency}ms)");
            }
            Ok(Err(e)) => {
                eprintln!("                {RED}{RESET} trust-ping failed: {e}");
            }
            Err(_) => {
                eprintln!("                {RED}{RESET} trust-ping timed out");
            }
        }
    }

    // 8. Gather stats from store
    let contexts_ks = cs.keyspace(crate::keyspaces::CONTEXTS)?;
    let keys_ks = cs.keyspace(crate::keyspaces::KEYS)?;
    let acl_ks = cs.keyspace(crate::keyspaces::ACL)?;
    let sessions_ks = cs.keyspace(crate::keyspaces::SESSIONS)?;

    // --- Contexts ---
    let ctx_records = contexts::list_contexts(&contexts_ks).await?;
    section(&format!("Contexts ({})", ctx_records.len()));

    for ctx in &ctx_records {
        let did_display = ctx.did.as_deref().unwrap_or("(no DID)");
        let resolution = if let Some(ref did) = ctx.did {
            if let Some(ref resolver) = did_resolver {
                match resolver.resolve(did).await {
                    Ok(_) => {
                        let method = did
                            .strip_prefix("did:")
                            .and_then(|s| s.split(':').next())
                            .unwrap_or("unknown");
                        format!("{GREEN}{RESET} {method}")
                    }
                    Err(e) => format!("{RED}{RESET} {e}"),
                }
            } else {
                format!("{DIM}skipped{RESET}")
            }
        } else {
            String::new()
        };

        if resolution.is_empty() {
            eprintln!("  {CYAN}{:<16}{RESET} {DIM}{did_display}{RESET}", ctx.id);
        } else {
            eprintln!("  {CYAN}{:<16}{RESET} {did_display}   {resolution}", ctx.id);
        }
    }

    // --- Keys ---
    let raw_keys = keys_ks.prefix_iter_raw("key:").await?;
    let mut total_keys = 0usize;
    let mut active = 0usize;
    let mut revoked = 0usize;
    let mut ed25519_count = 0usize;
    let mut x25519_count = 0usize;
    let mut p256_count = 0usize;

    for (_key, value) in &raw_keys {
        if let Ok(record) = serde_json::from_slice::<KeyRecord>(value) {
            total_keys += 1;
            match record.status {
                KeyStatus::Active => active += 1,
                KeyStatus::Revoked => revoked += 1,
            }
            match record.key_type {
                KeyType::Ed25519 => ed25519_count += 1,
                KeyType::X25519 => x25519_count += 1,
                KeyType::P256 => p256_count += 1,
            }
        }
    }

    section(&format!("Keys ({total_keys})"));
    eprintln!(
        "  {CYAN}{:<13}{RESET} {active}  Ed25519: {ed25519_count}, X25519: {x25519_count}, P-256: {p256_count}",
        "Active"
    );
    eprintln!("  {CYAN}{:<13}{RESET} {revoked}", "Revoked");

    // --- ACL ---
    let acl_entries = acl::list_acl_entries(&acl_ks).await?;
    let admin_count = acl_entries.iter().filter(|e| e.role == Role::Admin).count();
    let initiator_count = acl_entries
        .iter()
        .filter(|e| e.role == Role::Initiator)
        .count();
    let application_count = acl_entries
        .iter()
        .filter(|e| e.role == Role::Application)
        .count();

    section(&format!("ACL ({})", acl_entries.len()));
    eprintln!("  {CYAN}{:<13}{RESET} {admin_count}", "Admin");
    eprintln!("  {CYAN}{:<13}{RESET} {initiator_count}", "Initiator");
    eprintln!("  {CYAN}{:<13}{RESET} {application_count}", "Application");

    // --- Sessions ---
    let sessions = session::list_sessions(&sessions_ks).await?;
    let authenticated = sessions
        .iter()
        .filter(|s| s.state == SessionState::Authenticated)
        .count();
    let challenge_sent = sessions
        .iter()
        .filter(|s| s.state == SessionState::ChallengeSent)
        .count();

    section(&format!("Sessions ({})", sessions.len()));
    eprintln!("  {CYAN}{:<13}{RESET} {authenticated}", "Authenticated");
    eprintln!("  {CYAN}{:<13}{RESET} {challenge_sent}", "ChallengeSent");
    eprintln!();

    Ok(())
}

/// Send a DIDComm trust-ping to the mediator and return latency in milliseconds.
async fn send_trust_ping(
    config: &AppConfig,
    store: &Store,
    vta_did: &str,
    mediator_did: &str,
) -> Result<u128, Box<dyn std::error::Error>> {
    let seed_store = create_seed_store(config)?;
    // Master seed in plaintext — wipe on drop (P0.7).
    let seed = zeroize::Zeroizing::new(seed_store.get().await?.ok_or("no master seed available")?);

    let root = ExtendedSigningKey::from_seed(&seed)?;

    let keys_ks = store.keyspace(crate::keyspaces::KEYS)?;

    // Internal storage always uses #key-0 for the signing record, regardless
    // of DID method. The X25519 record at #key-1 only exists for did:webvh
    // (did:key curve-converts the X25519 key from Ed25519 at runtime).
    let signing_key_id = format!("{vta_did}#key-0");

    let signing: KeyRecord = keys_ks
        .get(crate::keys::store_key(&signing_key_id))
        .await?
        .ok_or("VTA signing key record not found")?;

    let tdk = TDKSharedState::new(TDKConfig::builder().build()?).await?;

    if vta_did.starts_with("did:key:") {
        // did:key: X25519 is curve-converted from Ed25519, and verification method
        // IDs use multibase-encoded public key fragments, not #key-0/#key-1.
        let dp: ed25519_dalek_bip32::DerivationPath = signing.derivation_path.parse()?;
        let derived = root.derive(&dp)?;
        let seed_bytes: &[u8; 32] = derived.signing_key.as_bytes();
        let secrets = vta_sdk::did_key::secrets_from_did_key(vta_did, seed_bytes)?;
        tdk.secrets_resolver().insert(secrets.signing).await;
        tdk.secrets_resolver().insert(secrets.key_agreement).await;
    } else {
        // did:webvh / other methods: independently derived keys, #key-0/#key-1 IDs.
        let ka_key_id = format!("{vta_did}#key-1");
        let ka: KeyRecord = keys_ks
            .get(crate::keys::store_key(&ka_key_id))
            .await?
            .ok_or("VTA key-agreement key record not found")?;

        let mut signing_secret = root.derive_ed25519(&signing.derivation_path)?;
        signing_secret.id = signing_key_id;
        tdk.secrets_resolver().insert(signing_secret).await;

        let mut ka_secret = root.derive_x25519(&ka.derivation_path)?;
        ka_secret.id = ka_key_id;
        tdk.secrets_resolver().insert(ka_secret).await;
    }

    let atm = Arc::new(ATM::new(ATMConfig::builder().build()?, Arc::new(tdk)).await?);

    // Everything past the ATM runs inside the block so ONE path tears it down.
    // Both `?`s below used to return past `graceful_shutdown` entirely, and that
    // shutdown could not have stopped the socket anyway — it stops websockets by
    // iterating the ATM's profile map, and this profile was never registered
    // (vta-sdk #830). `vta status` exits straight after, so nothing was harmed;
    // the shape is the trap. Stringified before the teardown await: a boxed
    // error is not `Send`.
    let outcome = async {
        let profile = ATMProfile::new(
            &atm,
            None,
            vta_did.to_string(),
            Some(mediator_did.to_string()),
        )
        .await?;
        // Registered, so the teardown below can actually reach the socket.
        let profile = atm.profile_add(&profile, false).await?;

        // The mediator may only expose a wss:// endpoint (no REST/https).
        atm.profile_enable_websocket(&profile).await?;

        let start = Instant::now();
        TrustPing::default()
            .send_ping(&atm, &profile, mediator_did, true, true, true)
            .await?;
        Ok::<u128, Box<dyn std::error::Error>>(start.elapsed().as_millis())
    }
    .await
    .map_err(|e| e.to_string());

    atm.graceful_shutdown().await;
    outcome.map_err(Into::into)
}