vta-service 0.43.0

Service for Verifiable Trust Agents operating in 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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
//! ACL-gated holder-key resolution for credential presentation (Phase 3).
//!
//! To sign a presentation server-side — the SD-JWT-VC holder `kb-jwt`, and the
//! Data-Integrity proof on a consent record — the VTA needs the holder subject
//! key's private material. That key is **VTA-managed** (derived from the master
//! seed), looked up by the subject `did:key`, and — the load-bearing constraint
//! — only usable **within the context the caller's ACL allows**. The VTA must
//! refuse to sign with a key outside the caller's authorised context(s): the
//! privilege boundary (memory `vta-holder-key-acl-gated-signing`).
//!
//! This reuses the **exact** ACL gate ([`AuthClaims::require_context`]) and
//! BIP-32 derivation the signing oracle uses — the boundary is not reinvented.

use std::sync::Arc;

use affinidi_sd_jwt::error::SdJwtError;
use affinidi_secrets_resolver::secrets::Secret;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use ed25519_dalek::{Signature, Signer, SigningKey};
use serde_json::Value;
use vta_sdk::keys::{KeyOrigin, KeyRecord, KeyStatus, KeyType};
use zeroize::Zeroizing;

use crate::auth::AuthClaims;
use crate::keys::seed_store::SeedStore;
use crate::store::KeyspaceHandle;
use vti_common::error::AppError;

/// A production Ed25519 SD-JWT [`JwtSigner`](affinidi_sd_jwt::signer::JwtSigner)
/// wrapping a derived holder key — used to sign the presentation `kb-jwt`.
///
/// `Debug` is derived; `ed25519_dalek::SigningKey`'s own `Debug` redacts the key.
#[derive(Debug)]
pub struct HolderSdJwtSigner {
    key: SigningKey,
    kid: String,
}

impl affinidi_sd_jwt::signer::JwtSigner for HolderSdJwtSigner {
    fn algorithm(&self) -> &str {
        "EdDSA"
    }
    fn key_id(&self) -> Option<&str> {
        Some(&self.kid)
    }
    fn sign_jwt(&self, header: &Value, payload: &Value) -> Result<String, SdJwtError> {
        let h = URL_SAFE_NO_PAD.encode(
            serde_json::to_vec(header).map_err(|e| SdJwtError::Verification(e.to_string()))?,
        );
        let p = URL_SAFE_NO_PAD.encode(
            serde_json::to_vec(payload).map_err(|e| SdJwtError::Verification(e.to_string()))?,
        );
        let input = format!("{h}.{p}");
        let sig: Signature = self.key.sign(input.as_bytes());
        Ok(format!(
            "{input}.{}",
            URL_SAFE_NO_PAD.encode(sig.to_bytes())
        ))
    }
}

/// The holder's signing material for presenting `subject_did`'s credentials —
/// the SD-JWT `kb-jwt` signer and the consent-record DI secret, both over the
/// same derived key.
#[derive(Debug)]
pub struct HolderKeys {
    /// SD-JWT-VC `kb-jwt` signer.
    pub signer: HolderSdJwtSigner,
    /// Data-Integrity secret for signing a (query-scoped) consent record.
    pub consent_secret: Secret,
}

/// Resolve the VTA-managed holder key for `subject_did`, **gated by the caller's
/// ACL** for the key's context.
///
/// - The subject must be a `did:key` whose (derived, active, Ed25519) key the
///   VTA manages — else `NotFound` / `Validation`.
/// - The caller must have ACL access to the key's `context_id` (or be
///   super-admin for a context-less key) — else `Forbidden`. **This is the
///   privilege boundary**: it stops a caller minting presentations from keys
///   outside their authorised context.
/// - The key is then derived from the master seed exactly as the signing oracle
///   derives it.
pub async fn resolve_holder_keys(
    keys_ks: &KeyspaceHandle,
    contexts_ks: &KeyspaceHandle,
    seed_store: &Arc<dyn SeedStore>,
    audit: &vta_audit::SharedAuditSink,
    auth: &AuthClaims,
    subject_did: &str,
) -> Result<HolderKeys, AppError> {
    let multibase = subject_did.strip_prefix("did:key:").ok_or_else(|| {
        AppError::Validation(format!("holder subject `{subject_did}` is not a did:key"))
    })?;
    // did:key VMs are `<did>#<multibase>` (the multibase IS the did suffix).
    let key_id = format!("{subject_did}#{multibase}");

    let record: KeyRecord = keys_ks
        .get(crate::keys::store_key(&key_id))
        .await?
        .ok_or_else(|| {
            AppError::NotFound(format!(
                "holder key for `{subject_did}` is not managed by this VTA"
            ))
        })?;

    if record.key_type != KeyType::Ed25519 {
        return Err(AppError::Validation(format!(
            "holder key `{key_id}` is not an Ed25519 key"
        )));
    }
    if record.status != KeyStatus::Active {
        return Err(AppError::Validation(format!(
            "holder key `{key_id}` is not active"
        )));
    }
    if record.origin != KeyOrigin::Derived {
        return Err(AppError::Validation(
            "imported holder keys are not supported for presentation yet".into(),
        ));
    }

    // ── Privilege boundary: only sign with a key in an authorised context. ──
    match &record.context_id {
        Some(ctx) => auth.require_context(ctx)?,
        None => auth.require_super_admin()?,
    }

    // Derive through key custody (same door as the signing oracle): the
    // record's path must lie in its context's base (`vta_keys::custody` rule 6).
    let key = crate::operations::key_custody::derive_record_key(
        contexts_ks,
        keys_ks,
        &**seed_store,
        audit,
        &auth.did,
        &record,
        "holder-keys",
    )
    .await?;
    let derived_bytes = key.ed25519_signing_key_bytes()?;
    let signing_key = ed25519_dalek::SigningKey::from_bytes(&derived_bytes);

    let signer = HolderSdJwtSigner {
        key: signing_key.clone(),
        kid: key_id.clone(),
    };
    let mut consent_secret = Secret::generate_ed25519(Some(&key_id), Some(signing_key.as_bytes()));
    consent_secret.id = key_id;

    Ok(HolderKeys {
        signer,
        consent_secret,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::acl::Role;
    use affinidi_sd_jwt::signer::JwtSigner;
    use chrono::Utc;
    use vti_common::config::StoreConfig;
    use vti_common::slip10::{DerivationPath, ExtendedSigningKey};
    use vti_common::store::Store;

    fn admin_of(ctx: &str) -> AuthClaims {
        AuthClaims {
            role: Role::Admin,
            allowed_contexts: vec![ctx.to_string()],
            ..Default::default()
        }
    }
    fn super_admin() -> AuthClaims {
        AuthClaims {
            role: Role::Admin,
            allowed_contexts: Vec::new(),
            ..Default::default()
        }
    }

    /// Open a keys keyspace + seed store, derive an Ed25519 key at
    /// `m/26'/2'/0'/0'` in `context`, store its `KeyRecord`, and return the
    /// pieces plus the derived subject `did:key`.
    ///
    /// The key's context is created with base `context_base`. Pass a base that
    /// does not contain the key's path to model a planted record.
    async fn setup_with_base(context: Option<&str>, context_base: &str) -> Fixture {
        let dir = tempfile::tempdir().unwrap();
        let store = Store::open(&StoreConfig {
            data_dir: dir.path().to_path_buf(),
        })
        .unwrap();
        let keys_ks = store.keyspace(crate::keyspaces::KEYS).unwrap();
        let contexts_ks = store.keyspace(crate::keyspaces::CONTEXTS).unwrap();
        let audit =
            vta_audit::shared_keyspace_sink(store.keyspace(crate::keyspaces::AUDIT).unwrap());
        if let Some(ctx) = context {
            crate::contexts::store_context(
                &contexts_ks,
                &crate::contexts::ContextRecord {
                    id: ctx.into(),
                    name: ctx.into(),
                    did: None,
                    description: None,
                    parent: None,
                    base_path: context_base.into(),
                    index: 0,
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                    context_policy: None,
                },
            )
            .await
            .unwrap();
        }

        let seed = vec![42u8; 64];
        let seed_store: Arc<dyn SeedStore> =
            Arc::new(crate::test_support::TestSeedStore(seed.clone()));

        let path = "m/26'/2'/0'/0'";
        let bip32 = ExtendedSigningKey::from_seed(&seed).unwrap();
        let derived = bip32
            .derive(&path.parse::<DerivationPath>().unwrap())
            .unwrap();
        let subject_did = affinidi_crypto::did_key::ed25519_pub_to_did_key(
            derived.signing_key.verifying_key().as_bytes(),
        );
        let multibase = subject_did.strip_prefix("did:key:").unwrap();
        let key_id = format!("{subject_did}#{multibase}");

        let record = KeyRecord {
            exportable: None,
            key_id: key_id.clone(),
            derivation_path: path.to_string(),
            key_type: KeyType::Ed25519,
            status: KeyStatus::Active,
            public_key: multibase.to_string(),
            label: None,
            context_id: context.map(str::to_string),
            seed_id: None,
            origin: KeyOrigin::Derived,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };
        keys_ks
            .insert(crate::keys::store_key(&key_id), &record)
            .await
            .unwrap();

        Fixture {
            _dir: dir,
            _store: store,
            keys_ks,
            contexts_ks,
            audit,
            seed_store,
            subject_did,
        }
    }

    struct Fixture {
        _dir: tempfile::TempDir,
        _store: Store,
        keys_ks: KeyspaceHandle,
        contexts_ks: KeyspaceHandle,
        audit: vta_audit::SharedAuditSink,
        seed_store: Arc<dyn SeedStore>,
        subject_did: String,
    }

    async fn setup(context: Option<&str>) -> Fixture {
        setup_with_base(context, "m/26'/2'/0'").await
    }

    async fn resolve(
        f: &Fixture,
        auth: &AuthClaims,
        subject: &str,
    ) -> Result<HolderKeys, AppError> {
        resolve_holder_keys(
            &f.keys_ks,
            &f.contexts_ks,
            &f.seed_store,
            &f.audit,
            auth,
            subject,
        )
        .await
    }

    #[tokio::test]
    async fn resolves_within_an_authorised_context() {
        let f = setup(Some("acme")).await;
        let subject_did = f.subject_did.clone();
        let keys = resolve(&f, &admin_of("acme"), &subject_did)
            .await
            .expect("resolve");
        let multibase = subject_did.strip_prefix("did:key:").unwrap();
        let key_id = format!("{subject_did}#{multibase}");
        assert_eq!(keys.signer.key_id(), Some(key_id.as_str()));
        assert_eq!(keys.consent_secret.id, key_id);
    }

    #[tokio::test]
    async fn refuses_a_key_outside_the_callers_context() {
        let f = setup(Some("acme")).await;
        // The privilege boundary: an admin of `other` must NOT sign with `acme`'s key.
        let Err(err) = resolve(&f, &admin_of("other"), &f.subject_did).await else {
            panic!("expected a refusal");
        };
        assert!(matches!(err, AppError::Forbidden(_)), "{err:?}");
    }

    #[tokio::test]
    async fn parent_admin_resolves_a_descendant_context_key() {
        let f = setup(Some("acme/eng")).await;
        // Folder authority (ties to hierarchical contexts): an admin of `acme`
        // reaches a key whose context is `acme/eng`.
        assert!(resolve(&f, &admin_of("acme"), &f.subject_did).await.is_ok());
    }

    #[tokio::test]
    async fn unknown_subject_is_not_found() {
        let f = setup(Some("acme")).await;
        let Err(err) = resolve(&f, &super_admin(), "did:key:zUnknownHolder").await else {
            panic!("expected a refusal");
        };
        assert!(matches!(err, AppError::NotFound(_)), "{err:?}");
    }

    /// Key custody rule 6: a record in `acme` whose path is not under
    /// `acme`'s base (a planted record) is refused even to `acme`'s own admin.
    #[tokio::test]
    async fn a_record_outside_its_contexts_base_cannot_sign() {
        let f = setup_with_base(Some("acme"), "m/26'/2'/5'").await;
        let Err(err) = resolve(&f, &admin_of("acme"), &f.subject_did).await else {
            panic!("expected a refusal");
        };
        assert!(matches!(err, AppError::Forbidden(_)), "{err:?}");
    }
}

/// The signing material for presenting an **ISO mdoc**.
///
/// Separate from [`HolderKeys`] because an mdoc's holder is a *key*, not a DID:
/// there is no subject to resolve, and the two things that must be signed are
/// different from every other format's.
#[derive(Debug)]
pub struct MdocHolderKeys {
    /// The `did:key` the device key resolves to. Names the consent receipt's
    /// `dpv:hasDataSubject`, which must be the DID whose key signs it —
    /// `ConsentRecord::verify_proof` binds the two.
    pub device_did: String,
    /// P-256 secret, in Data-Integrity form, for signing the consent receipt
    /// under `ecdsa-jcs-2019`.
    pub consent_secret: Secret,
    /// The same key as raw SEC1 bytes, for the COSE_Sign1 `DeviceAuth` that
    /// binds the presentation to the verifier's session.
    pub device_private: Zeroizing<Vec<u8>>,
}

/// Resolve the VTA-managed **mdoc device key** named by `key_id`, gated by the
/// caller's ACL exactly as [`resolve_holder_keys`] is.
///
/// `key_id` comes off the stored credential's `MDOC_DEVICE_KEY_TAG`, recorded at
/// receive — an mdoc carries no subject DID to look one up from, and #990
/// refuses at receive any mdoc whose device key this VTA does not hold, so a
/// stored one always resolves here.
pub async fn resolve_mdoc_device_keys(
    keys_ks: &KeyspaceHandle,
    contexts_ks: &KeyspaceHandle,
    seed_store: &Arc<dyn SeedStore>,
    audit: &vta_audit::SharedAuditSink,
    auth: &AuthClaims,
    key_id: &str,
) -> Result<MdocHolderKeys, AppError> {
    let record: KeyRecord = keys_ks
        .get(crate::keys::store_key(key_id))
        .await?
        .ok_or_else(|| {
            AppError::NotFound(format!(
                "mdoc device key `{key_id}` is not managed by this VTA"
            ))
        })?;

    if record.key_type != KeyType::P256 {
        return Err(AppError::Validation(format!(
            "mdoc device key `{key_id}` is {:?}, but ISO 18013-5 device keys are P-256",
            record.key_type
        )));
    }
    if record.status != KeyStatus::Active {
        return Err(AppError::Validation(format!(
            "mdoc device key `{key_id}` is not active"
        )));
    }
    if record.origin != KeyOrigin::Derived {
        return Err(AppError::Validation(
            "imported mdoc device keys are not supported for presentation yet".into(),
        ));
    }

    // ── Privilege boundary: only sign with a key in an authorised context. ──
    // Same gate as `resolve_holder_keys`; without it a caller could present
    // another context's mdoc by naming its device key.
    match &record.context_id {
        Some(ctx) => auth.require_context(ctx)?,
        None => auth.require_super_admin()?,
    }

    let p256_secret = crate::operations::key_custody::derive_record_key(
        contexts_ks,
        keys_ks,
        &**seed_store,
        audit,
        &auth.did,
        &record,
        "holder-keys",
    )
    .await?
    .p256_secret()?;
    let device_private = Zeroizing::new(p256_secret.secret_key.to_bytes().to_vec());

    // The device key's canonical `did:key`, so the receipt has a subject that
    // resolves to the key that signed it.
    let device_did = format!("did:key:{}", record.public_key);
    let vm = format!("{device_did}#{}", record.public_key);

    let consent_secret = Secret::from_multibase(
        &vta_keys::encode_private_multibase(&KeyType::P256, &device_private),
        Some(&vm),
    )
    .map_err(|e| AppError::Internal(format!("build P-256 consent secret: {e}")))?;

    Ok(MdocHolderKeys {
        device_did,
        consent_secret,
        device_private,
    })
}