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
//! Key + seed management methods on [`VtaClient`].
use super::{
CreateKeyRequest, CreateKeyResponse, GetKeySecretResponse, ImportKeyRequest, ImportKeyResponse,
InvalidateKeyResponse, ListKeysResponse, ListSeedsResponse, RenameKeyResponse,
RotateSeedRequest, RotateSeedResponse, SignResponse, Transport, VtaClient, WrappingKeyResponse,
};
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).
// `internal` and `derivation_path` are forwarded, not dropped.
//
// `internal` was hardcoded `None` here while `CreateKeyRequest::internal`
// was never read, so `pnm keys create --internal` printed its whole
// non-recoverable-key warning, made the operator type "i understand this
// key cannot be recovered", and then minted an ordinary derived key —
// one that *is* in backups and *is* exportable. The operator was told
// the opposite of what happened.
//
// `derivation_path` was `unwrap_or_default()`, sending `""` for absent.
// The operation layer reads `""` as absent, so it worked; but the wire
// then carried a member the caller never set, and the empty string is
// meaningless to any other maintainer.
let body = crate::protocols::key_management::create::CreateKeyBody {
internal: req.internal,
key_id: req.key_id.clone(),
key_type: req.key_type.clone(),
derivation_path: req.derivation_path.clone(),
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,
)
.await?;
let key = wrapped.key;
Ok(CreateKeyResponse {
origin: key.origin,
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,
)
.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,
)
.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,
)
.await?;
wrapped
.key
.ok_or_else(|| VtaError::NotFound(format!("no key record for `{key_id}`")))
}
/// Export one key's private half.
///
/// `keys/export-secret/0.1`. This used to dispatch
/// `vta/seeds/export-mnemonic/1.0`, which exported no mnemonic and no seed
/// — a per-key secret export wearing the name of the thing it was migrated
/// from, in the wrong family, with no published spec, and gated on **global
/// Admin** so that wanting one key meant holding authority over every other
/// context in the VTA. The replacement is admin of the key's own scope.
///
/// The response is private key material in the clear: never log it, never
/// cache it in a shared store, never put it in a diagnostic bundle.
pub async fn get_key_secret(&self, key_id: &str) -> Result<GetKeySecretResponse, VtaError> {
self.rpc_tt(
trust_tasks::TASK_KEYS_EXPORT_SECRET_0_1,
serde_json::to_value(crate::protocols::key_management::secret::GetKeySecretBody {
key_id: key_id.to_string(),
})?,
30,
)
.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,
)
.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)
.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> {
// Built from the canonical body, not a hand-rolled map. The map spelled
// `proofPurpose` unconditionally, so an unset purpose went on the wire
// as `null` and `keys/derive-and-sign-document/0.1` — which types it
// `"string"` — rejected the request. Omitting the member is what
// selects the `assertionMethod` default, so the *documented* way to
// call this was the one that could not work. Same defect as #919's
// `keys/create`, and the same fix: let the body struct's
// `skip_serializing_if` decide what reaches the wire.
let body = serde_json::to_value(
crate::protocols::key_management::derive_and_sign_document::DeriveAndSignDocumentBody {
key_type,
derivation_path: derivation_path.to_string(),
document,
proof_purpose: proof_purpose.map(str::to_string),
},
)?;
self.rpc_tt(
trust_tasks::TASK_KEYS_DERIVE_AND_SIGN_DOCUMENT_0_1,
body.clone(),
30,
)
.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,
)
.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,
)
.await
}
/// Set whether a key's private half may be released.
///
/// `exportable` is the state the key should be in afterwards, **not a
/// delta**, so a retry of a lost `false` lands on `false` rather than
/// toggling back. There is deliberately no toggle form.
///
/// The two directions do not cost the same. Imposing the restriction needs
/// admin of the key's context; lifting it needs strictly more — super-admin
/// or a live step-up. A restriction the party who imposed it can lift
/// unilaterally protects against accident but not against a compromised
/// caller holding that party's credentials, which is the case it exists for.
pub async fn set_key_exportability(
&self,
key_id: &str,
exportable: bool,
) -> Result<
crate::protocols::key_management::set_exportability::SetKeyExportabilityResultBody,
VtaError,
> {
self.rpc_tt(
trust_tasks::TASK_KEYS_SET_EXPORTABILITY_0_1,
serde_json::json!({ "keyId": key_id, "exportable": exportable }),
30,
)
.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)
.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,
)
.await
}
}
#[cfg(all(test, feature = "test-loopback", feature = "client"))]
mod exportability_tests {
use crate::client::loopback::RecordingSink;
use std::sync::Arc;
/// The producer side of `keys/set-exportability`: the URI it dispatches and
/// the body it builds.
///
/// Worth pinning because this method is the only way an operator can reach
/// the task — the VTA served it for a release with no client and no CLI, so
/// nothing would have noticed a wrong URI here.
#[tokio::test]
async fn it_sends_the_state_absolutely_under_the_right_uri() {
let sink = Arc::new(RecordingSink::new());
let client = crate::client::VtaClient::loopback(sink.clone());
// The response will not deserialize from `null`; the request was
// captured before that, which is what this test is asking about.
let _ = client.set_key_exportability("app-signing-key", false).await;
let (uri, payload) = sink.recorded().pop().expect("one task was dispatched");
assert_eq!(uri, crate::trust_tasks::TASK_KEYS_SET_EXPORTABILITY_0_1);
assert_eq!(payload["keyId"], "app-signing-key");
assert_eq!(
payload["exportable"], false,
"a boolean, not a string: `\"false\"` is truthy in several languages \
and would invert the request"
);
assert!(
payload.get("toggle").is_none(),
"the state is absolute — a toggle would make a retried request undo itself"
);
}
/// The other direction reaches the same task. It is the one the VTA gates
/// harder, and a client that spelled it differently would fail at the far
/// end rather than here.
#[tokio::test]
async fn releasing_uses_the_same_task() {
let sink = Arc::new(RecordingSink::new());
let client = crate::client::VtaClient::loopback(sink.clone());
let _ = client.set_key_exportability("app-signing-key", true).await;
let (uri, payload) = sink.recorded().pop().expect("one task was dispatched");
assert_eq!(uri, crate::trust_tasks::TASK_KEYS_SET_EXPORTABILITY_0_1);
assert_eq!(payload["exportable"], true);
}
}