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
//! Key + seed management methods on [`VtaClient`].
use super::{
CreateKeyRequest, CreateKeyResponse, GetKeySecretResponse, ImportKeyRequest, ImportKeyResponse,
InvalidateKeyResponse, ListKeysResponse, ListSeedsResponse, RenameKeyRequest,
RenameKeyResponse, RotateSeedRequest, RotateSeedResponse, SignResponse, Transport, VtaClient,
WrappingKeyResponse, encode_path_segment,
};
use crate::error::VtaError;
use crate::keys::{KeyRecord, KeyType};
use crate::protocols::key_management::derive_and_sign::DeriveAndSignResultBody;
use crate::protocols::key_management::derive_and_sign_document::DeriveAndSignDocumentResultBody;
use crate::protocols::key_management::sign::SignAlgorithm;
use crate::trust_tasks;
#[cfg(feature = "client")]
impl VtaClient {
// ── Key methods ─────────────────────────────────────────────────
/// Create a key.
///
/// Trust-task leg note: `spec/vta/keys/create/1.0` auto-generates the
/// key id from the derivation path, so an explicit `req.key_id` only
/// takes effect on the REST leg — exactly as it did on the legacy
/// DIDComm message, which never carried `key_id` either.
pub async fn create_key(&self, req: CreateKeyRequest) -> Result<CreateKeyResponse, VtaError> {
// Built from the canonical body rather than a hand-rolled map: the map
// spelled its members snake_case and carried `mnemonic` before the
// registry had a member for it, so it was one rename away from
// silently dropping the create-from-a-phrase path (see #884's
// `update_acl`, the same failure with different members).
let body = crate::protocols::key_management::create::CreateKeyBody {
key_type: req.key_type.clone(),
derivation_path: req.derivation_path.clone().unwrap_or_default(),
mnemonic: req.mnemonic.clone(),
label: req.label.clone(),
context_id: req.context_id.clone(),
};
let wrapped: crate::protocols::key_management::create::CreateKeyResponseBody = self
.rpc_tt(
trust_tasks::TASK_KEYS_CREATE_0_1,
serde_json::to_value(&body)?,
30,
|c, url| c.post(format!("{url}/keys")).json(&req),
)
.await?;
let key = wrapped.key;
Ok(CreateKeyResponse {
key_id: key.key_id,
key_type: key.key_type,
derivation_path: key.derivation_path,
public_key: key.public_key,
status: key.status,
label: key.label,
created_at: key.created_at,
})
}
/// Import an externally-created private key.
///
/// Canonical `keys/import/0.1` on **every** transport. The carrier is a
/// confidentiality decision the VTA enforces rather than a formatting one:
/// `private_key_sealed` and `private_key_jwe` encrypt to the VTA and are
/// accepted anywhere, while the cleartext `private_key_multibase` is
/// accepted only where the transport is confidential end-to-end — DIDComm
/// and TSP — and refused over REST, whose TLS terminates wherever the
/// operator terminates it.
///
/// The multibase carrier used to fork onto the legacy
/// `key-management/1.0/import-key` message here. That was dead: the VTA has
/// never routed that type, so the call failed with `unsupported message
/// type` on DIDComm and was refused outright on REST. It works now.
pub async fn import_key(&self, req: ImportKeyRequest) -> Result<ImportKeyResponse, VtaError> {
let body = crate::protocols::key_management::import::ImportKeyBody {
key_type: req.key_type.clone(),
private_key_sealed: req.private_key_sealed.clone(),
private_key_jwe: req.private_key_jwe.clone(),
private_key_multibase: req.private_key_multibase.clone(),
label: req.label.clone(),
context_id: req.context_id.clone(),
};
let wrapped: crate::protocols::key_management::create::CreateKeyResponseBody = self
.rpc_tt(
trust_tasks::TASK_KEYS_IMPORT_0_1,
serde_json::to_value(&body)?,
30,
|c, url| c.post(format!("{url}/keys/import")).json(&req),
)
.await?;
Ok(ImportKeyResponse {
key_id: wrapped.key.key_id,
key_type: wrapped.key.key_type,
public_key: wrapped.key.public_key,
status: wrapped.key.status,
label: wrapped.key.label,
origin: wrapped.key.origin,
created_at: wrapped.key.created_at,
})
}
pub async fn list_keys(
&self,
offset: u64,
limit: u64,
status: Option<&str>,
context_id: Option<&str>,
) -> Result<ListKeysResponse, VtaError> {
self.rpc_tt(
trust_tasks::TASK_KEYS_LIST_0_1,
serde_json::to_value(crate::protocols::key_management::list::ListKeysBody {
offset: Some(offset),
limit: Some(limit),
status: status
.map(str::to_string)
.and_then(|s| serde_json::from_value(serde_json::Value::String(s)).ok()),
context_id: context_id.map(str::to_string),
})?,
30,
|c, url| {
let mut u = format!("{url}/keys?offset={offset}&limit={limit}");
if let Some(s) = status {
u.push_str(&format!("&status={s}"));
}
if let Some(ctx) = context_id {
u.push_str(&format!("&context_id={ctx}"));
}
c.get(u)
},
)
.await
}
pub async fn get_key(&self, key_id: &str) -> Result<KeyRecord, VtaError> {
// Canonical `keys/show/0.1` answers `{ key }`, with `key: null` for a
// key the maintainer does not hold — a successful answer, not an error.
// This method promises a record, so absence becomes `NotFound` here
// rather than a decode failure the caller cannot interpret.
let wrapped: crate::protocols::key_management::get::GetKeyResponseBody = self
.rpc_tt(
trust_tasks::TASK_KEYS_SHOW_0_1,
serde_json::json!({ "keyId": key_id }),
30,
|c, url| c.get(format!("{url}/keys/{}", encode_path_segment(key_id))),
)
.await?;
wrapped
.key
.ok_or_else(|| VtaError::NotFound(format!("no key record for `{key_id}`")))
}
/// Export a key's secret material. The trust-task twin lives in the
/// seeds slice (`spec/vta/seeds/export-mnemonic/1.0`) — same
/// `{ key_id }` request and the same
/// `operations::keys::get_key_secret` spine as the legacy message.
pub async fn get_key_secret(&self, key_id: &str) -> Result<GetKeySecretResponse, VtaError> {
self.rpc_tt(
trust_tasks::TASK_SEEDS_EXPORT_MNEMONIC_1_0,
serde_json::json!({ "key_id": key_id }),
30,
|c, url| c.get(format!("{url}/keys/{}/secret", encode_path_segment(key_id))),
)
.await
}
/// Sign a payload using a VTA-managed key.
///
/// Sends the base64url-encoded payload to the VTA, which derives the key,
/// signs in memory, and returns the signature. Key material never leaves VTA.
pub async fn sign(
&self,
key_id: &str,
payload: &[u8],
algorithm: SignAlgorithm,
) -> Result<SignResponse, VtaError> {
use base64::Engine;
let payload_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload);
self.rpc_tt(
trust_tasks::TASK_KEYS_SIGN_0_1,
serde_json::json!({
"keyId": key_id,
"payload": payload_b64,
"algorithm": algorithm,
}),
30,
|c, url| {
c.post(format!("{url}/keys/{}/sign", encode_path_segment(key_id)))
.json(&serde_json::json!({
"payload": payload_b64,
"algorithm": algorithm,
}))
},
)
.await
}
/// Ephemerally derive a key at `derivation_path` and sign `payload` —
/// **without persisting a key record**. Admin-only on the VTA. Returns the
/// derived public key + signature.
///
/// This is how a client (e.g. a fleet manager whose fleet seed *is* this
/// VTA's seed) acts as a derived child identity — e.g. a per-VTA super-admin
/// at `m/26'/9'/<idx>'` — so the seed never leaves the VTA. REST:
/// `POST /keys/derive-and-sign`; DIDComm: the `keys/derive-and-sign/1.0`
/// trust task.
pub async fn derive_and_sign(
&self,
key_type: KeyType,
derivation_path: &str,
payload: &[u8],
algorithm: SignAlgorithm,
) -> Result<DeriveAndSignResultBody, VtaError> {
use base64::Engine;
let payload_b64 = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(payload);
let body = serde_json::json!({
"keyType": serde_json::to_value(&key_type)?,
"derivationPath": derivation_path,
"payload": payload_b64,
"algorithm": algorithm,
});
self.rpc_tt(
trust_tasks::TASK_KEYS_DERIVE_AND_SIGN_0_1,
body.clone(),
30,
move |c, url| c.post(format!("{url}/keys/derive-and-sign")).json(&body),
)
.await
}
/// Derive a key at `derivation_path` and attach an `eddsa-jcs-2022`
/// Data-Integrity proof to `document`, signed **as the derived key** —
/// persisting no key record. Admin-only. Returns the signer `did:key` + the
/// signed document. This is how a fleet manager has its fleet VTA sign an
/// auth document as a per-VTA super-admin without the seed leaving the VTA.
pub async fn derive_and_sign_document(
&self,
key_type: KeyType,
derivation_path: &str,
document: serde_json::Value,
proof_purpose: Option<&str>,
) -> Result<DeriveAndSignDocumentResultBody, VtaError> {
let body = serde_json::json!({
"keyType": serde_json::to_value(&key_type)?,
"derivationPath": derivation_path,
"document": document,
"proofPurpose": proof_purpose,
});
self.rpc_tt(
trust_tasks::TASK_KEYS_DERIVE_AND_SIGN_DOCUMENT_0_1,
body.clone(),
30,
move |c, url| {
c.post(format!("{url}/keys/derive-and-sign-document"))
.json(&body)
},
)
.await
}
pub async fn invalidate_key(&self, key_id: &str) -> Result<InvalidateKeyResponse, VtaError> {
self.rpc_tt(
trust_tasks::TASK_KEYS_REVOKE_0_1,
serde_json::json!({ "keyId": key_id }),
30,
|c, url| c.delete(format!("{url}/keys/{}", encode_path_segment(key_id))),
)
.await
}
pub async fn rename_key(
&self,
key_id: &str,
new_key_id: &str,
) -> Result<RenameKeyResponse, VtaError> {
self.rpc_tt(
trust_tasks::TASK_KEYS_RENAME_0_1,
serde_json::json!({ "keyId": key_id, "newKeyId": new_key_id }),
30,
|c, url| {
c.patch(format!("{url}/keys/{}", encode_path_segment(key_id)))
.json(&RenameKeyRequest {
key_id: new_key_id.to_string(),
})
},
)
.await
}
// ── Import key methods ──────────────────────────────────────────
/// Fetch an ephemeral wrapping key for REST key import.
pub async fn get_wrapping_key(&self) -> Result<WrappingKeyResponse, VtaError> {
match &self.transport {
Transport::Rest {
client,
base_url,
auth,
} => {
Self::ensure_token_valid(client, base_url, auth).await?;
let token = auth.lock().await.token.clone();
let req = client.get(format!("{base_url}/keys/import/wrapping-key"));
let resp = Self::with_auth_token(req, &token).send().await?;
Self::handle_response(resp).await
}
#[cfg(feature = "session")]
Transport::DIDComm { .. } => Err(VtaError::UnsupportedTransport(
"wrapping key not needed for DIDComm transport".into(),
)),
#[cfg(feature = "tsp")]
Transport::Tsp { .. } => Err(VtaError::UnsupportedTransport(
"wrapping key not needed for TSP transport".into(),
)),
}
}
// ── Seed methods ────────────────────────────────────────────────
pub async fn list_seeds(&self) -> Result<ListSeedsResponse, VtaError> {
self.rpc_tt(
trust_tasks::TASK_SEEDS_LIST_1_0,
serde_json::json!({}),
30,
|c, url| c.get(format!("{url}/keys/seeds")),
)
.await
}
pub async fn rotate_seed(
&self,
mnemonic: Option<String>,
) -> Result<RotateSeedResponse, VtaError> {
let body = RotateSeedRequest {
mnemonic: mnemonic.clone(),
};
self.rpc_tt(
trust_tasks::TASK_SEEDS_ROTATE_1_0,
serde_json::json!({ "mnemonic": mnemonic }),
30,
|c, url| c.post(format!("{url}/keys/seeds/rotate")).json(&body),
)
.await
}
}