vta-sdk 0.22.0

SDK 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
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
//! DIDComm protocol for `provision-integration`.
//!
//! Carries a VP-framed [`crate::provision_integration::BootstrapRequest`]
//! to the VTA in an authcrypt'd DIDComm message; receives the sealed
//! `TemplateBootstrap` bundle back in an authcrypt'd reply.
//!
//! Auth model: DIDComm authcrypt is the auth — the VTA reads `from`
//! as the authenticated sender DID and ACL-checks it (must hold admin
//! role in the target context). The VP's `DataIntegrityProof` is the
//! second proof; both must agree (`from == VP holder`) for the
//! handler to proceed.
//!
//! Both parties exchange the same on-the-wire shapes the REST endpoint
//! at `POST /bootstrap/provision-integration` does — wire format is
//! transport-neutral. See
//! [`crate::provision_integration::http::ProvisionIntegrationRequest`]
//! and [`crate::provision_integration::http::ProvisionIntegrationResponse`].
//!
//! Two canonical Trust Task URI versions are accepted on the wire, both
//! routed to the same handler:
//!
//! * [`CANONICAL_PROVISION_INTEGRATION`] — `provision/integration/0.1`,
//!   landed in `dtgwg-trust-tasks-tf` PR #51.
//! * [`CANONICAL_PROVISION_INTEGRATION_0_2`] —
//!   `provision/integration/0.2`. Same VP/bundle wire body; the 0.2 delta
//!   is camelCase enum casing (e.g. the VP's `ask.type`), which the typed
//!   verifier accommodates by checking the proof over the bytes as
//!   received — see
//!   [`crate::provision_integration::BootstrapRequest::verify_value`].
//!
//! The handler emits the response under whichever version the request
//! came in with — a 0.1 request gets the `0.1#response` URI, a 0.2 request
//! the `0.2#response` URI — so both clients work without either knowing
//! about the other.
//!
//! The legacy `firstperson.network` provision-integration URI was retired
//! once consumers (the browser plugin, the Rust CLIs) moved to the
//! canonical registry. The other `firstperson.network` management
//! protocols are unaffected.

/// Inbound VP + provisioning options — canonical Trust Task URI, v0.1.
pub const CANONICAL_PROVISION_INTEGRATION: &str =
    "https://trusttasks.org/spec/provision/integration/0.1";

/// Outbound sealed bundle + summary — canonical Trust Task URI, v0.1.
/// Per SPEC.md §4.4.1 of `dtgwg-trust-tasks-tf`, success responses are
/// emitted under the request URI with a `#response` fragment.
pub const CANONICAL_PROVISION_INTEGRATION_RESULT: &str =
    "https://trusttasks.org/spec/provision/integration/0.1#response";

/// Inbound VP + provisioning options — canonical Trust Task URI, v0.2.
/// Same wire body as v0.1; the 0.2 spec uses camelCase enum casing
/// (notably the signed VP's `ask.type`). Verification runs over the
/// as-received bytes so the holder's casing survives.
pub const CANONICAL_PROVISION_INTEGRATION_0_2: &str =
    "https://trusttasks.org/spec/provision/integration/0.2";

/// Outbound sealed bundle + summary — canonical Trust Task URI, v0.2.
pub const CANONICAL_PROVISION_INTEGRATION_0_2_RESULT: &str =
    "https://trusttasks.org/spec/provision/integration/0.2#response";

/// Match the result URI to whichever request URI the caller used.
/// Centralised here so the routing decision lives next to the URI
/// constants — handlers downstream just call this. The 0.2 request URI
/// maps to the 0.2 `#response`; the 0.1 request URI (the only other shape
/// the router advertises) maps to the 0.1 `#response`.
pub fn result_uri_for(request_uri: &str) -> &'static str {
    if request_uri == CANONICAL_PROVISION_INTEGRATION_0_2 {
        CANONICAL_PROVISION_INTEGRATION_0_2_RESULT
    } else {
        CANONICAL_PROVISION_INTEGRATION_RESULT
    }
}

pub mod request {
    //! Body shape for the inbound DIDComm message.
    //!
    //! Equivalent to [`crate::provision_integration::http::ProvisionIntegrationRequest`]
    //! — same field semantics, same JSON layout.
    pub use crate::provision_integration::http::{AssertionMode, ProvisionIntegrationRequest};
}

pub mod result {
    //! Body shape for the reply DIDComm message.
    //!
    //! Equivalent to [`crate::provision_integration::http::ProvisionIntegrationResponse`].
    pub use crate::provision_integration::http::{ProvisionIntegrationResponse, ProvisionSummary};
}

use serde_json::Value;

use crate::provision_integration::http::{
    ProvisionIntegrationRequest, ProvisionIntegrationResponse,
};

/// Which casing convention a provision-integration body is emitted under. The
/// 0.1 wire form is snake_case fields + kebab-case `assertion`; the 0.2 form is
/// lowerCamelCase throughout, per `dtgwg-trust-tasks-tf`'s
/// `provision/integration/0.2` schema.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProvisionSpecVersion {
    V0_1,
    V0_2,
}

impl ProvisionSpecVersion {
    /// The canonical request URI to address this version at.
    pub fn request_uri(self) -> &'static str {
        match self {
            ProvisionSpecVersion::V0_1 => CANONICAL_PROVISION_INTEGRATION,
            ProvisionSpecVersion::V0_2 => CANONICAL_PROVISION_INTEGRATION_0_2,
        }
    }
}

fn is_v0_1(request_uri: &str) -> bool {
    request_uri != CANONICAL_PROVISION_INTEGRATION_0_2
}

/// `fooBarBaz` → `foo_bar_baz`. A single-word key is returned unchanged.
fn lower_camel_to_snake(key: &str) -> String {
    lower_camel_to_delimited(key, '_')
}

/// `didSigned` → `did-signed`. A single-word value is returned unchanged.
fn lower_camel_to_kebab(value: &str) -> String {
    lower_camel_to_delimited(value, '-')
}

fn lower_camel_to_delimited(s: &str, delim: char) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    for c in s.chars() {
        if c.is_ascii_uppercase() {
            out.push(delim);
            out.push(c.to_ascii_lowercase());
        } else {
            out.push(c);
        }
    }
    out
}

/// Rewrite the keys of an object in place via `lower_camel_to_snake`, leaving
/// the values untouched. Shallow on purpose: the caller decides which subtrees
/// (e.g. the signed VP) must stay byte-identical.
fn recase_object_keys_shallow(map: &mut serde_json::Map<String, Value>) {
    let renamed: Vec<(String, Value)> = std::mem::take(map)
        .into_iter()
        .map(|(k, v)| (lower_camel_to_snake(&k), v))
        .collect();
    map.extend(renamed);
}

/// Serialise a provision-integration **request** body in the casing
/// `request_uri` implies. The types now serialise the canonical 0.2
/// lowerCamelCase directly (#857), so 0.2 is the identity; for a **0.1**
/// destination the optional fields are down-cased (`vcValiditySeconds` →
/// `vc_validity_seconds`, `createContext` → `create_context`) and the
/// `assertion` value kebab-cased (`didSigned` → `did-signed`).
///
/// The signed `request` VP subtree is **never** touched — it carries the
/// holder's `DataIntegrityProof` over its exact bytes, and the holder signs
/// whatever casing it chose inside it (see [`crate::provision_integration::request`]).
pub fn request_body_for_version(
    req: &ProvisionIntegrationRequest,
    request_uri: &str,
) -> Result<Value, serde_json::Error> {
    let mut v = serde_json::to_value(req)?;
    if is_v0_1(request_uri)
        && let Value::Object(map) = &mut v
    {
        // `request` (the signed VP) is a single-word key, so the shallow
        // rename leaves both its key and value intact.
        recase_object_keys_shallow(map);
        if let Some(Value::String(a)) = map.get_mut("assertion") {
            *a = lower_camel_to_kebab(a);
        }
    }
    Ok(v)
}

/// Serialise a provision-integration **response** body in the casing
/// `request_uri` implies. 0.2 is the canonical serialization (identity); for
/// a **0.1** requester the `summary` object's keys are down-cased
/// (`clientDid` → `client_did`, `bundleIdHex` → `bundle_id_hex`, …). The
/// top-level `bundle`/`digest` are opaque single-word fields and unchanged.
pub fn response_body_for_version(
    resp: &ProvisionIntegrationResponse,
    request_uri: &str,
) -> Result<Value, serde_json::Error> {
    let mut v = serde_json::to_value(resp)?;
    if is_v0_1(request_uri)
        && let Some(Value::Object(summary)) = v.get_mut("summary")
    {
        recase_object_keys_shallow(summary);
    }
    Ok(v)
}

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

    #[test]
    fn result_uri_for_v0_1_request_emits_v0_1_response() {
        assert_eq!(
            result_uri_for(CANONICAL_PROVISION_INTEGRATION),
            CANONICAL_PROVISION_INTEGRATION_RESULT
        );
    }

    #[test]
    fn result_uri_for_v0_2_request_emits_v0_2_response() {
        assert_eq!(
            result_uri_for(CANONICAL_PROVISION_INTEGRATION_0_2),
            CANONICAL_PROVISION_INTEGRATION_0_2_RESULT
        );
    }

    /// Unknown / future URIs default to the 0.1 result URI. The router
    /// only advertises the 0.1 and 0.2 URIs, so this branch is unreachable
    /// in production — but exercising it pins the fallback so a future
    /// widening doesn't silently change the default response shape.
    #[test]
    fn result_uri_for_unknown_request_defaults_to_v0_1() {
        assert_eq!(
            result_uri_for("https://example.invalid/something-else"),
            CANONICAL_PROVISION_INTEGRATION_RESULT
        );
    }

    /// The canonical Trust Task URIs MUST be exactly the values declared
    /// in `dtgwg-trust-tasks-tf`'s `payload.schema.json` `$id`. Pin the
    /// strings so a refactor here can't drift away from the registry.
    #[test]
    fn canonical_uris_match_registry() {
        assert_eq!(
            CANONICAL_PROVISION_INTEGRATION,
            "https://trusttasks.org/spec/provision/integration/0.1"
        );
        assert_eq!(
            CANONICAL_PROVISION_INTEGRATION_RESULT,
            "https://trusttasks.org/spec/provision/integration/0.1#response"
        );
        assert_eq!(
            CANONICAL_PROVISION_INTEGRATION_0_2,
            "https://trusttasks.org/spec/provision/integration/0.2"
        );
        assert_eq!(
            CANONICAL_PROVISION_INTEGRATION_0_2_RESULT,
            "https://trusttasks.org/spec/provision/integration/0.2#response"
        );
    }

    /// The recase runs camel → snake/kebab now: the types serialise the
    /// canonical 0.2 form, so 0.1 is the direction that needs converting
    /// (#857).
    #[test]
    fn lower_camel_to_snake_and_kebab() {
        assert_eq!(lower_camel_to_snake("clientDid"), "client_did");
        assert_eq!(lower_camel_to_snake("bundleIdHex"), "bundle_id_hex");
        assert_eq!(
            lower_camel_to_snake("vcValiditySeconds"),
            "vc_validity_seconds"
        );
        assert_eq!(lower_camel_to_snake("bundle"), "bundle"); // single word
        assert_eq!(lower_camel_to_kebab("didSigned"), "did-signed");
        assert_eq!(lower_camel_to_kebab("pinnedOnly"), "pinned-only");
    }

    /// Build a real VP-framed request so the `request` subtree carries a
    /// genuine `DataIntegrityProof` — the casing helpers must leave it intact.
    async fn sample_request(
        assertion: Option<crate::provision_integration::http::AssertionMode>,
        vc_validity_seconds: Option<i64>,
        create_context: bool,
    ) -> (ProvisionIntegrationRequest, Value) {
        use crate::provision_integration::ProvisionRequestBuilder;
        let (seed, pub_bytes) = crate::sealed_transfer::generate_ed25519_keypair();
        let client_did = affinidi_crypto::did_key::ed25519_pub_to_did_key(&pub_bytes);
        let vp = ProvisionRequestBuilder::new("didcomm-mediator")
            .sign_with(&seed, &client_did)
            .await
            .expect("sign VP");
        let vp_value = serde_json::to_value(&vp).expect("serialize VP");
        let req = ProvisionIntegrationRequest {
            request: vp_value.clone(),
            context: Some("ctx".into()),
            assertion,
            vc_validity_seconds,
            create_context,
        };
        (req, vp_value)
    }

    #[tokio::test]
    async fn request_body_v0_1_stays_snake_case_and_kebab_assertion() {
        let (req, _) = sample_request(
            Some(crate::provision_integration::http::AssertionMode::DidSigned),
            Some(3600),
            true,
        )
        .await;
        let v = request_body_for_version(&req, CANONICAL_PROVISION_INTEGRATION).unwrap();
        assert_eq!(v["assertion"], "did-signed");
        assert_eq!(v["vc_validity_seconds"], 3600);
        assert_eq!(v["create_context"], true);
        assert!(v.get("vcValiditySeconds").is_none());
    }

    #[tokio::test]
    async fn request_body_v0_2_camelizes_opts_and_assertion_but_not_signed_vp() {
        let (req, vp_value) = sample_request(
            Some(crate::provision_integration::http::AssertionMode::PinnedOnly),
            Some(60),
            false,
        )
        .await;
        let v = request_body_for_version(&req, CANONICAL_PROVISION_INTEGRATION_0_2).unwrap();
        // Opt keys + assertion value camelized.
        assert_eq!(v["assertion"], "pinnedOnly");
        assert_eq!(v["vcValiditySeconds"], 60);
        assert!(v.get("vc_validity_seconds").is_none());
        // `create_context: false` is skipped on the wire (is_false) — absent.
        assert!(v.get("createContext").is_none());
        assert!(v.get("create_context").is_none());
        // Single-word keys unchanged.
        assert_eq!(v["context"], "ctx");
        // The signed VP subtree is byte-identical — the proof still covers it.
        assert_eq!(v["request"], vp_value);
    }

    /// Sign a VP the way a holder on vta-sdk < 0.21.11 does: `ask.type`
    /// PascalCase (`TemplateBootstrap`), signed over that wire form.
    ///
    /// Deliberately *not* built through [`ProvisionRequestBuilder`]. The
    /// point is a document this crate did not render — the relaying tests
    /// above compare the SDK's own serde output against itself, which is
    /// true by construction and cannot catch a relayer that re-renders
    /// what it forwards.
    async fn foreign_holder_vp() -> Value {
        use affinidi_data_integrity::{DataIntegrityProof, SignOptions};
        use affinidi_secrets_resolver::secrets::Secret;
        use base64::Engine;
        use base64::engine::general_purpose::URL_SAFE_NO_PAD as B64URL;

        let (seed, pub_bytes) = crate::sealed_transfer::generate_ed25519_keypair();
        let did = affinidi_crypto::did_key::ed25519_pub_to_did_key(&pub_bytes);
        let mb = did.strip_prefix("did:key:").expect("did:key prefix");
        let vm_id = format!("{did}#{mb}");
        let mut signer = Secret::generate_ed25519(Some(&vm_id), Some(&seed));
        signer.id = vm_id;

        let now = chrono::Utc::now();
        let mut doc = serde_json::json!({
            "@context": [
                crate::provision_integration::VC_V2_CONTEXT_URL,
                crate::provision_integration::BOOTSTRAP_CONTEXT_URL,
            ],
            "type": ["VerifiablePresentation", "BootstrapRequest"],
            "id": format!("urn:uuid:{}", uuid::Uuid::new_v4()),
            "holder": did,
            "nonce": B64URL.encode([0xF1u8; 16]),
            "validUntil": (now + chrono::Duration::hours(1)).to_rfc3339(),
            "ask": {
                "type": "TemplateBootstrap",
                "template": { "name": "didcomm-mediator", "vars": {} }
            }
        });
        let proof = DataIntegrityProof::sign(
            &doc,
            &signer,
            SignOptions::new()
                .with_proof_purpose("authentication")
                .with_created(now),
        )
        .await
        .expect("sign foreign VP");
        doc.as_object_mut()
            .unwrap()
            .insert("proof".into(), serde_json::to_value(&proof).unwrap());
        doc
    }

    #[tokio::test]
    async fn a_foreign_holders_vp_is_relayed_byte_for_byte() {
        let vp = foreign_holder_vp().await;

        // Guard against this test going vacuous. It only proves anything
        // while the SDK's rendering of the document differs from the
        // document — if the two ever converge, the assertions below pass
        // for the wrong reason and the fixture needs a new divergence.
        let round_tripped = serde_json::to_value(
            serde_json::from_value::<crate::provision_integration::BootstrapRequest>(vp.clone())
                .expect("foreign VP parses"),
        )
        .expect("re-serialize");
        assert_ne!(
            round_tripped, vp,
            "fixture no longer diverges from this crate's serde output"
        );

        for uri in [
            CANONICAL_PROVISION_INTEGRATION,
            CANONICAL_PROVISION_INTEGRATION_0_2,
        ] {
            let req = ProvisionIntegrationRequest {
                request: vp.clone(),
                context: Some("ctx".into()),
                assertion: None,
                vc_validity_seconds: None,
                create_context: false,
            };
            let body = request_body_for_version(&req, uri).expect("build body");
            assert_eq!(
                body["request"], vp,
                "relaying under {uri} altered the holder's signed document"
            );
            // The end the relayer is talking to must still be able to
            // verify it — the whole reason the bytes matter.
            crate::provision_integration::BootstrapRequest::verify_value(body["request"].clone())
                .expect("relayed VP still verifies");
        }
    }

    #[test]
    fn response_body_v0_1_stays_snake_case_v0_2_camelizes_summary() {
        let resp = ProvisionIntegrationResponse {
            bundle: "armored".into(),
            digest: "deadbeef".into(),
            summary: crate::provision_integration::http::ProvisionSummary {
                client_did: "did:key:zClient".into(),
                admin_did: "did:key:zAdmin".into(),
                admin_rolled_over: true,
                integration_did: Some("did:webvh:x".into()),
                template_name: Some("tmpl".into()),
                template_kind: Some("kind".into()),
                admin_template_name: None,
                bundle_id_hex: "abc".into(),
                secret_count: 2,
                output_count: 1,
                webvh_server_id: None,
                context_created: true,
            },
        };
        // 0.1 — snake_case preserved.
        let v01 = response_body_for_version(&resp, CANONICAL_PROVISION_INTEGRATION).unwrap();
        assert_eq!(v01["summary"]["client_did"], "did:key:zClient");
        assert_eq!(v01["summary"]["bundle_id_hex"], "abc");
        assert!(v01["summary"].get("clientDid").is_none());
        // 0.2 — summary keys camelized; values and opaque bundle/digest intact.
        let v02 = response_body_for_version(&resp, CANONICAL_PROVISION_INTEGRATION_0_2).unwrap();
        assert_eq!(v02["summary"]["clientDid"], "did:key:zClient");
        assert_eq!(v02["summary"]["bundleIdHex"], "abc");
        assert_eq!(v02["summary"]["secretCount"], 2);
        assert_eq!(v02["summary"]["adminRolledOver"], true);
        assert_eq!(v02["summary"]["contextCreated"], true);
        assert!(v02["summary"].get("client_did").is_none());
        assert_eq!(v02["bundle"], "armored");
        assert_eq!(v02["digest"], "deadbeef");
    }
}